问:
Could not initialize class on App Engine, works on dev_appserver
While trying to find the cause of a larger bug, I found that class org.apache.commons.vfs2.util.Os from Commons-VFS cannot be initialized on App Engine. But it works on dev_appserver. This minimum maven javaee7 app with the following files  demonstrates the problem:

src/main/java/org/example/SampleServlet.java

```<code>package org.example;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.vfs2.util.Os;

public class SampleServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Os.isArch(""); // java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.vfs2.util.Os

        resp.getOutputStream().print("Hello world");
    }
}
</code>```

src/main/java/org/apache/commons/vfs2/util/Os.java

Get from here

src/main/java/org/apache/commons/vfs2/util/OsFamily.java

Get from here

src/main/webapp/WEB-INF/web.xml

```<code><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <servlet>
        <servlet-name>sample-servlet</servlet-name>
        <servlet-class>org.example.SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sample-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

src/main/webapp/WEB-INF/appengine-web.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>redacted</application>
    <version>1</version>
    <threadsafe>true</threadsafe>
</appengine-web-app>
</code>```

pom.xml

```<code><?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>org.example</groupId>
    <artifactId>webapp-javaee7</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>webapp-javaee7</name>

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

    <dependencies>
        <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>

</project>
</code>```

Deploy with mvn clean install && appcfg.sh --oauth2 update target/webapp-javaee7-1.0-SNAPSHOT/

The error I get:

```<code>Error for /
java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.vfs2.util.Os
    at org.example.SampleServlet.doGet(SampleServlet.java:13)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:266)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:146)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:188)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)
C 2014-04-13 17:29:50.430
Uncaught exception from servlet
java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.vfs2.util.Os
    at org.example.SampleServlet.doGet(SampleServlet.java:13)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:266)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:146)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:188)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)
</code>```

It also works if I delete everything in org/apache/commons/vfs2/util/Os.java and change it to this:

```<code>package org.apache.commons.vfs2.util;

public final class Os
{
    public static boolean isArch(final String arch)
    {
        return false;
    }
}
</code>```

Is this a bug in App Engine or does the class org.apache.commons.vfs2.util.Os have something that makes it unacceptable for App Engine?

答:
if you have changed the JDK in your project to jDK 1.8.Then, add the following tag to appengine-web.xml :-

<runtime>java8</runtime>

Body:
While trying to find the cause of a larger bug, I found that class org.apache.commons.vfs2.util.Os from Commons-VFS cannot be initialized on App Engine. But it works on dev_appserver. This minimum maven javaee7 app with the following files  demonstrates the problem:

src/main/java/org/example/SampleServlet.java

package org.example;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.vfs2.util.Os;

public class SampleServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Os.isArch(""); // java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.vfs2.util.Os

        resp.getOutputStream().print("Hello world");
    }
}

src/main/java/org/apache/commons/vfs2/util/Os.java

Get from here

src/main/java/org/apache/commons/vfs2/util/OsFamily.java

Get from here

src/main/webapp/WEB-INF/web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">
    <servlet>
        <servlet-name>sample-servlet</servlet-name>
        <servlet-class>org.example.SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sample-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

src/main/webapp/WEB-INF/appengine-web.xml

<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
    <application>redacted</application>
    <version>1</version>
    <threadsafe>true</threadsafe>
</appengine-web-app>

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>org.example</groupId>
    <artifactId>webapp-javaee7</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>webapp-javaee7</name>

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

    <dependencies>
        <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>

</project>

Deploy with mvn clean install && appcfg.sh --oauth2 update target/webapp-javaee7-1.0-SNAPSHOT/

The error I get:

Error for /
java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.vfs2.util.Os
    at org.example.SampleServlet.doGet(SampleServlet.java:13)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:266)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:146)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:188)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)
C 2014-04-13 17:29:50.430
Uncaught exception from servlet
java.lang.NoClassDefFoundError: Could not initialize class org.apache.commons.vfs2.util.Os
    at org.example.SampleServlet.doGet(SampleServlet.java:13)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.JdbcMySqlConnectionCleanupFilter.doFilter(JdbcMySqlConnectionCleanupFilter.java:60)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:266)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:146)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:446)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:188)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:251)
    at java.lang.Thread.run(Thread.java:724)

It also works if I delete everything in org/apache/commons/vfs2/util/Os.java and change it to this:

package org.apache.commons.vfs2.util;

public final class Os
{
    public static boolean isArch(final String arch)
    {
        return false;
    }
}

Is this a bug in App Engine or does the class org.apache.commons.vfs2.util.Os have something that makes it unacceptable for App Engine?


来源: stackexchange

问:
@font-face with multiple files looks different in Firefox and Chrome
I've css for Custom Arial font face for regular, bold, italic and bold-italic style.

And for that all different font files are created arial_mt_stdregular, arial_mt_stdbold, arial_mt_stditalic and arial_mt_stdbold_italic

```<code>#span{
    font-family: 'arial_mt_stditalic';
    font-style: italic;
    font-size: 30px;
}
</code>```

In Firefox, this apply italic style twice as Chrome and IE.

So my content looks twice italic and twice bold in FireFox than Chrome and IE.

```<code>@font-face {
    font-family: 'arial_mt_stdregular';
    src: url('arialmtstd-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'arial_mt_stdbold';
    src: url('arialmtstd-bold-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
 }

@font-face {
    font-family: 'arial_mt_stditalic';
    src: url('arialmtstd-italic-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'arial_mt_stdbold_italic';
    src: url('arialmtstd-bolditalic-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}
</code>```

sample from FF and Chrome

Why Chrome and IE not applied font-style:italic for "arial_mt_stditalic" font?

答:
I suspect this is browsers trying to simulate italics when you've provided an italic font but told the browser it isn't italic.

When applying the font you have:

```<code>font-family: 'arial_mt_stditalic';
font-style: italic;
</code>```

But in the single @font-face for rial_mt_stditalic you have

```<code>font-style: normal;
</code>```

Ie. you have told the browser to use a non-italic typeface as italic.

All the @font-face definitions should have the same value for font-family, and the other properties then tell the browser what variant, weight, etc. that particular download is.

When you use that font-family the browser matches on the other properties to select the download.

Ie. you should have:

```<code>#span{
    font-family: 'arial mt';
    font-style: italic;
    font-size: 30px;
}

@font-face {
    font-family: 'arial mt';
    src: url('arialmtstd-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'arial mt';
    src: url('arialmtstd-bold-webfont.woff2') format('woff2');
    font-weight: bold;
    font-style: normal;
 }

@font-face {
    font-family: 'arial mt';
    src: url('arialmtstd-italic-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: italic;
}

// etc.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've css for Custom Arial font face for regular, bold, italic and bold-italic style.

And for that all different font files are created arial_mt_stdregular, arial_mt_stdbold, arial_mt_stditalic and arial_mt_stdbold_italic

#span{
    font-family: 'arial_mt_stditalic';
    font-style: italic;
    font-size: 30px;
}

In Firefox, this apply italic style twice as Chrome and IE.

So my content looks twice italic and twice bold in FireFox than Chrome and IE.

@font-face {
    font-family: 'arial_mt_stdregular';
    src: url('arialmtstd-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'arial_mt_stdbold';
    src: url('arialmtstd-bold-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
 }

@font-face {
    font-family: 'arial_mt_stditalic';
    src: url('arialmtstd-italic-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'arial_mt_stdbold_italic';
    src: url('arialmtstd-bolditalic-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}

sample from FF and Chrome

Why Chrome and IE not applied font-style:italic for "arial_mt_stditalic" font?

Body:
I suspect this is browsers trying to simulate italics when you've provided an italic font but told the browser it isn't italic.

When applying the font you have:

font-family: 'arial_mt_stditalic';
font-style: italic;

But in the single @font-face for rial_mt_stditalic you have

font-style: normal;

Ie. you have told the browser to use a non-italic typeface as italic.

All the @font-face definitions should have the same value for font-family, and the other properties then tell the browser what variant, weight, etc. that particular download is.

When you use that font-family the browser matches on the other properties to select the download.

Ie. you should have:

#span{
    font-family: 'arial mt';
    font-style: italic;
    font-size: 30px;
}

@font-face {
    font-family: 'arial mt';
    src: url('arialmtstd-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'arial mt';
    src: url('arialmtstd-bold-webfont.woff2') format('woff2');
    font-weight: bold;
    font-style: normal;
 }

@font-face {
    font-family: 'arial mt';
    src: url('arialmtstd-italic-webfont.woff2') format('woff2');
    font-weight: normal;
    font-style: italic;
}

// etc.


问:
Find remaining memory available to a process in 32 bit Linux using C++
My C++ program caches lots of objects, and in beginning of each major API call, I want to ensure that there is at least 500 MB available for the API call. I may either be running out of RAM+swap space (consider system with 1 GB RAM + 1 GB SWAP file), or I may be running out of Virtual Address in my process.(I may already be using 3.7 GB out of total 4GB address space). It's not easy for me to approximate how much data I have cached, but I can purge some of it if it is becoming an issue, and do so iteratively till I have 500 MB available in system or address space (whichever is becoming bottleneck). So my requirements are to find in C++ on 32 bit Linux:

A) Find how much RAM + SWAP space is free.

B) How much user space address space is available to my process.

C) How much Virtual Memory the process is already using. Consider it similar to 'Commit Size' or 'Working Set Size' of a process on Windows.

Any answers would be greatly appreciated.

答:
Look at /proc/vmstat there is a  lot of information about the system wide memory.

The /proc//maps will give you a lot of information about your process memory layout.

Note that if you check the memory before running a long job, another process may eat all the available memory and your program may crash anyway !

I do not know anything about your cached classes but if these objects are quite small you probably have overridden the new/delete operators. By this it is quite easy to keep track of the memory consumption (at least by counting objects)
Why not change your cache policy ? And flush old unused object.

Another ugly way is to try to allocate several chunk of memory and see the program can allocate it, and release it after that. On 32 bits it may fail because the heap may be fragmented, but if it works you sure that you have enough memory at this time.

ContentLicense: CC BY-SA 2.5


问:
How to store in file outputs of a c/c++ program in unix
I have a program made on c++, let's call it program, which has a lot of output while running. I want to log that output on a file so is easier then to look at it. I tried already ./program & > file ./program & |tee file but it doesnt work (I want to run it in background if posible).

any idea?

Thanks

EDIT: It doesnt work ./program > file. I tried putting it on background, on foreground, but the file is empty....

答: If you want to redirect stdout and put the program to background use (./program > file)&


问:
Crashlytics with Hello Jni App
I got some issues with crashlytics. I think I cannot set crashlytics androidNdkOut and androidNdkLibsOut paths.

First question is what is gradle's default output path for ndk according to the this gradle settings ?
Second if settings are correct why I saw my ndk errors as "???" on Crashlytics dashboard?

Here is my app build.gradle

```<code>    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        classpath 'io.fabric.tools:gradle:1.21.7'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Here is my module's build.gradle:

```<code>apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 24
    buildToolsVersion '23.0.3'
    defaultConfig {
        applicationId "com.test.crashlyticsndktest"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            moduleName "crashlytics-jni"
            abiFilters "armeabi"
            cFlags "-g"
        }
    }

}

crashlytics {
    enableNdk=true
    androidNdkOut getProjectDir().absolutePath +'/build/intermediates/ndk/debug/lib'
    //androidNdkOut "src/main/obj"
    androidNdkLibsOut getProjectDir().absolutePath + "/build/intermediates/ndk/debug/obj/local"
    //androidNdkLibsOut "src/main/jniLibs"

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    testCompile 'junit:junit:4.12'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.5@aar') { transitive = true; }
}
</code>```

Here is my proguard file:

```<code>-keep public class * extends java.lang.Exception
-keep class com.crashlytics.** { *; }
-dontwarn com.crashlytics.**
-keepattributes SourceFile,LineNumberTable,Annotation
-keep class com.crashlytics.android.**
</code>```

and here is my Activity's Fabric code:

```<code>Fabric.with(this, new Crashlytics(),new CrashlyticsNdk());
</code>```

答:
Matt here from the Fabric team!

I wanted to let you know that we've just released version 1.23.0 of the Fabric plugin for Gradle which supports automatically resolving the appropriate native library paths when you're using the Android Gradle plugin 2.2.0+ with the externalNativeBuild DSL, so you no longer have to set androidNdkOut and androidNdkLibsOut if you're using the latest Android Gradle plugin. That should help you get your NDK symbols uploaded correctly and improve your stack traces!

Title: Crashlytics with Hello Jni App

Body:
I got some issues with crashlytics. I think I cannot set crashlytics androidNdkOut and androidNdkLibsOut paths.

First question is what is gradle's default output path for ndk according to the this gradle settings ?
Second if settings are correct why I saw my ndk errors as "???" on Crashlytics dashboard?

Here is my app build.gradle

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0'
        classpath 'io.fabric.tools:gradle:1.21.7'
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.fabric.io/public' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Here is my module's build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
    compileSdkVersion 24
    buildToolsVersion '23.0.3'
    defaultConfig {
        applicationId "com.test.crashlyticsndktest"
        minSdkVersion 15
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            moduleName "crashlytics-jni"
            abiFilters "armeabi"
            cFlags "-g"
        }
    }

}

crashlytics {
    enableNdk=true
    androidNdkOut getProjectDir().absolutePath +'/build/intermediates/ndk/debug/lib'
    //androidNdkOut "src/main/obj"
    androidNdkLibsOut getProjectDir().absolutePath + "/build/intermediates/ndk/debug/obj/local"
    //androidNdkLibsOut "src/main/jniLibs"

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    testCompile 'junit:junit:4.12'
    compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.5@aar') { transitive = true; }
}

Here is my proguard file:

-keep public class * extends java.lang.Exception
-keep class com.crashlytics.** { *; }
-dontwarn com.crashlytics.**
-keepattributes SourceFile,LineNumberTable,Annotation
-keep class com.crashlytics.android.**

and here is my Activity's Fabric code:

Fabric.with(this, new Crashlytics(),new CrashlyticsNdk());


问:
How can hide the textbox on basis on checkbox in JSP
In my JSP page two fields one is textbox and one is checkbox, I tried with     j query and java script also for hiding the textbox on checked of checkbox but it is not reflecting. Below I am mentioning code here

```<code><p class="contact"> <input id="check" name="check" value="check" style="margin-right: 10px" type="checkbox" tabindex="11">
        <label for="name"> Not Yet Registered</label> </p>

        <p class= "reg"><label for="reg">Register No.</label></p><br>
        <input id = "reg" maxlength="15"  name= "reg" placeholder="Reg No." type ="text" tabindex="12"><br><br>
</code>```

J query

```<code>$('#check').click(function() {
  $('.reg')[this.checked ? "hide" : "show"]();
});
</code>```

Kindly Help me out

答:
you can use condition using if</p>

```<code>if('#check').checked==true{
  $('#reg').css("display","none")
}
</code>```

Body:
In my JSP page two fields one is textbox and one is checkbox, I tried with     j query and java script also for hiding the textbox on checked of checkbox but it is not reflecting. Below I am mentioning code here

 <input id="check" name="check" value="check" style="margin-right: 10px" type="checkbox" tabindex="11">
         Not Yet Registered

Register No.

        <input id = "reg" maxlength="15"  name= "reg" placeholder="Reg No." type ="text" tabindex="12">

J query

$('#check').click(function() {
  $('.reg')[this.checked ? "hide" : "show"]();
});

Kindly Help me out

Body:
you can use condition using if

if('#check').checked==true{
  $('#reg').css("display","none")
}


问:
Form validation losing variables
Let's say I enter a registration form with this ending URL: registration.php?accountType=a
The form is parsed on the same page (registration.php).  If the user doesn't pass form validation they are taken to registration.php with error messages.  So you see I lost my variable accountType=a.  My question:

Can I submit a form for validation and retain the accountType variable?  I'm aware that this could easily be done using a cookie.  I just want a further understanding.

Solution: Although all of the answers below were valid, I went with a Session variable and <form action="registration.php?<?php print 'accountType=' . $_SESSION['accountType']; ?>" etc.  Thanks for the help.

答:
I think you should add the "accountType=$accountType" at the url's end, when you make a http forward, so the user will taken back to the correct page.

I dont see your code, but maybe like this:

```<code>if(auth())
{
  //do something...
}
else
{
  header("Location: /registration.php?somerror=true&accountType=" . $accountType);
}
</code>```

Title: Form validation losing variables

Body:
I think you should add the "accountType=$accountType" at the url's end, when you make a http forward, so the user will taken back to the correct page.

I dont see your code, but maybe like this:

if(auth())
{
  //do something...
}
else
{
  header("Location: /registration.php?somerror=true&accountType=" . $accountType);
}


问:
Angular unit test error: Unexpected value 'ObservableMedia' imported by the module 'DynamicTestModule'
I have a fairly simple unit test file like so:

```<code>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Http, HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { MaterialModule } from '@angular/material';
import { MediaChange, ObservableMedia } from "@angular/flex-layout";
import { PageHeaderComponent } from './page-header.component';
import { UserService } from '../user.service';
import { PreloadService } from '../preload.service';

describe('PageHeaderComponent', () => {
    let component: PageHeaderComponent;
    let fixture: ComponentFixture<PageHeaderComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [PageHeaderComponent],
            providers: [
                {
                    provide: Http,
                    deps: [MockBackend]
                },
                PreloadService,
                UserService
            ],
            imports: [MaterialModule, ObservableMedia],
            schemas: [CUSTOM_ELEMENTS_SCHEMA]
        });

        fixture = TestBed.createComponent(PageHeaderComponent);
        component = fixture.componentInstance;
    });

    it('should be created', () => {
        expect(component).toBeTruthy();
    });
});
</code>```

It's testing a run-of-the-mill Angular CLI component that contains a subscription to watch breakpoints for element visibility:

```<code>constructor(public media: ObservableMedia) {
    // watch for changes in breakpoint
    media.asObservable()
        .subscribe((change: MediaChange) => {
            // update the header tooltip state
            if (change.mqAlias == 'xs') {
                this.showHeaderTooltip = false;
            }
            else {
                this.showHeaderTooltip = true;
            }
        });
}

ngOnInit() {
    // check breakpoint and set header tooltip state
    if (this.media.isActive('xs')) {
        this.showHeaderTooltip = false;
    } else {
        this.showHeaderTooltip = true;
    }
}
</code>```

It throws this error:

Error: Unexpected value 'ObservableMedia' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation. in http://localhost:9876/_karma_webpack_/polyfills.bundle.js (line 6972)
          ZoneAwareError@http://localhost:9876/_karma_webpack_/polyfills.bundle.js:6972:28
          syntaxError@http://localhost:9876/_karma_webpack_/vendor.bundle.js:14803:39
          http://localhost:9876/_karma_webpack_/vendor.bundle.js:28487:55
          forEach@[native code]

....

I've seen similar error reports in my research, but not for ObservableMedia. I've tried adding the imports to app.module.ts, but that had no effect. What's missing?

答:
I think you should use FlexLayoutModule instead of ObservableMedia because ObservableMedia is just base abstract class while you need to import angular module i.e class adorned with with @NgModule decorator

Docs

Body:
I have a fairly simple unit test file like so:

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Http, HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { MaterialModule } from '@angular/material';
import { MediaChange, ObservableMedia } from "@angular/flex-layout";
import { PageHeaderComponent } from './page-header.component';
import { UserService } from '../user.service';
import { PreloadService } from '../preload.service';

describe('PageHeaderComponent', () => {
    let component: PageHeaderComponent;
    let fixture: ComponentFixture<PageHeaderComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [PageHeaderComponent],
            providers: [
                {
                    provide: Http,
                    deps: [MockBackend]
                },
                PreloadService,
                UserService
            ],
            imports: [MaterialModule, ObservableMedia],
            schemas: [CUSTOM_ELEMENTS_SCHEMA]
        });

        fixture = TestBed.createComponent(PageHeaderComponent);
        component = fixture.componentInstance;
    });

    it('should be created', () => {
        expect(component).toBeTruthy();
    });
});

It's testing a run-of-the-mill Angular CLI component that contains a subscription to watch breakpoints for element visibility:

constructor(public media: ObservableMedia) {
    // watch for changes in breakpoint
    media.asObservable()
        .subscribe((change: MediaChange) => {
            // update the header tooltip state
            if (change.mqAlias == 'xs') {
                this.showHeaderTooltip = false;
            }
            else {
                this.showHeaderTooltip = true;
            }
        });
}

ngOnInit() {
    // check breakpoint and set header tooltip state
    if (this.media.isActive('xs')) {
        this.showHeaderTooltip = false;
    } else {
        this.showHeaderTooltip = true;
    }
}

It throws this error:

Error: Unexpected value 'ObservableMedia' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation. in http://localhost:9876/_karma_webpack_/polyfills.bundle.js (line 6972)
          ZoneAwareError@http://localhost:9876/_karma_webpack_/polyfills.bundle.js:6972:28
          syntaxError@http://localhost:9876/_karma_webpack_/vendor.bundle.js:14803:39
          http://localhost:9876/_karma_webpack_/vendor.bundle.js:28487:55
          forEach@[native code]

....

I've seen similar error reports in my research, but not for ObservableMedia. I've tried adding the imports to app.module.ts, but that had no effect. What's missing?


问:
HIVE: Count distinct window function throws error
I am trying to use the window function count distinct in hive, and getting error.

The query used is as follows:

select
  user
  ,dt
  ,count(distinct dt) over(partition by user) as dates
from table
```
<p>It throws the following error:</p>
```FAILED: SemanticException [Error 10025]: Line 1:123 Expression not in GROUP BY key 'user'
```

I think I am using the syntax as specified in the hive language manual

What exactly am I doing wrong?

答:
The following solution will work like a count distinct.
The dense rank function will give a rank for distinct c within the partitions.
The highest dense rank number will be the amount of distinct entries of c.
No quiet the best performing way due to performing two window functions but for me it was the only way getting it to work on Hive <2.1.0. </p>

```<code>select src.a, src.b, src.c, max(src.cnt_dens_rank) over ( PARTITION BY src.a, src.b) as cnt_distinct
from
(
select a, b, c, DENSE_RANK ( ) OVER (PARTITION BY a, b order by c) cnt_dens_rank
) src
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use the window function count distinct in hive, and getting error.

The query used is as follows:

select
  user
  ,dt
  ,count(distinct dt) over(partition by user) as dates
from table

It throws the following error:

FAILED: SemanticException [Error 10025]: Line 1:123 Expression not in GROUP BY key 'user'

I think I am using the syntax as specified in the hive language manual

What exactly am I doing wrong?

Body:
The following solution will work like a count distinct.
The dense rank function will give a rank for distinct c within the partitions.
The highest dense rank number will be the amount of distinct entries of c.
No quiet the best performing way due to performing two window functions but for me it was the only way getting it to work on Hive <2.1.0.

select src.a, src.b, src.c, max(src.cnt_dens_rank) over ( PARTITION BY src.a, src.b) as cnt_distinct
from
(
select a, b, c, DENSE_RANK ( ) OVER (PARTITION BY a, b order by c) cnt_dens_rank
) src


问:
How to initiate a function using data(){} but not mounted(){} while using vue-resource
This works, but I need to use mounted(){} to initiate the function which I think can be avoided but not sure how.

```<code><script>
  export default {
    data () {
      return {
        domains: [],
      }
    },

    methods: {
      fetchDomains() {
        let _this = this;

        api._get({url: 'api/domains'})
          .then(function (response) {
            _this.domains = response.data;
          })
      }
    },

    mounted() {
      this.fetchDomains()
    }
  }
</script>
</code>```

This code doesn't work, but I like to do something like this. Initiating the function in data(){} itself.

```<code><script>
  export default {
    data () {
      return {
        domains: this.fetchDomains(),
      }
    },

    methods: {
      fetchDomains() {
        let data = [];

        api._get({url: 'api/domains'})
          .then(function (response) {
            data = response.data;
          })

        return data
      }
    }
  }
</script>
</code>```

Thanks in advance.

答:
I agree with Decade Moon that your first approach is the better way to do it (though you could use created instead of mounted).

The reason your second approach doesn't work is that you return an array and then replace the local variable's value with a different array. What you need to do is populate the array you returned.

new Vue({
  el: '#app',
  data() {
    return {item: this.getItem()}
  },
  methods: {
    getItem() {
      let val = [];
      setTimeout(() => {
        const result = ['first','second','third'];
        val.push(...result);
      }, 800);
      return val;
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">{{item}}</div></code>```

Body:
This works, but I need to use mounted(){} to initiate the function which I think can be avoided but not sure how.

This code doesn't work, but I like to do something like this. Initiating the function in data(){} itself.

Thanks in advance.

Body:
I agree with Decade Moon that your first approach is the better way to do it (though you could use created instead of mounted).

The reason your second approach doesn't work is that you return an array and then replace the local variable's value with a different array. What you need to do is populate the array you returned.

new Vue({
  el: '#app',
  data() {
    return {item: this.getItem()}
  },
  methods: {
    getItem() {
      let val = [];
      setTimeout(() => {
        const result = ['first','second','third'];
        val.push(...result);
      }, 800);
      return val;
    }
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">{{item}}</div>


问:
Using settings in dll?
I am writing a library to control measurement instruments and make calibrations. The library will be used in a few apps.

At one point I need to set the max. permitted signal's deviance, which depends on the transmitter being calibrated. So for. ex. Tansmitter-typ 1 has .2% and typ 2 has .1% and typ 3 has .05%.

```<code> Private Function GetMaxDeviationAllowed(transmitterName as String) As Double
        With transmitterName.Substring(0, 8)
            If .Contains("050") Then
                Return 0.2
            ElseIf .Contains("100") Or .Contains("101") then
                Return  0.15
            ElseIf .Contains("200") or .Contains("201") then
                Return  0.05
            ElseIf .Contains("_PSP")
                Return  0.2
            Else
                Return 0.2 'ASK: Use default tolerance or throw TypeNotSupported exception?'
            End If
        End With
End Function
</code>```

This programm will be used by people without any programming-knowledge and I wanted to give them the possibility to change the max. permitted deviance of each transmitter type without changing source code.

I always read that is no good idea using settings in the library and thats is better letting the UI handle the settings, but I can't (at least I dont know how) wrap such a method, because If I have 100 diferent types I need a method with 100 parameters (one for each type, if each has a different maxDeviationPermitted).
Also if I use a setting file with the dll, afaik this will not be used and also not be copied to the app output directory...so I am a little bit lost here...

Maybe I am just short-minded but if not would be nice if someone can give me some hint here.

Thank you in advance
RG

答:
I think your high-level design is a bit flawed. So let's break down some of the components.

What is a Library?

A Library is a set of (usually) precompiled functions that can be used by multiple programs. Libraries are simply tools. For example, in your code, you use a "String" and call its "Substring" method. That's a library! It performs tasks for you. Notice that you can only change the behavior of that method by giving it a different string with different parameters. Libraries don't change. They don't have settings.

So should you make a Deviation Parameter for each Transmitter Type?

This is a solution. It would allow you to change the deviations from each of your programs.

But then you would need to create a variable for every single transmitter type, then make a public method to change it. That way your library knows what deviations to use. You would have to set these every single time you reference the library, in every one of your programs.

In short, this is too much work. Libraries are meant to be as flexible as possible.

Any other ideas?

I'm not sure what your library does. I see it has a method to "Get the max deviation". I assume this value is then used in other methods?

So let's say this is your method:

```<code>Private Function MakeCalibration(transmitterName as String)

    Dim deviation as Double = GetMaxDeviationAllowed(transmitterName)
    // Do more stuff

End Function
</code>```

Pretty simple, but it has too much dependence on that "GetMaxDeviationAllowed" method. This method cannot work unless another method works. That is improper design.

Here is something better:

```<code>Private Function MakeCalibration(transmitterName as String, maxDeviationAllowed as Double)

    // Do more stuff using "maxDeviationAllowed"

End Function
</code>```

This allows your method to be used with anything.

This solution may not be exactly what you need, because I don't know what your goal is. However, the point is that your library should NOT care about what a given transmitter's maximum deviation is. All your library should do is take a transmitter type and a deviation, and perform what it needs to perform.

Maximum deviation should be decided in your program that's used by end-users. Then you can use a setting file, a setting's window, a JSON config, an XML config, a SQL server, or whatever you want. Your library doesn't care.

Helpful Articles for design

http://blog.gauffin.org/2011/07/single-responsibility-prinicple/

Title: Using settings in dll?

Body:
I am writing a library to control measurement instruments and make calibrations. The library will be used in a few apps.

At one point I need to set the max. permitted signal's deviance, which depends on the transmitter being calibrated. So for. ex. Tansmitter-typ 1 has .2% and typ 2 has .1% and typ 3 has .05%.

 Private Function GetMaxDeviationAllowed(transmitterName as String) As Double
        With transmitterName.Substring(0, 8)
            If .Contains("050") Then
                Return 0.2
            ElseIf .Contains("100") Or .Contains("101") then
                Return  0.15
            ElseIf .Contains("200") or .Contains("201") then
                Return  0.05
            ElseIf .Contains("_PSP")
                Return  0.2
            Else
                Return 0.2 'ASK: Use default tolerance or throw TypeNotSupported exception?'
            End If
        End With
End Function

This programm will be used by people without any programming-knowledge and I wanted to give them the possibility to change the max. permitted deviance of each transmitter type without changing source code.

I always read that is no good idea using settings in the library and thats is better letting the UI handle the settings, but I can't (at least I dont know how) wrap such a method, because If I have 100 diferent types I need a method with 100 parameters (one for each type, if each has a different maxDeviationPermitted).
Also if I use a setting file with the dll, afaik this will not be used and also not be copied to the app output directory...so I am a little bit lost here...

Maybe I am just short-minded but if not would be nice if someone can give me some hint here.

Thank you in advance
RG

Body:
I think your high-level design is a bit flawed. So let's break down some of the components.

What is a Library?

A Library is a set of (usually) precompiled functions that can be used by multiple programs. Libraries are simply tools. For example, in your code, you use a "String" and call its "Substring" method. That's a library! It performs tasks for you. Notice that you can only change the behavior of that method by giving it a different string with different parameters. Libraries don't change. They don't have settings.

So should you make a Deviation Parameter for each Transmitter Type?

This is a solution. It would allow you to change the deviations from each of your programs.

But then you would need to create a variable for every single transmitter type, then make a public method to change it. That way your library knows what deviations to use. You would have to set these every single time you reference the library, in every one of your programs.

In short, this is too much work. Libraries are meant to be as flexible as possible.

Any other ideas?

I'm not sure what your library does. I see it has a method to "Get the max deviation". I assume this value is then used in other methods?

So let's say this is your method:

Private Function MakeCalibration(transmitterName as String)

    Dim deviation as Double = GetMaxDeviationAllowed(transmitterName)
    // Do more stuff

End Function

Pretty simple, but it has too much dependence on that "GetMaxDeviationAllowed" method. This method cannot work unless another method works. That is improper design.

Here is something better:

Private Function MakeCalibration(transmitterName as String, maxDeviationAllowed as Double)

    // Do more stuff using "maxDeviationAllowed"

End Function

This allows your method to be used with anything.

This solution may not be exactly what you need, because I don't know what your goal is. However, the point is that your library should NOT care about what a given transmitter's maximum deviation is. All your library should do is take a transmitter type and a deviation, and perform what it needs to perform.

Maximum deviation should be decided in your program that's used by end-users. Then you can use a setting file, a setting's window, a JSON config, an XML config, a SQL server, or whatever you want. Your library doesn't care.

Helpful Articles for design

http://blog.gauffin.org/2011/07/single-responsibility-prinicple/


问:
jQuery table sort with colspan or rowspan
Hi

I'm using tablesorter and have problems with sorting tables that contain rowspan in  definition.
I've read hints here Grouping Rows with Client Side HTML Table Sorting
but solution doesn't work when I have different values for rowspan: once is rowspan=3, once 4 - depends on data taken from DB.

Do you have any other plugin that sorts even such non-standard tables or maybe you know how to tune tablesorter so it sorts data properly?

Expected behaviour: when clicked on column, rows "belonging" to rowspan should be sorted within this section only, all the others - in a standard way.

Thanks in advance,

Zbigniew

Table code example:

```<code><html>
<body>
  <table id="misint" border=1 width="400px">
    <thead>
        <tr style="background:yellow">
            <th>Col1</th>
            <th>Col2</th>
            <th>Col3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
          <td rowspan="3">1-1</td>
          <td>1-2</td>
          <td>1-3</td>
        </tr>
        <tr>
            <td>2-2</td>
            <td>2-3</td>
        </tr>
        <tr>
            <td>3-2</td>
            <td>3-3</td>
        </tr>
        <tr>
            <td>4-1</td>
            <td>4-2</td>
            <td>4-3</td>
        </tr>
        <tr>
          <td>5-1</td>
          <td rowspan="2">5-2</td>
          <td>5-3</td>
        </tr>
        <tr>
            <td>6-1</td>
            <td>6-3</td>
        </tr>
    </tbody>
  </table>

</body>
</html>
</code>```

答: You should look into the parser functionality of table sorter. You'll need to develop your own parser that will be able to recognize the cells properly.</p>

Body:
Hi

I'm using tablesorter and have problems with sorting tables that contain rowspan in  definition.
I've read hints here Grouping Rows with Client Side HTML Table Sorting
but solution doesn't work when I have different values for rowspan: once is rowspan=3, once 4 - depends on data taken from DB.

Do you have any other plugin that sorts even such non-standard tables or maybe you know how to tune tablesorter so it sorts data properly?

Expected behaviour: when clicked on column, rows "belonging" to rowspan should be sorted within this section only, all the others - in a standard way.

Thanks in advance,

Zbigniew

Table code example:

            Col1
            Col2
            Col3

          1-1
          1-2
          1-3

            2-2
            2-3

            3-2
            3-3

            4-1
            4-2
            4-3

          5-1
          5-2
          5-3

            6-1
            6-3


问:
Turn 2 bit module (Multiplier) into more bits
I have the following code for a 2 bit multiplier:

```<code>module Multiplier (a0, a1, b0, b1, c[3:0]);
output      [3:0]c;
input       a0, a1, b0, b1;
wire        a0b1, a1b0, ha0c, a1b1;

and (c[0], a0, b0);
and (a0b1, a0, b1);
and (a1b0, a1, b0);
HalfAdder ha0 (a1b0, a0b1, c[1], ha0c);

and (a1b1, a1, b1);
HalfAdder ha1 (ha0c, a1b1, c[2], c[3]);
endmodule
</code>```

I want to be able to expand this to more than 2 bits though (32 bits).  The structure of my code poses a challenge for this though.  First off I would have to have 68 parameters for the module.  Also I would have to manually create 64 wires (duplicates of wire a0b1, a1b0, ha0c, a1b1).  Finally I would need to manually write out a bunch of logic gates and HalfAdder modules to connect all the logic.  Because of this I am wondering if there is a way that I can refactor my code to be able to instantiate a binary multiplier of n (a passed parameter) size.

答:
You need to parameterize and use a generate block. (And it is much better to use a synchronous circuit then an asynchronous circuit).

Here is an incomplete example, you can fill in the necessary logic :

```<code>module Multiplier (a, b, c, clk);
parameter WIDTH = 64;
output      [2*WIDTH:0]c;
input       [WIDTH-1:0]a;
input       [WIDTH-1:0]b;
input       clk;

genvar i;
generate  for (i = 0; i < WIDTH; i <= i + 1)
begin : shifts
    // shift a 1-bit for each i and 'logical and' it with b
    reg  [WIDTH + i :0]carry;
    wire [WIDTH + i -1:0]shifted = {a,i{0}} & b[i];

    // sum the result of shift and 'logical and'
    always @ (posedge clk)
    begin
        carry <= shifted + shifts[i-1].carry ;
    end
end

assign c = shifts[WIDTH].carry;

endgenerate

endmodule
</code>```

Body:
I have the following code for a 2 bit multiplier:

module Multiplier (a0, a1, b0, b1, c[3:0]);
output      [3:0]c;
input       a0, a1, b0, b1;
wire        a0b1, a1b0, ha0c, a1b1;

and (c[0], a0, b0);
and (a0b1, a0, b1);
and (a1b0, a1, b0);
HalfAdder ha0 (a1b0, a0b1, c[1], ha0c);

and (a1b1, a1, b1);
HalfAdder ha1 (ha0c, a1b1, c[2], c[3]);
endmodule

I want to be able to expand this to more than 2 bits though (32 bits).  The structure of my code poses a challenge for this though.  First off I would have to have 68 parameters for the module.  Also I would have to manually create 64 wires (duplicates of wire a0b1, a1b0, ha0c, a1b1).  Finally I would need to manually write out a bunch of logic gates and HalfAdder modules to connect all the logic.  Because of this I am wondering if there is a way that I can refactor my code to be able to instantiate a binary multiplier of n (a passed parameter) size.

Body:
You need to parameterize and use a generate block. (And it is much better to use a synchronous circuit then an asynchronous circuit).

Here is an incomplete example, you can fill in the necessary logic :

module Multiplier (a, b, c, clk);
parameter WIDTH = 64;
output      [2*WIDTH:0]c;
input       [WIDTH-1:0]a;
input       [WIDTH-1:0]b;
input       clk;

genvar i;
generate  for (i = 0; i < WIDTH; i <= i + 1)
begin : shifts
    // shift a 1-bit for each i and 'logical and' it with b
    reg  [WIDTH + i :0]carry;
    wire [WIDTH + i -1:0]shifted = {a,i{0}} & b[i];

    // sum the result of shift and 'logical and'
    always @ (posedge clk)
    begin
        carry <= shifted + shifts[i-1].carry ;
    end
end

assign c = shifts[WIDTH].carry;

endgenerate

endmodule


问:
Subset rows of a data frame that contain numbers in all of the column
I want to get a subset of my dataframe by keeping rows that have numeric in all columns so

```<code>>small
     0    16h    24h    48h
ID1  1    0      0
ID2  453  254    21     12
ID3  true  3     2      1
ID4  65    23    12     12
</code>```

would be

```<code>>small_numeric
     0    16h    24h    48h
ID2  453  254    21     12
ID4  65    23    12     1
</code>```

I tried

```<code>sapply(small, is.numeric)
</code>```

but got this

```<code>0      16h    24h    48h
FALSE  FALSE  FALSE  FALSE
</code>```

答:
Using:

```<code>small[!rowSums(is.na(sapply(small, as.numeric))),]
</code>```

gives:

```<code>      0 16h 24h 48h
ID2 453 254  21  12
ID4  65  23  12  12
</code>```

What this does:

With sapply(small, as.numeric) you force all columns to numeric. Non-numeric values are converted to NA-values as a result.

Next you count the number of NA-values with rowSums(is.na(sapply(small, as.numeric))) which gives you back a numeric vector, [1] 1 0 1 0, with the number of non-numeric values by row.

Negating this with ! gives you a logical vector of the rows where all columns have numeric values.

Used data:

```<code>small <- read.table(text="     0    16h    24h    48h
ID1  1    0      0
ID2  453  254    21     12
ID3  true  3     2      1
ID4  65    23    12     12", header=TRUE, stringsAsFactors = FALSE, fill = TRUE, check.names = FALSE)
</code>```

For the updated example data, the problem is that columns with non-numeric values are factors instead of character. There you'll have to adapt the above code as follows:

```<code>testdata[!rowSums(is.na(sapply(testdata[-1], function(x) as.numeric(as.character(x))))),]
</code>```

which gives:

```<code>      0  16h  24h  48h   NA
ID2 ID2   46   23   23   48
ID3 ID3   44   10   14   22
ID4 ID4   17   11    4   24
ID5 ID5   13    5    3   18
ID7 ID7 4387 4216 2992 3744
</code>```

Extra explanation:

When converting factor-columns to numeric, you will have to convert those to character first. Hence: as.numeric(as.character(x)). If you don't do that, as.numeric with give back the numbers of the factor levels.

I used testdata[-1] as I supposed that you didn't want to include the first column in the check for numeric values.

Body:
I want to get a subset of my dataframe by keeping rows that have numeric in all columns so

>small
     0    16h    24h    48h
ID1  1    0      0
ID2  453  254    21     12
ID3  true  3     2      1
ID4  65    23    12     12

would be

>small_numeric
     0    16h    24h    48h
ID2  453  254    21     12
ID4  65    23    12     1

I tried

sapply(small, is.numeric)

but got this

0      16h    24h    48h
FALSE  FALSE  FALSE  FALSE

Body:
Using:

small[!rowSums(is.na(sapply(small, as.numeric))),]

gives:

      0 16h 24h 48h
ID2 453 254  21  12
ID4  65  23  12  12

What this does:

With sapply(small, as.numeric) you force all columns to numeric. Non-numeric values are converted to NA-values as a result.

Next you count the number of NA-values with rowSums(is.na(sapply(small, as.numeric))) which gives you back a numeric vector, [1] 1 0 1 0, with the number of non-numeric values by row.

Negating this with ! gives you a logical vector of the rows where all columns have numeric values.

Used data:

small <- read.table(text="     0    16h    24h    48h
ID1  1    0      0
ID2  453  254    21     12
ID3  true  3     2      1
ID4  65    23    12     12", header=TRUE, stringsAsFactors = FALSE, fill = TRUE, check.names = FALSE)

For the updated example data, the problem is that columns with non-numeric values are factors instead of character. There you'll have to adapt the above code as follows:

testdata[!rowSums(is.na(sapply(testdata[-1], function(x) as.numeric(as.character(x))))),]

which gives:

      0  16h  24h  48h   NA
ID2 ID2   46   23   23   48
ID3 ID3   44   10   14   22
ID4 ID4   17   11    4   24
ID5 ID5   13    5    3   18
ID7 ID7 4387 4216 2992 3744

Extra explanation:

When converting factor-columns to numeric, you will have to convert those to character first. Hence: as.numeric(as.character(x)). If you don't do that, as.numeric with give back the numbers of the factor levels.

I used testdata[-1] as I supposed that you didn't want to include the first column in the check for numeric values.


问:
How to show loader until file uploads? Angular 2
I want to add loader icon when I'm uploading some file. How can I set it to last until the upload is done?

I have a simple upload form where I want to upload document and click Save button, then loader should pop up and show itself only until the file is uploaded.

```<code><input type="file" (change)="AddFiles($event)" />
<button type="submit">Save</button>
</code>```

TS:

```<code>addFiles(event: EventTarget) {
    // this.file = [];
    const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    const files: FileList = target.files;
    if (files.length !== 0) {
      this.file = [];
      this.file.push(files[0]);
      this.uploadFlag = true;
    } else {
      this.uploadFlag = false;
    }

  }
</code>```

Thats the code for adding files and what I would like to do is on click of Save show loader until its done.

答:
You can do it like this:

```<code><div align="center" *ngIf="result?.length == 0">Waiting ...</div>
  <div id="loader-home" align="center" *ngIf="result?.length == 0">
    <div class="bounce1"></div>
    <div class="bounce2"></div>
    <div class="bounce3"></div>
  </div>
</code>```

Each of bounce class represent one bubble (adjusted with css to bounce one after one)

```<code>    /* LOADER */
  #loader-home {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%; }
  #loader-home > div {
    width: 18px;
    height: 18px;
    background-color: black;
    border-radius: 100%;
    display: inline-block;
    -webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
    animation: sk-bouncedelay 1.4s infinite ease-in-out both; }
  #loader-home .bounce1 {
    animation-delay: -0.32s; }
  #loader-home .bounce2 {
    animation-delay: -0.16s; }
  #loader-home .bounce3 {
    animation-delay: -0.08s; }
</code>```

The "result" variable is the result of your observable

```<code> this.data.import(uploadResult)
        .map((res: any) => res.errorMessage)
        .subscribe(result => {
        this.result = result;
...}
</code>```

Body:
I want to add loader icon when I'm uploading some file. How can I set it to last until the upload is done?

I have a simple upload form where I want to upload document and click Save button, then loader should pop up and show itself only until the file is uploaded.

<input type="file" (change)="AddFiles($event)" />
<button type="submit">Save</button>

TS:

addFiles(event: EventTarget) {
    // this.file = [];
    const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
    const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
    const files: FileList = target.files;
    if (files.length !== 0) {
      this.file = [];
      this.file.push(files[0]);
      this.uploadFlag = true;
    } else {
      this.uploadFlag = false;
    }

  }

Thats the code for adding files and what I would like to do is on click of Save show loader until its done.

Body:
You can do it like this:

<div align="center" *ngIf="result?.length == 0">Waiting ...</div>
  <div id="loader-home" align="center" *ngIf="result?.length == 0">
    <div class="bounce1"></div>
    <div class="bounce2"></div>
    <div class="bounce3"></div>
  </div>

Each of bounce class represent one bubble (adjusted with css to bounce one after one)

    /* LOADER */
  #loader-home {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%; }
  #loader-home > div {
    width: 18px;
    height: 18px;
    background-color: black;
    border-radius: 100%;
    display: inline-block;
    -webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
    animation: sk-bouncedelay 1.4s infinite ease-in-out both; }
  #loader-home .bounce1 {
    animation-delay: -0.32s; }
  #loader-home .bounce2 {
    animation-delay: -0.16s; }
  #loader-home .bounce3 {
    animation-delay: -0.08s; }

The "result" variable is the result of your observable

 this.data.import(uploadResult)
        .map((res: any) => res.errorMessage)
        .subscribe(result => {
        this.result = result;
...}


问:
changing text in html with php without affecting html tags
i've edited a simple php function to convert the letters to the homograph with similar look.

my code :

```<code>function homographit($string){

$alphabet = array("A", "B", "C", "E", "H", "J", "K", "M", "N", "O", "P", "S", "T", "X", "Y",
"a", "b", "c", "e", "i", "j", "k", "o", "p", "r", "s", "v", "x", "y");
$Greec   = array("\u0391", "\u0392", "\u0421", "\u0395", "\u0397", "\u0408", "\u039A", "\u039C", "\u039D", "\u039F", "\u03A1", "\u0405",
"\u03A4", "\u03A7", "\u03A5", "\u0430", "\u042C", "\u0441", "\u0435", "\u0456", "\u0458", "\u03BA", "\u03BF", "\u03C1", "\u0433", "\u0455",
"\u03BD", "\u03C7", "\u0443");

$newstring = str_replace($alphabet, $Greec, $string);
return json_decode('"'.$newstring.'"', true);
}
</code>```

for a text string the function work as perfect.

My question:

How to apply this homgraphit() to all text in html string withouwt affecting html TAGS?
thx

答:
You can use strip_tags built-in php function for Strip HTML and PHP tags from a string. Im tested with code bellow using your homographit function:

```<code>$x = '<span>\u0391</span><b>\u0392</b>';
$x = strip_tags($x);
var_dump(homographit($x));die();

//will print
//string(4) "ΑΒ"

$x = '<span>\u0391</span><b>\u0392</b>';
var_dump(homographit($x));die();

//will print
//string(32) "<ѕρаn>Α</ѕρаn><Ь>Β</Ь>"
</code>```

hope this can solve your problem.

Edit
i found this

```<code>$x = '<span>\u0455\u0391</span><b>\u0392</b>';
$convertedString = json_decode('"' . $x . '"');
var_dump($convertedString);

// will print
// string(26) "<span>ѕΑ</span><b>Β</b>"
</code>```

try this

Body:
i've edited a simple php function to convert the letters to the homograph with similar look.

my code :

function homographit($string){

$alphabet = array("A", "B", "C", "E", "H", "J", "K", "M", "N", "O", "P", "S", "T", "X", "Y",
"a", "b", "c", "e", "i", "j", "k", "o", "p", "r", "s", "v", "x", "y");
$Greec   = array("\u0391", "\u0392", "\u0421", "\u0395", "\u0397", "\u0408", "\u039A", "\u039C", "\u039D", "\u039F", "\u03A1", "\u0405",
"\u03A4", "\u03A7", "\u03A5", "\u0430", "\u042C", "\u0441", "\u0435", "\u0456", "\u0458", "\u03BA", "\u03BF", "\u03C1", "\u0433", "\u0455",
"\u03BD", "\u03C7", "\u0443");

$newstring = str_replace($alphabet, $Greec, $string);
return json_decode('"'.$newstring.'"', true);
}

for a text string the function work as perfect.

My question:

How to apply this homgraphit() to all text in html string withouwt affecting html TAGS?
thx

Body:
You can use strip_tags built-in php function for Strip HTML and PHP tags from a string. Im tested with code bellow using your homographit function:

$x = '<span>\u0391</span><b>\u0392</b>';
$x = strip_tags($x);
var_dump(homographit($x));die();

//will print
//string(4) "ΑΒ"

$x = '<span>\u0391</span><b>\u0392</b>';
var_dump(homographit($x));die();

//will print
//string(32) "<ѕρаn>Α</ѕρаn><Ь>Β</Ь>"

hope this can solve your problem.

Edit
i found this

$x = '<span>\u0455\u0391</span><b>\u0392</b>';
$convertedString = json_decode('"' . $x . '"');
var_dump($convertedString);

// will print
// string(26) "<span>ѕΑ</span><b>Β</b>"

try this


问:
Fortify Open redirect issue on Javascript
```<code>var param=document.getElementById("test").value;
var url= "http://localhost/app/default.aspx?test="+param;
Window.showModalDialog(url);
</code>```

showModalDialog method line is showing me fortify open redirect issue. Is there anyway I can resolve the issue on client side (in javascript file)?

Your help would be highly appreciated.

答:
Fortify is saying that you're redirecting the user to a new site whose URL is composed of the user's input, which could allow an attacker to phish or perform other attacks if it was manipulated in a special way using the input value. OWASP.org reference

The best way to fix this is to create a white list on the server of acceptable parameters values for the parameter test, so when the server receives a request with a value for test, it can redirect the user to a page if the value of the parameter is not recognized/invalid. There's no reliable fix for this issue that lies solely on the client side, given the information provided in the question. A regex would help in theory, although I am unsure if Fortify will be happy with a regex sanitation.

Body:
var param=document.getElementById("test").value;
var url= "http://localhost/app/default.aspx?test="+param;
Window.showModalDialog(url);

showModalDialog method line is showing me fortify open redirect issue. Is there anyway I can resolve the issue on client side (in javascript file)?

Your help would be highly appreciated.


问:
JSON schema to JSON data
I wanted to create JSON data from JSON schema in JavaScript.

I tried using JSON schema fakers, But the problem is it validates and generates random data all time, Sometimes I don't get all keys.

for example(Sample JSON schema)

```<code>{
"$schema" : "http://schema.net",
"id" : "0",
"definitions" :
{
"cote" :
{
"type" : "string"
}
}
}
</code>```

The data generated by JSON Schema faker is {}. As you can see not all keys are generated here. But I want all keys to be there. So is there any way I can create JSON data from Schema which contains all keys. Also,If there any way I can add required:[] to schema, I can use Schema faker to generate data.

How will I approach the problem in JavaScript?

答:
is very similar</p>

```<code>var data = {
    schema : "http://schema.net",
    id : "0",
    definitions :{
        cote :{
            type : "string"
        }
    }
}
</code>```

Title: JSON schema to JSON data

Body:
I wanted to create JSON data from JSON schema in JavaScript.

I tried using JSON schema fakers, But the problem is it validates and generates random data all time, Sometimes I don't get all keys.

for example(Sample JSON schema)

{
"$schema" : "http://schema.net",
"id" : "0",
"definitions" :
{
"cote" :
{
"type" : "string"
}
}
}

The data generated by JSON Schema faker is {}. As you can see not all keys are generated here. But I want all keys to be there. So is there any way I can create JSON data from Schema which contains all keys. Also,If there any way I can add required:[] to schema, I can use Schema faker to generate data.

How will I approach the problem in JavaScript?

Body:
is very similar

var data = {
    schema : "http://schema.net",
    id : "0",
    definitions :{
        cote :{
            type : "string"
        }
    }
}


问:
@property in my AppDelegate becomes null when app goes to background in iOS
In my AppDelegate I have a property. It is strong and of type custom class(which is a subclass of NSObject). It becomes NULL when the App goes to background. This behaviour is uncertain and could not be reproduced easily (even with Simulate Memory Warning option). It occurs randomly.

My understanding is, when the app goes to background and if some other app needs memory, the app will be terminated. But in this case, the app is not terminated but a specific property becomes null.

I have not implemented didReceiveMemoryWarning in any of my ViewControllers.

Please help me with this.

Edit:

This is the sample of how my AppDelegate looks

AppDelegate.h

```<code>@interface AppDelegate : UIResponder
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) Person *person;//This is the custom class
@end
</code>```

AppDelegate.m

```<code>@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Override point for customization after application launch.
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.navigationController = [[UINavigationController alloc] initWithRootViewController:[UIViewController new]];
   self.window.rootViewController = self.navigationController;
   [self.window makeKeyAndVisible];
   return YES;
}
@end
</code>```

答:
I would suggest you to override your property's setter and add a breakpoint in it. You will see when it has been set to nil.

Setter example:

```<code>- (void)setPerson:(Person *)person {
    _person = person; // breakpoint on this line
}
</code>```

Body:
In my AppDelegate I have a property. It is strong and of type custom class(which is a subclass of NSObject). It becomes NULL when the App goes to background. This behaviour is uncertain and could not be reproduced easily (even with Simulate Memory Warning option). It occurs randomly.

My understanding is, when the app goes to background and if some other app needs memory, the app will be terminated. But in this case, the app is not terminated but a specific property becomes null.

I have not implemented didReceiveMemoryWarning in any of my ViewControllers.

Please help me with this.

Edit:

This is the sample of how my AppDelegate looks

AppDelegate.h

@interface AppDelegate : UIResponder
@property (nonatomic, strong) UIWindow *window;
@property (nonatomic, strong) UINavigationController *navigationController;
@property (nonatomic, strong) Person *person;//This is the custom class
@end

AppDelegate.m

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   // Override point for customization after application launch.
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.navigationController = [[UINavigationController alloc] initWithRootViewController:[UIViewController new]];
   self.window.rootViewController = self.navigationController;
   [self.window makeKeyAndVisible];
   return YES;
}
@end

Body:
I would suggest you to override your property's setter and add a breakpoint in it. You will see when it has been set to nil.

Setter example:

- (void)setPerson:(Person *)person {
    _person = person; // breakpoint on this line
}


问:
Silverlight & Visual Tree Manipulation
Now this may be more trouble than it's worth but nevertheless, it'd be really useful to me right now.

What I'd like to know is how I might go about manipulating the Silverlight visual tree at runtime.  Doing simple things like adding and removing controls is easy enough but when you start having to traverse the tree with any reasonable amount of complexity I find myself yearning for a JQuery style syntax (LINQ would be pretty cool too I suppose) to handle DOM node replacements, movements and the like.

So I guess the question is are there any libraries out there to make this an easier job or is there something baked in that I've missed?

答:
what version of silverlight is this?
And what year of " Dec 13 at 13:13" is this post from?

in the current version of SL4 it does not seem to be there..

Title: Silverlight & Visual Tree Manipulation


问:
Convert select query to update MYSQL
How to convert select to update for this query for field 'year_from':

```<code>SELECT CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) FROM
lc_vehicles
</code>```

edit:
when using select i get results from 198501 to 1985.01, but when update I get 1985.0

答:
The update would presumably look something like this:

```<code>update lc_vehicles
    set ?? = CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) ;
</code>```

The ?? is for the name of the column to be updated.

Title: Convert select query to update MYSQL

Body:
How to convert select to update for this query for field 'year_from':

SELECT CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) FROM
lc_vehicles

edit:
when using select i get results from 198501 to 1985.01, but when update I get 1985.0

Body:
The update would presumably look something like this:

update lc_vehicles
    set ?? = CONCAT_WS('.', LEFT(year_from, 4), SUBSTRING(year_from, 5)) ;

The ?? is for the name of the column to be updated.


问:
Error when attempting to Publish Customizations (Cannot access the uploaded file)
We've recently created a second Company (id=3) based on a snapshot of our original company (id=2). I am attempting to publish a change to one of the Customization Projects in the new company. The file upload/save worked fine, but publishing leads to this error:

```<code>Publish Customization

Compiled projects: AA, BB, CC, DD

Validation has been started.

PX.Data.PXException: Cannot access the uploaded file. Failed to get the
latest revision of the file 9a65331c-ad34-477c-9759-2c414dead49f

   at Customization.CstBinFile.GetFileFromDb()
   at Customization.CstBinFile.SaveFiles(FilesCollection context)
   at Customization.CstDocument.GetFiles(FilesCollection context)
   at Customization.CstManager.ValidateDocument(CstDocument doc, Action`1

    logMessageDelegate, Boolean patchLibInDB)
  at PX.Customization.CstValidationProcess.ValidateCurrentDocument(Action`1
logMessage)
   at PX.Customization.CstValidationProcess.CompileInternal()
   at PX.Customization.CstValidationProcess.<>c__DisplayClass6_0.
<ProcessRequest>b__0()
</code>```

This attempt represents the first publish within this Company.
I retried the upload/save, but still no luck.
Our version is:  6.10.0010.

How do I overcome this error?
Any help would be great.  Thanks.

答:
This can happen when the customization projects reference a file that has been removed from the database. Customization project still has the file reference ID but the database doesn't contain a file associated with that ID anymore.

If this is the cause of your error, you can correct it by removing and adding back missing files. To do this, go to the Files section of your customization project. Click on each file link.

If the file is missing in database, an error message popup will appear. For these, remove the file link reference and add it back again. When files are not missing, they will appear like in the screenshots below.

Body:
We've recently created a second Company (id=3) based on a snapshot of our original company (id=2). I am attempting to publish a change to one of the Customization Projects in the new company. The file upload/save worked fine, but publishing leads to this error:

Publish Customization

Compiled projects: AA, BB, CC, DD

Validation has been started.

PX.Data.PXException: Cannot access the uploaded file. Failed to get the
latest revision of the file 9a65331c-ad34-477c-9759-2c414dead49f

   at Customization.CstBinFile.GetFileFromDb()
   at Customization.CstBinFile.SaveFiles(FilesCollection context)
   at Customization.CstDocument.GetFiles(FilesCollection context)
   at Customization.CstManager.ValidateDocument(CstDocument doc, Action`1

    logMessageDelegate, Boolean patchLibInDB)
  at PX.Customization.CstValidationProcess.ValidateCurrentDocument(Action`1
logMessage)
   at PX.Customization.CstValidationProcess.CompileInternal()
   at PX.Customization.CstValidationProcess.<>c__DisplayClass6_0.
<ProcessRequest>b__0()

This attempt represents the first publish within this Company.
I retried the upload/save, but still no luck.
Our version is:  6.10.0010.

How do I overcome this error?
Any help would be great.  Thanks.


问:
How to create a selector ID from a variable
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1 <br>
<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2 <br>

<div id = "box1" style="display:none">Checkbox 1 is selected</div>
<div id = "box2" style="display:none">Checkbox 2 is selected</div></code>```

Can anyone please help me understand why the .toggle doesn't work correctly?

答:
I'm not exactly sure what the problem is. In jQuery .each() is built in and is better than the for loop, so lets use that.

```<code>$(document).ready(function() {
  $("input[type=checkbox]").each(function(index) {
    $("input[name=checkbox" + (index + 1) + "]").click(function() {
      $("#box" + (index + 1)).toggle()
    })
  })
});
</code>```

So let's start at the top first we are selecting all the inputs that have a type of checkbox and executing a function for each matched element, it also gives us some data the "index" being passed through starting at 0 and going up.

We then grab all matched elements that are inputs with the name of checkbox and the number after checkbox is going to start at 1 and finish at 2 since we are adding 1 to the index.
When you click on one of these inputs we will call a new function that selects the box with the correct number (again using the index + 1, so we're not starting at 0) and toggles it.

Body:
In my HTML document, I want to have 9 checkboxes. When a checkbox is selected, I want a corresponding block of text to show. I'm trying to create a single function for this, that uses a parameter to select the corresponding box, but I've been unsuccesfull so far. I'm not experienced with HTML of jQuery at all, so I've got no idea what the problem is.

The code I currently have is as follows:

$(document).ready(function() {
    for ($i = 0; $i < 9; $i++) {
        $("input[name=checkbox" + $i + "]").click(function () {
            $('#box' + $i).toggle();
        });
    }
});

<input type="checkbox" name="checkbox1" value="alpha"> Checkbox 1

<input type="checkbox" name="checkbox2" value="beta"> Checkbox 2

Checkbox 1 is selected

Checkbox 2 is selected

Can anyone please help me understand why the .toggle doesn't work correctly?

Body:
I'm not exactly sure what the problem is. In jQuery .each() is built in and is better than the for loop, so lets use that.

$(document).ready(function() {
  $("input[type=checkbox]").each(function(index) {
    $("input[name=checkbox" + (index + 1) + "]").click(function() {
      $("#box" + (index + 1)).toggle()
    })
  })
});

So let's start at the top first we are selecting all the inputs that have a type of checkbox and executing a function for each matched element, it also gives us some data the "index" being passed through starting at 0 and going up.

We then grab all matched elements that are inputs with the name of checkbox and the number after checkbox is going to start at 1 and finish at 2 since we are adding 1 to the index.
When you click on one of these inputs we will call a new function that selects the box with the correct number (again using the index + 1, so we're not starting at 0) and toggles it.


问:
PHP Ajax file upload not working
Please help me find the problem here. I am trying to upload a file via AJAX but For some reason which I am unaware of this code has refused to work i.e uploaded file is not copied to the location.

```<code>function save()
{
    var fileUpload = $("#files").get(0);
    var files = fileUpload.files;
    var data = new FormData();
    for (var i = 0; i < files.length ; i++) {
       data.append('files',files[i],files[i].name);
    }

    var datastring = $("#businessform").serializeArray();
    $.each(datastring,function(key,input){
        data.append(input.name,input.value);
    });

    $.ajax({
            type: "POST",
            url: "../include/update_ajax.php",
            contentType: false,
            processData: false,
            data: data,
            dataType: 'json',
            cache: false,
            success: function(data) {
                //do something
            },
            error: function(){
                  alert('error handling here');
            }
        });
 }
</code>```

Here's the PHP

```<code>        $success = 0;
        $logo = "";
        $logo_error = 0;
        $sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
        $fields = array(
            ':bname'=>$_POST['businessname'],
            ':phone'=>$_POST['businessphone'],
            ':email'=>$_POST['businessemail'],
            ':id'=>$_POST['vendorid']
        );
        $q=$con->update_query($sql,$fields);
        if($q)
        {
            //save logo
            $businessid = $con->lastID;
            if(!empty($_FILES['files']['tmp_name']))
            {
                $ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
                if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
                {
                    $logo = "logo".$businessid;
                    move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
                }
                else
                {
                    $logo_error = 1;
                }

            }
            $success = 1;
        }
        echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));
</code>```

The serialized form appended is sent and inserted without issues but the uploaded file is not sent this way. Please what are my doing wrong and what's the better way.

Thank you so much.

答:
You don't need to append files in FormData() just put Form tag selector in side FormData($("#businessform")[0]);

```<code>function save()
{
    var datastring = FormData($("#businessform")[0]);

    $.ajax({
            type: "POST",
            url: "../include/update_ajax.php",
            contentType: false,
            processData: false,
            data: data,
            dataType: 'json',
            cache: false,
            success: function(data) {
                //do something
            },
            error: function(){
                  alert('error handling here');
            }
        });
 }
</code>```

Title: PHP Ajax file upload not working

Body:
Please help me find the problem here. I am trying to upload a file via AJAX but For some reason which I am unaware of this code has refused to work i.e uploaded file is not copied to the location.

function save()
{
    var fileUpload = $("#files").get(0);
    var files = fileUpload.files;
    var data = new FormData();
    for (var i = 0; i < files.length ; i++) {
       data.append('files',files[i],files[i].name);
    }

    var datastring = $("#businessform").serializeArray();
    $.each(datastring,function(key,input){
        data.append(input.name,input.value);
    });

    $.ajax({
            type: "POST",
            url: "../include/update_ajax.php",
            contentType: false,
            processData: false,
            data: data,
            dataType: 'json',
            cache: false,
            success: function(data) {
                //do something
            },
            error: function(){
                  alert('error handling here');
            }
        });
 }

Here's the PHP

        $success = 0;
        $logo = "";
        $logo_error = 0;
        $sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
        $fields = array(
            ':bname'=>$_POST['businessname'],
            ':phone'=>$_POST['businessphone'],
            ':email'=>$_POST['businessemail'],
            ':id'=>$_POST['vendorid']
        );
        $q=$con->update_query($sql,$fields);
        if($q)
        {
            //save logo
            $businessid = $con->lastID;
            if(!empty($_FILES['files']['tmp_name']))
            {
                $ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
                if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
                {
                    $logo = "logo".$businessid;
                    move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
                }
                else
                {
                    $logo_error = 1;
                }

            }
            $success = 1;
        }
        echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));

The serialized form appended is sent and inserted without issues but the uploaded file is not sent this way. Please what are my doing wrong and what's the better way.

Thank you so much.

Body:
You don't need to append files in FormData() just put Form tag selector in side FormData($("#businessform")[0]);

function save()
{
    var datastring = FormData($("#businessform")[0]);

    $.ajax({
            type: "POST",
            url: "../include/update_ajax.php",
            contentType: false,
            processData: false,
            data: data,
            dataType: 'json',
            cache: false,
            success: function(data) {
                //do something
            },
            error: function(){
                  alert('error handling here');
            }
        });
 }