问:
Payara MicroProfile 5.191 intermitted "converter not found" after clean, compile, package, run
I've a Java EE 8 web project (war) with a JSF page that uses a converter.

When I try to load that page (after mvn clean compile package and java -jar payara-micro-5.191.jar --deploy rbooking.war) "sometimes" the converter class was not found.

To solve the problem the only solution is to recompile the war.

Here some details:

the pom file:

```<code><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>sartorieinformatiche.it.rbooking</groupId>
  <artifactId>rbooking</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <repositories>
    <repository>
      <id>prime-repo</id>
      <name>PrimeFaces Maven Repository</name>
      <url>http://repository.primefaces.org</url>
      <layout>default</layout>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-email</artifactId>
      <version>1.5</version>
    </dependency>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>8.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.primefaces</groupId>
      <artifactId>primefaces</artifactId>
      <version>7.0</version>
    </dependency>
    <dependency>
      <groupId>org.primefaces.themes</groupId>
      <artifactId>all-themes</artifactId>
      <version>1.0.10</version>
    </dependency>
    <dependency>
      <groupId>uaihebert.com</groupId>
      <artifactId>uaiCriteria</artifactId>
      <version>4.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.omnifaces</groupId>
      <artifactId>omnifaces</artifactId>
      <version>3.3</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>rbooking</finalName>
  </build>
</project>
</code>```

the converter class:

```<code>package sartorieinformatiche.it.rbooking.control;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;

import sartorieinformatiche.it.rbooking.entity.Language;

@FacesConverter(value = "languageConverter", managed = true)
public class LanguageConverter implements Converter<Language> {

  @Inject
  private LanguageService languageService;

  @Override
  public String getAsString(FacesContext context, UIComponent component, Language language) {
    if (language == null) {
      return "";
    }

    return language.getId().toString();
  }

  @Override
  public Language getAsObject(FacesContext context, UIComponent component, String value) {
    if (value == null || value.trim().isEmpty()) {
      return null;
    }

    Long id = Long.parseLong(value);

    return languageService.findById(id);
  }

}
</code>```

the JSF page fragment:

```<code>...<p:selectOneMenu id="language"
                 value="#{bookingBean.booking.language}"
                 converter="languageConverter">
  <f:selectItems value="#{bookingBean.allLanguages}"
                 itemLabel="#{language.description}"
                 itemValue="#{language.id}" />
    <p:column>
      <h:outputText value="#{language.description}" />
    </p:column>
</p:selectOneMenu>...
</code>```

the error when the JSF page is loaded:

```<code>  StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
javax.faces.FacesException: Expression Error: Named Object: languageConverter not found.
    at com.sun.faces.util.Util.notNullNamedObject(Util.java:467)
    at com.sun.faces.application.applicationimpl.InstanceFactory.createConverter(InstanceFactory.java:456)
    at com.sun.faces.application.ApplicationImpl.createConverter(ApplicationImpl.java:502)
    at javax.faces.application.ApplicationWrapper.createConverter(ApplicationWrapper.java:420)
    at org.omnifaces.cdi.converter.ConverterManager.createConverter(ConverterManager.java:131)
    at org.omnifaces.cdi.converter.ConverterManager$Proxy$_$$_WeldClientProxy.createConverter(Unknown Source)
    at org.omnifaces.application.OmniApplication.createConverter(OmniApplication.java:83)
    at com.sun.faces.facelets.tag.jsf.ValueHolderRule$LiteralConverterMetadata.applyMetadata(ValueHolderRule.java:45)
    at com.sun.faces.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:40)
    at javax.faces.view.facelets.MetaTagHandler.setAttributes(MetaTagHandler.java:100)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.setAttributes(DelegatingMetaTagHandler.java:92)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.doNewComponentActions(ComponentTagHandlerDelegateImpl.java:453)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:155)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:52)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:46)
    at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:120)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:358)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:339)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:209)
    at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:251)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:209)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$0(WorkerThreadIOStrategy.java:90)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
    at java.lang.Thread.run(Thread.java:748)
</code>```

To solve the issue I have to recompile the project and the converter is correctly loaded...

Any idea to solve the issue ?

PS:
I'm using OpenJDK Runtime Environment (build 1.8.0_212-8u212-b03-0ubuntu1.16.04.1-b03) Linux Mint 18.3 Sylvia.

答: The issue has been solved on Payara Micro 5.192</p>

Body:
I've a Java EE 8 web project (war) with a JSF page that uses a converter.

When I try to load that page (after mvn clean compile package and java -jar payara-micro-5.191.jar --deploy rbooking.war) "sometimes" the converter class was not found.

To solve the problem the only solution is to recompile the war.

Here some details:

the pom file:

<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>sartorieinformatiche.it.rbooking</groupId>
  <artifactId>rbooking</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>

  <repositories>
    <repository>
      <id>prime-repo</id>
      <name>PrimeFaces Maven Repository</name>
      <url>http://repository.primefaces.org</url>
      <layout>default</layout>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-email</artifactId>
      <version>1.5</version>
    </dependency>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>8.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.primefaces</groupId>
      <artifactId>primefaces</artifactId>
      <version>7.0</version>
    </dependency>
    <dependency>
      <groupId>org.primefaces.themes</groupId>
      <artifactId>all-themes</artifactId>
      <version>1.0.10</version>
    </dependency>
    <dependency>
      <groupId>uaihebert.com</groupId>
      <artifactId>uaiCriteria</artifactId>
      <version>4.0.0</version>
    </dependency>
    <dependency>
      <groupId>org.omnifaces</groupId>
      <artifactId>omnifaces</artifactId>
      <version>3.3</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>rbooking</finalName>
  </build>
</project>

the converter class:

package sartorieinformatiche.it.rbooking.control;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;

import sartorieinformatiche.it.rbooking.entity.Language;

@FacesConverter(value = "languageConverter", managed = true)
public class LanguageConverter implements Converter<Language> {

  @Inject
  private LanguageService languageService;

  @Override
  public String getAsString(FacesContext context, UIComponent component, Language language) {
    if (language == null) {
      return "";
    }

    return language.getId().toString();
  }

  @Override
  public Language getAsObject(FacesContext context, UIComponent component, String value) {
    if (value == null || value.trim().isEmpty()) {
      return null;
    }

    Long id = Long.parseLong(value);

    return languageService.findById(id);
  }

}

the JSF page fragment:

...

  <f:selectItems value="#{bookingBean.allLanguages}"
                 itemLabel="#{language.description}"
                 itemValue="#{language.id}" />

      <h:outputText value="#{language.description}" />

...

the error when the JSF page is loaded:

  StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
javax.faces.FacesException: Expression Error: Named Object: languageConverter not found.
    at com.sun.faces.util.Util.notNullNamedObject(Util.java:467)
    at com.sun.faces.application.applicationimpl.InstanceFactory.createConverter(InstanceFactory.java:456)
    at com.sun.faces.application.ApplicationImpl.createConverter(ApplicationImpl.java:502)
    at javax.faces.application.ApplicationWrapper.createConverter(ApplicationWrapper.java:420)
    at org.omnifaces.cdi.converter.ConverterManager.createConverter(ConverterManager.java:131)
    at org.omnifaces.cdi.converter.ConverterManager$Proxy$_$$_WeldClientProxy.createConverter(Unknown Source)
    at org.omnifaces.application.OmniApplication.createConverter(OmniApplication.java:83)
    at com.sun.faces.facelets.tag.jsf.ValueHolderRule$LiteralConverterMetadata.applyMetadata(ValueHolderRule.java:45)
    at com.sun.faces.facelets.tag.MetadataImpl.applyMetadata(MetadataImpl.java:40)
    at javax.faces.view.facelets.MetaTagHandler.setAttributes(MetaTagHandler.java:100)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.setAttributes(DelegatingMetaTagHandler.java:92)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.doNewComponentActions(ComponentTagHandlerDelegateImpl.java:453)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:155)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
    at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:179)
    at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:111)
    at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:55)
    at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:52)
    at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:46)
    at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:120)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:358)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:339)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:209)
    at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:251)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:209)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$0(WorkerThreadIOStrategy.java:90)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
    at java.lang.Thread.run(Thread.java:748)

To solve the issue I have to recompile the project and the converter is correctly loaded...

Any idea to solve the issue ?

PS:
I'm using OpenJDK Runtime Environment (build 1.8.0_212-8u212-b03-0ubuntu1.16.04.1-b03) Linux Mint 18.3 Sylvia.


来源: stackexchange

问:
syntax.vim file is missing
I jumped on to a colleague's computer and tried opening a C++ file in vim, and got the following error -

```<code>E484: Can't open file /usr/local/share/vim/syntax/syntax.vim
</code>```

Interestingly, the location /usr/local/share/vim/ does not even exist. It looks like vim is installed in /usr/share/vim

I tried hacking the ~/.vimrc, but I think the ~/.vimrc is fine, because I ssh'ed into another machine, and vim was able to do syntax highlighting there.

This is on debian 7. Also, interestingly, when I did env from tcsh, I did not see VIMRUNTIME listed there.

Any suggestions?

答:
My case, did not detect /usr/share/vim/vim80/syntax/syntax.vim
since I updated....

my solution:

corrects the path

```<code>ln -s /usr/share/vim/vim81 /usr/share/vim/vim80
</code>```

corrects the access to colors/

```<code>ln -s /usr/share/vim/vim80/syntax/* .vim/colors/
</code>```

ContentLicense: CC BY-SA 3.0

Title: syntax.vim file is missing

Body:
I jumped on to a colleague's computer and tried opening a C++ file in vim, and got the following error -

E484: Can't open file /usr/local/share/vim/syntax/syntax.vim

Interestingly, the location /usr/local/share/vim/ does not even exist. It looks like vim is installed in /usr/share/vim

I tried hacking the ~/.vimrc, but I think the ~/.vimrc is fine, because I ssh'ed into another machine, and vim was able to do syntax highlighting there.

This is on debian 7. Also, interestingly, when I did env from tcsh, I did not see VIMRUNTIME listed there.

Any suggestions?

Body:
My case, did not detect /usr/share/vim/vim80/syntax/syntax.vim
since I updated....

my solution:

corrects the path

ln -s /usr/share/vim/vim81 /usr/share/vim/vim80

corrects the access to colors/

ln -s /usr/share/vim/vim80/syntax/* .vim/colors/

ContentLicense: CC BY-SA 4.0


问:
How to verify LEI checksum in java?
I am following https://en.wikipedia.org/wiki/International_Bank_Account_Number to verify the checksum of Legal Entity Identifier(LEI) with the following code:

```<code>import java. math. BigInteger;

public class LEIChecksumVerifier{

    public final String [] leiChars = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    public final String [] leiDigits = {"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35"};

    public boolean verifyLeiCheckSum(String lei){
        boolean result = false;
        String shiftedLei = "";
        String digitisedLei= "";
        BigInteger leiBigInt = new BigInteger("0");
        BigInteger leiDivisorBigInt = new BigInteger("97");
        BigInteger remainderBigInt = new BigInteger("0");

        if(lei != null){
            lei = lei.toUpperCase().trim();
            if(lei.length() == 20){
                //Step1: Shift the first 4 digits to the end
                shiftedLei =  lei.substring(4, 20).concat(lei.substring(0, 4));
                //System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei);
                digitisedLei= shiftedLei;
                //Step2: Replace the alphabets with their integer values
                for ( int e = 0; e < leiChars.length; e++){
                    digitisedLei= digitisedLei.replaceAll(leiChars[e], leiDigits[e]);
                }
                //System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei+"\tDigitised LEI: "+digitisedLei);
                leiBigInt = new BigInteger(digitisedLei);
                //System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei+"\tDigitised LEI: "+digitisedLei+"\t LEI Big Integer: "+leiBigInt);
                remainderBigInt = leiBigInt.mod(leiDivisorBigInt);
                System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei+"\tDigitised LEI: "+digitisedLei+"\t LEI Big Integer: "+leiBigInt+"\t "+lei+" mod 97 : "+remainderBigInt);
                //Step3: if digitiesedLEI mod 97 == 1, checksum is valid!
                result = remainderBigInt.equals(new BigInteger("1"));
            }else{
                System.out.println("Error: "+lei+" length "+lei.length()+" differs from its standard value 20!");
            }
        }else{
            System.out.println("Error: lei is null!");
        }
    System.out.println("LEI :"+lei+" has valid checksum:" + result+"!");
    return result;
    }

    public static void main(String [] args){
        LEIChecksumVerifier lEIChecksumVerifier = new LEIChecksumVerifier();
        //LEI of British Broadcasting Corporation : 5493-00-0IBP32UQZ0KL-24
        lEIChecksumVerifier.verifyLeiCheckSum("5493000IBP32UQZ0KL24");
    }
}
</code>```

But, it gives invalid checksum for a valid LEI.  Please guide me in proper LEI checksum verification!

答:
It's hard to find details, but https://github.com/EDumdum/iso-17442-java has an implementation.

The checksum in LEI is already at the end, all you have change in your code is skip the shifting step. Now it reports a valid checksum for me.

Title: How to verify LEI checksum in java?

Body:
I am following https://en.wikipedia.org/wiki/International_Bank_Account_Number to verify the checksum of Legal Entity Identifier(LEI) with the following code:

import java. math. BigInteger;

public class LEIChecksumVerifier{

    public final String [] leiChars = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    public final String [] leiDigits = {"10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35"};

    public boolean verifyLeiCheckSum(String lei){
        boolean result = false;
        String shiftedLei = "";
        String digitisedLei= "";
        BigInteger leiBigInt = new BigInteger("0");
        BigInteger leiDivisorBigInt = new BigInteger("97");
        BigInteger remainderBigInt = new BigInteger("0");

        if(lei != null){
            lei = lei.toUpperCase().trim();
            if(lei.length() == 20){
                //Step1: Shift the first 4 digits to the end
                shiftedLei =  lei.substring(4, 20).concat(lei.substring(0, 4));
                //System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei);
                digitisedLei= shiftedLei;
                //Step2: Replace the alphabets with their integer values
                for ( int e = 0; e < leiChars.length; e++){
                    digitisedLei= digitisedLei.replaceAll(leiChars[e], leiDigits[e]);
                }
                //System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei+"\tDigitised LEI: "+digitisedLei);
                leiBigInt = new BigInteger(digitisedLei);
                //System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei+"\tDigitised LEI: "+digitisedLei+"\t LEI Big Integer: "+leiBigInt);
                remainderBigInt = leiBigInt.mod(leiDivisorBigInt);
                System.out.println("LEI: "+lei+"\tShifted LEI: "+shiftedLei+"\tDigitised LEI: "+digitisedLei+"\t LEI Big Integer: "+leiBigInt+"\t "+lei+" mod 97 : "+remainderBigInt);
                //Step3: if digitiesedLEI mod 97 == 1, checksum is valid!
                result = remainderBigInt.equals(new BigInteger("1"));
            }else{
                System.out.println("Error: "+lei+" length "+lei.length()+" differs from its standard value 20!");
            }
        }else{
            System.out.println("Error: lei is null!");
        }
    System.out.println("LEI :"+lei+" has valid checksum:" + result+"!");
    return result;
    }

    public static void main(String [] args){
        LEIChecksumVerifier lEIChecksumVerifier = new LEIChecksumVerifier();
        //LEI of British Broadcasting Corporation : 5493-00-0IBP32UQZ0KL-24
        lEIChecksumVerifier.verifyLeiCheckSum("5493000IBP32UQZ0KL24");
    }
}

But, it gives invalid checksum for a valid LEI.  Please guide me in proper LEI checksum verification!


问:
Split Pandas Dataframe Into Sub Dataframes (not list of dataframes)
I am trying to split a dataframe into as many different dataframes as possible, and set the name of the new dataframe based on information being split.

EX:

call this dataframe 'df'

```<code>Name    ID    Number    Code    Name2
123     cp1    500      ABC      456
123     cp1    501      DEF      456
</code>```

I am trying to split this dataframe into chunks based on 'Number', and then rename these new dataframes accordingly.

The result would look like the following:

```<code>df500:
Name    ID    Number    Code    Name2
123     cp1    500      ABC      456

df501:
Name    ID    Number    Code    Name2
123     cp1    501      DEF      456
</code>```

Does pandas allow for something like this to be done?

答:
Create a dictionary by grouping:

```<code>d={'df_{}'.format(i):g for i,g in df.groupby('Number')}
</code>```

```<code>{'df_500':    Name   ID  Number Code  Name2
 0   123  cp1     500  ABC  456.0, 'df_501':    Name   ID  Number Code  Name2
 1   123  cp1     501  DEF    NaN}
</code>```

You can then call the keys of the dict like:

```<code>print(d['df_500'])
</code>```

```<code>   Name   ID  Number Code  Name2
0   123  cp1     500  ABC  456.0
</code>```

Body:
I am trying to split a dataframe into as many different dataframes as possible, and set the name of the new dataframe based on information being split.

EX:

call this dataframe 'df'

Name    ID    Number    Code    Name2
123     cp1    500      ABC      456
123     cp1    501      DEF      456

I am trying to split this dataframe into chunks based on 'Number', and then rename these new dataframes accordingly.

The result would look like the following:

df500:
Name    ID    Number    Code    Name2
123     cp1    500      ABC      456

df501:
Name    ID    Number    Code    Name2
123     cp1    501      DEF      456

Does pandas allow for something like this to be done?

Body:
Create a dictionary by grouping:

d={'df_{}'.format(i):g for i,g in df.groupby('Number')}

{'df_500':    Name   ID  Number Code  Name2
 0   123  cp1     500  ABC  456.0, 'df_501':    Name   ID  Number Code  Name2
 1   123  cp1     501  DEF    NaN}

You can then call the keys of the dict like:

print(d['df_500'])

   Name   ID  Number Code  Name2
0   123  cp1     500  ABC  456.0


问:
iOS + React Native - memory leaks
I'm considering making an iOS project in React Native. On iOS it's a big issue to find and fix so-called "retain cycles", i.e. when the two object store a strong reference to each other:

```<code>class Obj1 {
    var delegate: Obj2?
}

class Obj2 {
    var delegate: Obj1?
}

let obj1 = Obj1()
let obj2 = Obj2()

obj1.delegate = obj2
obj2.delegate = obj1
</code>```

Does the React Native has a concept of a memory leak or retain cycle? Would the similar code in the JS counterpart create a retain cycle in React Native environment?

How about passing a closure capturing self? Would that also create a memory leak in React Native?

Summary:

Would the listed sample code (rewritten to JS) cause a memory leak in RN?

Would capturing self in a closure cause a memory leak?

答:
You shouldn't really have two objects retaining strong references to each other, the delegate pattern is usually handled by having one strong and one weak reference, where the delegate is the weak one.

Now onto your questions:

Probably, but someone else might give you a better answer since I'm not entirely sure about RN.

Yes and no, depending on how you go about it.

If you use strong self, then definitely there will be a memory leak:

```<code>{ _ in
    self.doSomething()
}
</code>```

Better way is to use either weak self:

```<code>{ [weak self] _ in
    guard let self = self else { return }
    self.doSomething()
}
</code>```

or unowned self if you can guarantee self is available in the closure at all times:

```<code>{ [unowned self] _ in
    self.doSomething()
}
</code>```

Title: iOS + React Native - memory leaks

Body:
I'm considering making an iOS project in React Native. On iOS it's a big issue to find and fix so-called "retain cycles", i.e. when the two object store a strong reference to each other:

class Obj1 {
    var delegate: Obj2?
}

class Obj2 {
    var delegate: Obj1?
}

let obj1 = Obj1()
let obj2 = Obj2()

obj1.delegate = obj2
obj2.delegate = obj1

Does the React Native has a concept of a memory leak or retain cycle? Would the similar code in the JS counterpart create a retain cycle in React Native environment?

How about passing a closure capturing self? Would that also create a memory leak in React Native?

Summary:

Would the listed sample code (rewritten to JS) cause a memory leak in RN?

Would capturing self in a closure cause a memory leak?

Body:
You shouldn't really have two objects retaining strong references to each other, the delegate pattern is usually handled by having one strong and one weak reference, where the delegate is the weak one.

Now onto your questions:

Probably, but someone else might give you a better answer since I'm not entirely sure about RN.

Yes and no, depending on how you go about it.

If you use strong self, then definitely there will be a memory leak:

{ _ in
    self.doSomething()
}

Better way is to use either weak self:

{ [weak self] _ in
    guard let self = self else { return }
    self.doSomething()
}

or unowned self if you can guarantee self is available in the closure at all times:

{ [unowned self] _ in
    self.doSomething()
}


问:
How to enable logging in uwsgi?
Os: ubuntu16.04

The command in supervisor config file is :

command=uwsgi --socket 127.0.0.1:16657 --master --module web.wsgi --chdir /path/to/directory --env DJANGO_SETTINGS_MODULE=web.settings --processes 32 --threads 100 --max-requests=5000 --listen 65535 --vacuum -b 65535

How to enable in logging uwsgi?
or anywhere else to change the uwsgi.ini file?

i am using --logto path/to/store/log

but in log file we didn't get logs.

How to enable uwsgi logs and the logs should be in json format?

答:
```<code>daemonize= /home/ubuntu/sample/uwsgi.log
</code>```

Please add the above to your ini file, else refer this

Title: How to enable logging in uwsgi?

Body:
daemonize= /home/ubuntu/sample/uwsgi.log

Please add the above to your ini file, else refer this


问:
signal mapping issue with QlineEdit
I want to pass the argument to slot. so i'm using signal mapping . I'm passing the QlinEedit variable as a argument to the slot using setmapping . but my slot function is not calling.</p>

```<code>QSignalMapper* maper = new QSignalMapper (this) ;
connect(ui->step2,SIGNAL(returnPressed()),maper,SLOT(map()));
maper->setMapping(ui->step2,ui->step2);
connect (maper, SIGNAL(mapped(QLineEdit*)), this, SLOT(on_steps_returnPressed(QLineEdit*))) ;
</code>```

答:
The QSignalMapper class is deprecated and you should use the new signal/slots syntax with a lambda function:

```<code>connect(ui->step2, &QLineEdit::returnPressed, [=]() { this->on_steps_returnPressed(ui->step2); });
</code>```

You can also pass only the text inside you QLineEdit instead of a pointer on it:

```<code>connect(ui->step2, &QLineEdit::returnPressed, [=]() { this->on_steps_returnPressed(ui->step2->text()); });
</code>```

If you have to use a QSignalMapper anyway, you have to use the signal QSignalMapper::mapped(QWidget*). Since a slot has to have the same signature than the connected signal, on_steps_returnPressed becomes on_steps_returnPressed(QWidget*) (cast the parameter to a QLineEdit):

```<code>QSignalMapper* maper = new QSignalMapper (this) ;
connect(step2, SIGNAL(returnPressed()), maper, SLOT(map()));
maper->setMapping(step2, step2);
connect(maper, SIGNAL(mapped(QWidget*)), this, SLOT(on_steps_returnPressed(QWidget*)));
</code>```

Your slot should be something like that:

```<code>void on_steps_returnPressed(QWidget* widget)
{
    QLineEdit* edit = qobject_cast<QLineEdit*>(widget);
    if (!edit)
        return;
    label->setText(edit->text());
}
</code>```

A complete example to compare the two solutions:

```<code>class Widget: public QWidget
{
    Q_OBJECT
public:
    Widget(QWidget* parent=nullptr): QWidget(parent),
        lineEdit1(new QLineEdit(this)),
        lineEdit2(new QLineEdit(this)),
        label(new QLabel(this))
    {
        QVBoxLayout* layout = new QVBoxLayout(this);
        layout->addWidget(lineEdit1);
        layout->addWidget(lineEdit2);
        layout->addWidget(label);

        connect(lineEdit1, &QLineEdit::returnPressed, [=]() { this->on_steps_returnPressed(lineEdit1); });

        QSignalMapper* maper = new QSignalMapper (this) ;
        connect(lineEdit2, SIGNAL(returnPressed()), maper, SLOT(map()));
        maper->setMapping(lineEdit2, lineEdit2);
        connect(maper, SIGNAL(mapped(QWidget*)), this, SLOT(on_steps_returnPressed(QWidget*)));
    }

public slots:
    void on_steps_returnPressed(QLineEdit* edit)
    {
        label->setText(edit->text());
    }
    void on_steps_returnPressed(QWidget* widget)
    {
        QLineEdit* edit = qobject_cast<QLineEdit*>(widget);
        if (!edit)
            return;
        label->setText(edit->text());
    }
private:
    QLineEdit* lineEdit1;
    QLineEdit* lineEdit2;
    QLabel* label;
};
</code>```

Title: signal mapping issue with QlineEdit

Body:
I want to pass the argument to slot. so i'm using signal mapping . I'm passing the QlinEedit variable as a argument to the slot using setmapping . but my slot function is not calling.

QSignalMapper* maper = new QSignalMapper (this) ;
connect(ui->step2,SIGNAL(returnPressed()),maper,SLOT(map()));
maper->setMapping(ui->step2,ui->step2);
connect (maper, SIGNAL(mapped(QLineEdit*)), this, SLOT(on_steps_returnPressed(QLineEdit*))) ;

Body:
The QSignalMapper class is deprecated and you should use the new signal/slots syntax with a lambda function:

connect(ui->step2, &QLineEdit::returnPressed, [=]() { this->on_steps_returnPressed(ui->step2); });

You can also pass only the text inside you QLineEdit instead of a pointer on it:

connect(ui->step2, &QLineEdit::returnPressed, [=]() { this->on_steps_returnPressed(ui->step2->text()); });

If you have to use a QSignalMapper anyway, you have to use the signal QSignalMapper::mapped(QWidget*). Since a slot has to have the same signature than the connected signal, on_steps_returnPressed becomes on_steps_returnPressed(QWidget*) (cast the parameter to a QLineEdit):

QSignalMapper* maper = new QSignalMapper (this) ;
connect(step2, SIGNAL(returnPressed()), maper, SLOT(map()));
maper->setMapping(step2, step2);
connect(maper, SIGNAL(mapped(QWidget*)), this, SLOT(on_steps_returnPressed(QWidget*)));

Your slot should be something like that:

void on_steps_returnPressed(QWidget* widget)
{
    QLineEdit* edit = qobject_cast<QLineEdit*>(widget);
    if (!edit)
        return;
    label->setText(edit->text());
}

A complete example to compare the two solutions:

class Widget: public QWidget
{
    Q_OBJECT
public:
    Widget(QWidget* parent=nullptr): QWidget(parent),
        lineEdit1(new QLineEdit(this)),
        lineEdit2(new QLineEdit(this)),
        label(new QLabel(this))
    {
        QVBoxLayout* layout = new QVBoxLayout(this);
        layout->addWidget(lineEdit1);
        layout->addWidget(lineEdit2);
        layout->addWidget(label);

        connect(lineEdit1, &QLineEdit::returnPressed, [=]() { this->on_steps_returnPressed(lineEdit1); });

        QSignalMapper* maper = new QSignalMapper (this) ;
        connect(lineEdit2, SIGNAL(returnPressed()), maper, SLOT(map()));
        maper->setMapping(lineEdit2, lineEdit2);
        connect(maper, SIGNAL(mapped(QWidget*)), this, SLOT(on_steps_returnPressed(QWidget*)));
    }

public slots:
    void on_steps_returnPressed(QLineEdit* edit)
    {
        label->setText(edit->text());
    }
    void on_steps_returnPressed(QWidget* widget)
    {
        QLineEdit* edit = qobject_cast<QLineEdit*>(widget);
        if (!edit)
            return;
        label->setText(edit->text());
    }
private:
    QLineEdit* lineEdit1;
    QLineEdit* lineEdit2;
    QLabel* label;
};


问:
Is there any way to connect to specific readonly replica in Azure SQL DB Premium Read Scale-Out?
I would like to know is there any way to connect to one of readonly replicas?

I know if Azure SQL data base is Premium type and Read Scale-out is Enabled, I can have two readnonly replicas. For connecting to ANY of those replicas, I just need to put ApplicationIntent=ReadOnly; in my connection string.

Attached link about Read scale-out replicas
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-read-scale-out

Also I know that there are some load balancer that can switch from request from one readonly replica to another.

So, is there some approach to define what replica should I use, Replica1 or Replica2 for (for ex.) Analytics and PowerBi reports accordingly at the same time?

Server=tcp:.database.windows.net;Database=;ApplicationIntent=ReadOnly;User ID=;Password=;Trusted_Connection=False; Encrypt=True;

答:
No, not at this time - Per the documentation (in a 'Note' about half way down: https://learn.microsoft.com/en-us/azure/sql-database/sql-database-read-scale-out)

At any given time only one of the AlwaysON replicas is accessible by the ReadOnly sessions.

It seems that the system will choose which replica to use for the connection/session when the connection is initiated.


问:
How to durably rename a file in POSIX?
What's the correct way to durably rename a file in a POSIX file system?  Specifically wondering about fsyncs on the directories.  (If this depends on the OS/FS, I'm asking about Linux and ext3/ext4).

Note: there are other questions on StackOverflow about durable renames, but AFAICT they don't address fsync-ing the directories (which is what matters to me - I'm not even modifying file data).

I currently have (in Python):

```<code>dstdirfd = open(dstdirpath, O_DIRECTORY|O_RDONLY)
rename(srcdirpath + '/' + filename, dstdirpath + '/' + filename)
fsync(dstdirfd)
</code>```

Specific questions:

Does this also implicitly fsync the source directory?  Or might I end up with the file showing up in both directories after a power cycle (meaning I'd have to check the hard link count and manually perform recovery), i.e. it's impossible to guarantee a durably atomic move operation?

If I fsync the source directory instead of the destination directory, will that also implicitly fsync the destination directory?

Are there any useful related testing/debugging/learning tools (fault injectors, introspection tools, mock filesystems, etc.)?

Thanks in advance.

答:
The answer to your question is going to depend a lot on the specific OS being used, the type of filesystem being used and whether the source and dest are on the same device or not.

I'd start by reading the rename(2) man page on the platform you're using.

Title: How to durably rename a file in POSIX?

Body:
What's the correct way to durably rename a file in a POSIX file system?  Specifically wondering about fsyncs on the directories.  (If this depends on the OS/FS, I'm asking about Linux and ext3/ext4).

Note: there are other questions on StackOverflow about durable renames, but AFAICT they don't address fsync-ing the directories (which is what matters to me - I'm not even modifying file data).

I currently have (in Python):

dstdirfd = open(dstdirpath, O_DIRECTORY|O_RDONLY)
rename(srcdirpath + '/' + filename, dstdirpath + '/' + filename)
fsync(dstdirfd)

Specific questions:

Does this also implicitly fsync the source directory?  Or might I end up with the file showing up in both directories after a power cycle (meaning I'd have to check the hard link count and manually perform recovery), i.e. it's impossible to guarantee a durably atomic move operation?

If I fsync the source directory instead of the destination directory, will that also implicitly fsync the destination directory?

Are there any useful related testing/debugging/learning tools (fault injectors, introspection tools, mock filesystems, etc.)?

Thanks in advance.


问:
How will I set if account_status = 1 then I can able to login otherwise not able to login?
How will I set if account_status = 1 then I can able to login otherwise not able to login? email, phone and password must be there. This is the following code </p>

```<code>public function login(Request $request){

        if(Auth::attempt(['email' => request('email'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else if(Auth::attempt(['phone' => request('phone'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else{
            return response()->json(['error'=>'Unauthorised'], 401);
        }
    }
</code>```

答:
Your logic is correct but I have never seen a way of accessing request variables as you have mentioned:

```<code>request('email')
</code>```

Please use following format:

```<code>$request->input('email')
</code>```

So your code should be:

```<code>public function login(Request $request){
    if(Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'),
    'account_status'=> $request->input('account_status')])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        return response()->json(['success' => $success], $this-> successStatus);
    }
    else if(Auth::attempt(['phone' => $request->input('phone'), 'password' => $request->input('password'),
    'account_status'=> $request->input('account_status')])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        return response()->json(['success' => $success], $this-> successStatus);
    }
    else{
        return response()->json(['error'=>'Unauthorised'], 401);
    }
}
</code>```

I hope it helps

Body:
How will I set if account_status = 1 then I can able to login otherwise not able to login? email, phone and password must be there. This is the following code

public function login(Request $request){

        if(Auth::attempt(['email' => request('email'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else if(Auth::attempt(['phone' => request('phone'), 'password' => request('password'),
        'account_status'=> request('account_status')])){
            $user = Auth::user();
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            return response()->json(['success' => $success], $this-> successStatus);
        }
        else{
            return response()->json(['error'=>'Unauthorised'], 401);
        }
    }

Body:
Your logic is correct but I have never seen a way of accessing request variables as you have mentioned:

request('email')

Please use following format:

$request->input('email')

So your code should be:

public function login(Request $request){
    if(Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password'),
    'account_status'=> $request->input('account_status')])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        return response()->json(['success' => $success], $this-> successStatus);
    }
    else if(Auth::attempt(['phone' => $request->input('phone'), 'password' => $request->input('password'),
    'account_status'=> $request->input('account_status')])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        return response()->json(['success' => $success], $this-> successStatus);
    }
    else{
        return response()->json(['error'=>'Unauthorised'], 401);
    }
}

I hope it helps


问:
In Android, why the aar files can speed up compilation
In Android, why  the aar files can speed up compilation

I guess maybe because the content in aar file already compiled or it has the cache of compilation result

答:
AAR files are more similar to Jars than to Dlls for the following reason:

Dlls can be shared across applications where as AARs and jars are
  packaged in with your app.

AARs vs Jars:

The main difference between a Jar and a AAR is that AARs include
  resources such as layouts, drawables etc. This makes it a lot easier
  to create self-contained visual components. For example if you have
  multiple apps that use the same login screen, with Jars you could
  share classes but not the layout, styles, etc., you still had to
  duplicate them. With AARs everything is bundled in one neat package.

In conclusion, AARs are a big step in the right direction.

Note:
Similar attempts were made with apk-libs but they are now obsolete as AARs are much better.


问:
Issues while implementing jenkins docker image+chrome+ruby unknown error: Chrome failed to start: crashed (Selenium::WebDriver::Error::UnknownError)
I am trying to setup jenkins using the official jenkins docker image.

Dockerfile

```<code>FROM jenkins/jenkins:lts

USER root
RUN apt-get update && apt install -y ruby-full
RUN apt-get install -y curl
RUN apt -y autoremove
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
RUN apt-get install -y build-essential
RUN apt install -y wget
RUN gem install --no-ri --no-rdoc --format-executable rake
RUN gem install selenium-webdriver
RUN gem install bundler
RUN npm install -g node-mongo-seeds

#Permissions granted to jenkins user to do a gem install
RUN chown -R jenkins:jenkins /var/lib/gems
RUN apt-get install -y patch ruby-dev zlib1g-dev liblzma-dev
RUN chown -R jenkins:jenkins /usr/local/bin

# We need wget to set up the PPA and xvfb to have a virtual screen and unzip to install the Chromedriver
RUN apt-get install -y wget xvfb unzip

# Set up the Chrome PPA
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list

# Update the package list and install chrome
RUN apt-get update -y
RUN apt-get install -y google-chrome-stable

# Set up Chromedriver Environment variables
ENV CHROMEDRIVER_VERSION 2.35
ENV CHROMEDRIVER_DIR /chromedriver
RUN mkdir $CHROMEDRIVER_DIR

# Download and install Chromedriver
RUN wget -q --continue -P $CHROMEDRIVER_DIR "http://chromedriver.storage.googleapis.com/$CHROMEDRIVER_VERSION/chromedriver_linux64.zip"
RUN unzip $CHROMEDRIVER_DIR/chromedriver* -d $CHROMEDRIVER_DIR

# Put Chromedriver into the PATH
ENV PATH $CHROMEDRIVER_DIR:$PATH

USER jenkins
</code>```

While running the job the browser won't open and hit the localhost.
I tried hitting 'google.com' as well

```<code>google-chrome --headless --no-sandbox 'https://www.google.com'
</code>```

still no success

```<code>    Fontconfig warning: "/etc/fonts/fonts.conf", line 100: unknown element "blank"
[0531/130727.949511:ERROR:browser_process_sub_thread.cc(217)] Waited 17 ms for network service
</code>```

I am not able understand why jenkins user not able to open the browser.

Google Chrome 74.0.3729.169

ChromeDriver 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)

ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]

Jenkins 2.164.3

答:
This error message...

```<code>unknown error: Chrome failed to start: crashed (Selenium::WebDriver::Error::UnknownError)
</code>```

...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You are using chromedriver=2.35

Release Notes of chromedriver=2.35 clearly mentions the following :

Supports Chrome v62-64

You are using chrome=74.0

Release Notes of ChromeDriver v74.0 clearly mentions the following :

Supports Chrome v74

So there is a clear mismatch between ChromeDriver v2.35 and the Chrome Browser v74.0

Solution

Upgrade ChromeDriver to  current ChromeDriver v74.0 level.

Keep Chrome version at Chrome v74 level. (as per ChromeDriver v2.46 release notes)

Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Execute your @Test.

Body:
I am trying to setup jenkins using the official jenkins docker image.

Dockerfile

FROM jenkins/jenkins:lts

USER root
RUN apt-get update && apt install -y ruby-full
RUN apt-get install -y curl
RUN apt -y autoremove
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
RUN apt-get install -y build-essential
RUN apt install -y wget
RUN gem install --no-ri --no-rdoc --format-executable rake
RUN gem install selenium-webdriver
RUN gem install bundler
RUN npm install -g node-mongo-seeds

#Permissions granted to jenkins user to do a gem install
RUN chown -R jenkins:jenkins /var/lib/gems
RUN apt-get install -y patch ruby-dev zlib1g-dev liblzma-dev
RUN chown -R jenkins:jenkins /usr/local/bin

# We need wget to set up the PPA and xvfb to have a virtual screen and unzip to install the Chromedriver
RUN apt-get install -y wget xvfb unzip

# Set up the Chrome PPA
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list

# Update the package list and install chrome
RUN apt-get update -y
RUN apt-get install -y google-chrome-stable

# Set up Chromedriver Environment variables
ENV CHROMEDRIVER_VERSION 2.35
ENV CHROMEDRIVER_DIR /chromedriver
RUN mkdir $CHROMEDRIVER_DIR

# Download and install Chromedriver
RUN wget -q --continue -P $CHROMEDRIVER_DIR "http://chromedriver.storage.googleapis.com/$CHROMEDRIVER_VERSION/chromedriver_linux64.zip"
RUN unzip $CHROMEDRIVER_DIR/chromedriver* -d $CHROMEDRIVER_DIR

# Put Chromedriver into the PATH
ENV PATH $CHROMEDRIVER_DIR:$PATH

USER jenkins

While running the job the browser won't open and hit the localhost.
I tried hitting 'google.com' as well

google-chrome --headless --no-sandbox 'https://www.google.com'

still no success

    Fontconfig warning: "/etc/fonts/fonts.conf", line 100: unknown element "blank"
[0531/130727.949511:ERROR:browser_process_sub_thread.cc(217)] Waited 17 ms for network service

I am not able understand why jenkins user not able to open the browser.

Google Chrome 74.0.3729.169

ChromeDriver 2.35.528139 (47ead77cb35ad2a9a83248b292151462a66cd881)

ruby 2.3.3p222 (2016-11-21) [x86_64-linux-gnu]

Jenkins 2.164.3

Body:
This error message...

unknown error: Chrome failed to start: crashed (Selenium::WebDriver::Error::UnknownError)

...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You are using chromedriver=2.35

Release Notes of chromedriver=2.35 clearly mentions the following :

Supports Chrome v62-64

You are using chrome=74.0

Release Notes of ChromeDriver v74.0 clearly mentions the following :

Supports Chrome v74

So there is a clear mismatch between ChromeDriver v2.35 and the Chrome Browser v74.0

Solution

Upgrade ChromeDriver to  current ChromeDriver v74.0 level.

Keep Chrome version at Chrome v74 level. (as per ChromeDriver v2.46 release notes)

Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.

Execute your @Test.


问:
Can't hide dark line under nav bar - setBackgroundImage/shadow not working

There is a fine dark line between the navigation bar and the segmented control shown above. I need to try and remove this line.

The navigation bar is not translucent (and I don't want it to be).

I have tried this code but it's not working:

```<code>@IBOutlet var navBar: UINavigationBar!

self.navBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navBar.shadowImage = UIImage()
</code>```

I have tried the solutions in linked answers and they do not work. This question has the same problem but the answers are the same and they don't work.

答:
A pretty simple solution to hide the line would be</p>

```<code>override func viewDidLoad()
{
    super.viewDidLoad()

    self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
}
</code>```

Body:
There is a fine dark line between the navigation bar and the segmented control shown above. I need to try and remove this line.

The navigation bar is not translucent (and I don't want it to be).

I have tried this code but it's not working:

@IBOutlet var navBar: UINavigationBar!

self.navBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navBar.shadowImage = UIImage()

I have tried the solutions in linked answers and they do not work. This question has the same problem but the answers are the same and they don't work.

Body:
A pretty simple solution to hide the line would be

override func viewDidLoad()
{
    super.viewDidLoad()

    self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
}


问:
Javascript, yet another "too much recursion" issue: Revenge of evil eval()
I'm working on a project (a very old one who was revived) for a client.

When I browse one of the JSPs of the project in Firefox (4.0 in this case, but I suppose it happens with 3.x also), the following error appears on Firebug console:

Error: too much recursion

   Archivo fuente: https://localhost:9443/ClientProjectWeb/js/Object.js

   Línea: 226

Here is the code snippet of that line:

```<code>if(gControl){giveFocusToControl(gControl.name);}
</code>```

This is the invoked function:

```<code>function giveFocusToControl(nombreControl){
    var forma = document.forms[0];
    var campo = null;
    if(forma){
        var elemento = eval("forma."+nombreControl);
        if(eval(elemento.length)){
            if(elemento.type == "select-one" || elemento.type == "select-multiple"){
                campo = elemento;
            }else{
                campo = elemento[0];
            }
        }else{
            campo = elemento;
        }

        if(campo.style && campo.style.visibility){
            if(campo.style.visibility != "hidden"){
                campo.focus();
            }
        }else{
            campo.focus();
        }
    }
}
</code>```

I suspect this has to do with eval() calls inside a function, but despite I have tried to replace those "evil" calls with [] alternative proposed in this document, for example: var elemento = forma[nombreControl];, I haven't got the expected result, the error still is there: same line, same message.

Please do you have any suggestion? Thanks in advance.

答: The campo.focus() is where I would start my investigation.  I would put an alert just before each all to campo.focus() and check if the alert gets called multiple times.  If this is the case you will need to consider where the giveFocusToContol() method is being called.  The eval calls in this method are not really necessary.  Without playing with the code I would say the first eval could be replaced with forma.controls[nombeControl];  I would definately have to play with the second call to get the best way to evaluate it.  The purpose of the if(eval(elemento.length)) is basically a test to see if the control in question is a list.

Body:
I'm working on a project (a very old one who was revived) for a client.

When I browse one of the JSPs of the project in Firefox (4.0 in this case, but I suppose it happens with 3.x also), the following error appears on Firebug console:

Error: too much recursion

   Archivo fuente: https://localhost:9443/ClientProjectWeb/js/Object.js

   Línea: 226

Here is the code snippet of that line:

if(gControl){giveFocusToControl(gControl.name);}

This is the invoked function:

function giveFocusToControl(nombreControl){
    var forma = document.forms[0];
    var campo = null;
    if(forma){
        var elemento = eval("forma."+nombreControl);
        if(eval(elemento.length)){
            if(elemento.type == "select-one" || elemento.type == "select-multiple"){
                campo = elemento;
            }else{
                campo = elemento[0];
            }
        }else{
            campo = elemento;
        }

        if(campo.style && campo.style.visibility){
            if(campo.style.visibility != "hidden"){
                campo.focus();
            }
        }else{
            campo.focus();
        }
    }
}

I suspect this has to do with eval() calls inside a function, but despite I have tried to replace those "evil" calls with [] alternative proposed in this document, for example: var elemento = forma[nombreControl];, I haven't got the expected result, the error still is there: same line, same message.

Please do you have any suggestion? Thanks in advance.


问:
Hidden text animation is not working properly
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}</code>```

  <button>
</button>

some text

```

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

答:
Here's a solution with pure CSS and :after pseudo element:

div {
  position: relative;
  width: 10em;
}
p {
  text-align: center;
  transform: translateY(4rem);
}
p:after {
  content: "";
  display: block;
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
  transition: all .3s ease 0s;
  transform: translateY(-5rem);
}
div:hover p:after {
  transform: translateY(-12rem);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>some text</p>
</div></code>```

Body:
I want to make a similar page as this one: https://lp.anzi.kr/?page=listeners.
When you hover over a button, it moves up and some text will show with a background.

I try to make this with the following code: https://jsfiddle.net/rcv8b0kh/3/

$button = document.querySelector('button');
$textcontent = document.querySelector('.textcontent');

if ($button.hover) {
  $textcontent.classList.add('active')
}

button {
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
}

button:hover {
  box-shadow: 0px 4rem 6rem -2rem rgba(0, 0, 0, 0.57);
  -moz-box-shadow: 0px 2px 40px -10px rgba(0, 0, 0, 0.57);
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s;
  border: none;
}

.textcontent {
  visibility: hidden;
}

.active {
  visibility: 1;
  transform: translateY(-3.5rem);
  transition: all .3s ease 0s background-color: black;
  color: white
}

  <button>
</button>

some text

I also see people using ::before and ::after for these kind of animations but I don't really know how to implement them here.

Body:
Here's a solution with pure CSS and :after pseudo element:

div {
  position: relative;
  width: 10em;
}
p {
  text-align: center;
  transform: translateY(4rem);
}
p:after {
  content: "";
  display: block;
  background-color: red;
  border-radius: 50%;
  width: 10rem;
  height: 10rem;
  transition: all .3s ease 0s;
  transform: translateY(-5rem);
}
div:hover p:after {
  transform: translateY(-12rem);
}

<div>
  <p>some text</p>
</div>


问:
How to extract all non-nan values in this dataframe by the non-nan values count of each row
I want to extract the non-nan values in each row of dataframe.

I get a dataframe whose number of rows is more than 3000 as follows:

```<code># this is just an example, not whole data
  l1     l2     l3
0 2      nan    nan
1 1      nan    nan
2 3      4      nan
3 1      2      4
4 3      2      nan
5 4      1      2
6 5      nan    nan
</code>```

And I want to extract all non-nan values in this dataframe by the non-nan values count of each row like follows

```<code>one_non_nan_value_counts
    l1
0   2
1   1
2   5

two_non_nan_value_counts
    l1    l2
0   3     4
1   3     2

three_non_nan_value_counts
    l1    l2    l3
0   1     2     4
1   4     1     2
</code>```

Could any help me?

Thanks in advance.

答:
IIUC:

```<code>for x,y in df.groupby(df.isna().sum(axis=1)):
    print('nan', x)
    print(y.dropna(axis=1))
</code>```

output:

```<code>nan 0
   l1   l2   l3
3   1  2.0  4.0
5   4  1.0  2.0
nan 1
   l1   l2
2   3  4.0
4   3  2.0
nan 2
   l1
0   2
1   1
6   5
</code>```

Body:
I want to extract the non-nan values in each row of dataframe.

I get a dataframe whose number of rows is more than 3000 as follows:

# this is just an example, not whole data
  l1     l2     l3
0 2      nan    nan
1 1      nan    nan
2 3      4      nan
3 1      2      4
4 3      2      nan
5 4      1      2
6 5      nan    nan

And I want to extract all non-nan values in this dataframe by the non-nan values count of each row like follows

one_non_nan_value_counts
    l1
0   2
1   1
2   5

two_non_nan_value_counts
    l1    l2
0   3     4
1   3     2

three_non_nan_value_counts
    l1    l2    l3
0   1     2     4
1   4     1     2

Could any help me?

Thanks in advance.

Body:
IIUC:

for x,y in df.groupby(df.isna().sum(axis=1)):
    print('nan', x)
    print(y.dropna(axis=1))

output:

nan 0
   l1   l2   l3
3   1  2.0  4.0
5   4  1.0  2.0
nan 1
   l1   l2
2   3  4.0
4   3  2.0
nan 2
   l1
0   2
1   1
6   5


问:
How to do DNS lookup of an ip range using shell script
How to do DNS lookup of an IP range using shell script

when I do dig -x and provide an ip i get reverser DNS for the respective ip. However if I give range either CIDRs or ip range from & to thats a long manual process, which I want to get it working using shell script.

I tried

```<code>dig -x 1x.xx.xx.xx

;; ANSWER SECTION:

1x.xx.xx.xx.foo.addr. port IN   PTR

</code>```

I want to see reverse DNS of all ips falling in that range when I pass either
1x.xx.xx.xx/24
or
1x.xx.xx.xx - 1x.xx.xx.xxx

答:
I got the way to do this.
using nmap we can achieve this.

nmap -sL 4x.xx.xx.0/24 | awk '/Nmap scan report/{print $NF}' | xargs -I % bash -c 'echo "%: $(dig -x % +short)"'

output

```<code>41.74.205.0:
4x.xx.xx.1:a2b-foo.c.
4x.xx.xx.2:a2b-foo.c.
4x.xx.xx.3:
4x.xx.xx.4:
4x.xx.xx.5:
4x.xx.xx.6:
41.74.205.7:foo-smtp-delivery-foo.com.
41.74.205.8:foo-smtp-delivery-foo.com.
41.74.205.9:foo-smtp-delivery-foo.com.
41.74.205.10:foo-smtp-delivery-foo.com.

</code>```

I was expecting this way. I can now create a shell script and ask for an input range and show this sort of output.

Body:
How to do DNS lookup of an IP range using shell script

when I do dig -x and provide an ip i get reverser DNS for the respective ip. However if I give range either CIDRs or ip range from & to thats a long manual process, which I want to get it working using shell script.

I tried

dig -x 1x.xx.xx.xx

;; ANSWER SECTION:

1x.xx.xx.xx.foo.addr. port IN   PTR

I want to see reverse DNS of all ips falling in that range when I pass either
1x.xx.xx.xx/24
or
1x.xx.xx.xx - 1x.xx.xx.xxx

Body:
I got the way to do this.
using nmap we can achieve this.

nmap -sL 4x.xx.xx.0/24 | awk '/Nmap scan report/{print $NF}' | xargs -I % bash -c 'echo "%: $(dig -x % +short)"'

output

41.74.205.0:
4x.xx.xx.1:a2b-foo.c.
4x.xx.xx.2:a2b-foo.c.
4x.xx.xx.3:
4x.xx.xx.4:
4x.xx.xx.5:
4x.xx.xx.6:
41.74.205.7:foo-smtp-delivery-foo.com.
41.74.205.8:foo-smtp-delivery-foo.com.
41.74.205.9:foo-smtp-delivery-foo.com.
41.74.205.10:foo-smtp-delivery-foo.com.

I was expecting this way. I can now create a shell script and ask for an input range and show this sort of output.


问:
Lose window.history.state after page refresh in Firefox Quantum
I do not know if a problem in the history library or browser, but ...

I am working on Firefox Quantum 57.0.4 64 bit, and when I select the url and press enter, after updating the page I can not get the history.location.state. After investigating, I discovered that window.history.state is null.

Does anyone have this error?

答:
I'm not sure whether or not this is a bug in Firefox, because in other browsers (i.e. Chrome/IE11/Edge) it works fine using window.history.replaceState(null, null, url);.
The fix for FF seems to be using window.history.pushState(null, null, url);, as described here https://developer.mozilla.org/en-US/docs/Web/API/History_API
When using pushState you can press F5 and everything is fine.

Edit: Is a firefox bug and not fixed yet: https://bugzilla.mozilla.org/show_bug.cgi?id=1422334

Edit2: We currently use pushState instead of replaceState in FF (only in FF) until the mentioned bug is fixed.


问:
Batch insert in Yii
I need to insert multiple ActiveRecord object in Yii,if all of them inserted

```<code>$transaction = Yii::app()->db->beginTransaction();
for ($i = 0;$i < 10;$i++){
    $model = new Mymodel();
    $model->x = $i;
    if (!$model->save()){
        $transaction->rollback();
        break;
    }
}
if ($transaction->active)
    $transaction->commit();
</code>```

Now I need to insert all of them in one query,How can I do it during using active record?

答:
Since Yii 1.1.14 there is CDbCommandBuilder::createMultipleInsertCommand() method available. If you need to insert multiple records in one query, you should probably use it, since all other answers in this question are vulnerable to SQL injection, so it is easy to mess up something if you're trying to implement something like that by yourself.

```<code>Yii::app()->db->getCommandBuilder()
    ->createMultipleInsertCommand('table_name', $data)
    ->execute();
</code>```

For array of models you can probably generate $data in this way (note that it will not make any validation):

```<code>$data = [];
foreach ($models as $model) {
    $data[] = $model->getAttributes();
}
</code>```

Title: Batch insert in Yii

Body:
I need to insert multiple ActiveRecord object in Yii,if all of them inserted

$transaction = Yii::app()->db->beginTransaction();
for ($i = 0;$i < 10;$i++){
    $model = new Mymodel();
    $model->x = $i;
    if (!$model->save()){
        $transaction->rollback();
        break;
    }
}
if ($transaction->active)
    $transaction->commit();

Now I need to insert all of them in one query,How can I do it during using active record?

Body:
Since Yii 1.1.14 there is CDbCommandBuilder::createMultipleInsertCommand() method available. If you need to insert multiple records in one query, you should probably use it, since all other answers in this question are vulnerable to SQL injection, so it is easy to mess up something if you're trying to implement something like that by yourself.

Yii::app()->db->getCommandBuilder()
    ->createMultipleInsertCommand('table_name', $data)
    ->execute();

For array of models you can probably generate $data in this way (note that it will not make any validation):

$data = [];
foreach ($models as $model) {
    $data[] = $model->getAttributes();
}


问:
Accessing namespace Within XML to parse the correct data PHP/Laravel
I'm currently trying to parse some sweet sweet XML, only to realise that i have no idea how to access the namespacing, i need to parse the English.

is anyone so kind a to help a brother out x

link to xml = https://xml.inmobalia.com/361/e55d03759a1004da29b3e364faaff2e1.xml

for example

```<code><property>
    <descriptions>
        <property_desc lang="en">
        </property_desc>
        <property_desc lang="es">
        </property_desc>
    </descriptions>
</property>
</code>```

PHP - here what I've tried

```<code>foreach ($data as $key => $val) {
    $filterd[$key]['main_advert_1'] = json_encode([
        "main_advert" => (isset($val['descriptions']['long_description']['en'])
            and !empty($val['descriptions']['long_description']['en'])
        )
        ? $val['descriptions']['long_description']['en'] : "N.A"]);
}
</code>```

答:
Another solution would be:

<?php

$xml = simplexml_load_file('https://xml.inmobalia.com/361/e55d03759a1004da29b3e364faaff2e1.xml')->children();
foreach ($xml->xpath('/properties/property') as $property) {
    echo '
'.$property->reference->__toString().'
';
    foreach ($property->xpath('descriptions/long_description[@lang="en"]') as $property) {
        echo $property->__toString();
    }
}
```

With this solution, you can access the other details of a property as well.

Body:
I'm currently trying to parse some sweet sweet XML, only to realise that i have no idea how to access the namespacing, i need to parse the English.

is anyone so kind a to help a brother out x

link to xml = https://xml.inmobalia.com/361/e55d03759a1004da29b3e364faaff2e1.xml

for example

<property>
    <descriptions>
        <property_desc lang="en">
        </property_desc>
        <property_desc lang="es">
        </property_desc>
    </descriptions>
</property>

PHP - here what I've tried

foreach ($data as $key => $val) {
    $filterd[$key]['main_advert_1'] = json_encode([
        "main_advert" => (isset($val['descriptions']['long_description']['en'])
            and !empty($val['descriptions']['long_description']['en'])
        )
        ? $val['descriptions']['long_description']['en'] : "N.A"]);
}

Body:
Another solution would be:

<?php

$xml = simplexml_load_file('https://xml.inmobalia.com/361/e55d03759a1004da29b3e364faaff2e1.xml')->children();
foreach ($xml->xpath('/properties/property') as $property) {
    echo '<h2>'.$property->reference->__toString().'</h2>';
    foreach ($property->xpath('descriptions/long_description[@lang="en"]') as $property) {
        echo $property->__toString();
    }
}

With this solution, you can access the other details of a property as well.


问:
Silverlight 3 class library
I'm currently working on a UI development project and it was decided to implement it in Silvelight. I understand that Microsoft developers try to minimize size of the distribution and that's why some (lots) of the classes in regular .NET Framework are not included. Is it expected to see more classes included in Silverlight 3 library?</p>

答:
As an aside, you can always use Reflector over the core .NET Framework libraries to obtain some of the missing "nice to haves" in code form.

Here's redgate's reflector: http://www.red-gate.com/products/reflector/

And here is the code I extracted and modified version of HttpUtility.ParseQueryString:

```<code>public IDictionary<string, string> ParseParams(string paramsString)
{
    if (string.IsNullOrEmpty(paramsString))
        throw new ArgumentNullException("paramsString");

    // convert to dictionary
    var dict = new Dictionary<string, string>();

    // remove the leading ?
    if (paramsString.StartsWith("?"))
        paramsString = paramsString.Substring(1);

    var length = paramsString.Length;

    for (var i = 0; i < length; i++) {
        var startIndex = i;
        var pivotIndex = -1;

        while (i < length) {
            char ch = paramsString[i];
            if (ch == '=') {
                if (pivotIndex < 0) {
                    pivotIndex = i;
                }
            } else if (ch == '&') {
                break;
            }
            i++;
        }

        string name;
        string value;
        if (pivotIndex >= 0) {
            name = paramsString.Substring(startIndex, pivotIndex - startIndex);
            value = paramsString.Substring(pivotIndex + 1, (i - pivotIndex) - 1);
        } else {
            name = paramsString.Substring(startIndex, i - startIndex);
            value = null;
        }

        dict.Add(UrlDecode(name), UrlDecode(value));

        // if string ends with ampersand, add another empty token
        if ((i == (length - 1)) && (paramsString[i] == '&'))
            dict.Add(null, string.Empty);
    }

    return dict;
}
</code>```

It's just an example, but as you can see, .. if what you really need is already inside the .NET BCL... then why re-implement it? Just decompile the thing and re-implement it in Silverlight.

IMO most of what you'll be decompiling will probably be basic vanilla stuff "nice to haves" thats missing in Silverlight anyway so I don't think this'll raise any legal concerns.

Of course, you could re-implement the querystring parsing logic yourself but as you can see there're all the little details in there that you could have missed not to mention performance concerns.

OwnerDisplayName: buckethead

ContentLicense: CC BY-SA 2.5

Title: Silverlight 3 class library

LastEditorDisplayName: buckethead

Body:
As an aside, you can always use Reflector over the core .NET Framework libraries to obtain some of the missing "nice to haves" in code form.

Here's redgate's reflector: http://www.red-gate.com/products/reflector/

And here is the code I extracted and modified version of HttpUtility.ParseQueryString:

public IDictionary<string, string> ParseParams(string paramsString)
{
    if (string.IsNullOrEmpty(paramsString))
        throw new ArgumentNullException("paramsString");

    // convert to dictionary
    var dict = new Dictionary<string, string>();

    // remove the leading ?
    if (paramsString.StartsWith("?"))
        paramsString = paramsString.Substring(1);

    var length = paramsString.Length;

    for (var i = 0; i < length; i++) {
        var startIndex = i;
        var pivotIndex = -1;

        while (i < length) {
            char ch = paramsString[i];
            if (ch == '=') {
                if (pivotIndex < 0) {
                    pivotIndex = i;
                }
            } else if (ch == '&') {
                break;
            }
            i++;
        }

        string name;
        string value;
        if (pivotIndex >= 0) {
            name = paramsString.Substring(startIndex, pivotIndex - startIndex);
            value = paramsString.Substring(pivotIndex + 1, (i - pivotIndex) - 1);
        } else {
            name = paramsString.Substring(startIndex, i - startIndex);
            value = null;
        }

        dict.Add(UrlDecode(name), UrlDecode(value));

        // if string ends with ampersand, add another empty token
        if ((i == (length - 1)) && (paramsString[i] == '&'))
            dict.Add(null, string.Empty);
    }

    return dict;
}

It's just an example, but as you can see, .. if what you really need is already inside the .NET BCL... then why re-implement it? Just decompile the thing and re-implement it in Silverlight.

IMO most of what you'll be decompiling will probably be basic vanilla stuff "nice to haves" thats missing in Silverlight anyway so I don't think this'll raise any legal concerns.

Of course, you could re-implement the querystring parsing logic yourself but as you can see there're all the little details in there that you could have missed not to mention performance concerns.

OwnerDisplayName: chakrit

LastEditorDisplayName: chakrit


问:
PHP generate random directory for fileupload
I need to generate random directories for user file uploads.
Is it wise to use the following function for this?

```<code>hash('md5', time())
</code>```

I don't want PHP to tamper with the filenames, that's why I thought about using directories for this.

答:
You could use a time based approach, as you are doing, but it is more wise to use microtime instead of time because the entropy is larger and thus the chance of collision is smaller.

An even better approach is to generate a really unique ID. You could use the build-in uniqid function (https://www.php.net/manual/en/function.uniqid.php) with the extra entropy option, or the excelent ramsey/uuid library (https://github.com/ramsey/uuid) that generates a strong unique identifier based on the RFC 4122 standard. The chance of collisions here is so small it is practically non-existent (see: https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions).

You could use an increment-approach, where you store/retrieve the amount of directories that already exist, but that will mean you have an extra load on your file system and you miss the possibility to make multiple directories asynchronously.

Good luck!

Body:
I need to generate random directories for user file uploads.
Is it wise to use the following function for this?

hash('md5', time())

I don't want PHP to tamper with the filenames, that's why I thought about using directories for this.


问:
setting Identityserver 'state' parameter as a GUID to correlate calls?
I wish to correlate all the calls throughout Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents (OnRedirectToIdentityProvider, OnAuthorizationCodeReceived etc).

I wish to set the 'state' parameter in OnRedirectToIdentityProvider as a GUID to later corralate the calls in logs, for example

```<code> OnRedirectToIdentityProvider = async context =>
 {
    var myGuid = Guid.NewGuid().ToString();
    context.ProtocolMessage.State = myGuid;
    _log.LogInformation("OnRedirectToIdentityProvider: {0}", myGuid);

  ...
 },
 OnAuthorizationCodeReceived = async context =>
 {
     _log.LogInformation("OnAuthorizationCodeReceived: {0}", context.ProtocolMessage.State);

  ...
 },
...
</code>```

In the docs it is said that identityserver will echo back the state value on the token response. http://docs.identityserver.io/en/latest/endpoints/authorize.html

I also read that client is responsible for the validation of this property.

The question is:

I couldn't find any specific resource about when I want to use 'state' property, whether the validation is handled automatically by the middleware or should I handle the validation myself in a callback function?

Is there any security risks I should consider when using GUID in a 'state' parameter?

Pros/cons I should consider?

Regards,
A

答:
This is a valid approach to use GUID as ProtocolMessage.State property value.

After setting ProtocolMessage.State in OnRedirectToIdentityProvider event

```<code>context.ProtocolMessage.State = myGuid;
</code>```

Found out from source code that data is being deserialized with StateDataFormat.Unprotect() method. I used this to debug

```<code>context.Options.StateDataFormat.Unprotect("CfDJ8...yr7Rpx3DyQMwPw")
</code>```

'state' value in query is actually a serialized AuthenticationProperties class.

The AuthenticationProperties class is generated by the middleware and ProtocolMessage.State value is actually stored as AuthenticationProperties.Items["OpenIdConnect.Userstate"] in the response.
As mentioned in the comment, middleware handles the validation of state.

Body:
I wish to correlate all the calls throughout Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents (OnRedirectToIdentityProvider, OnAuthorizationCodeReceived etc).

I wish to set the 'state' parameter in OnRedirectToIdentityProvider as a GUID to later corralate the calls in logs, for example

 OnRedirectToIdentityProvider = async context =>
 {
    var myGuid = Guid.NewGuid().ToString();
    context.ProtocolMessage.State = myGuid;
    _log.LogInformation("OnRedirectToIdentityProvider: {0}", myGuid);

  ...
 },
 OnAuthorizationCodeReceived = async context =>
 {
     _log.LogInformation("OnAuthorizationCodeReceived: {0}", context.ProtocolMessage.State);

  ...
 },
...

In the docs it is said that identityserver will echo back the state value on the token response. http://docs.identityserver.io/en/latest/endpoints/authorize.html

I also read that client is responsible for the validation of this property.

The question is:

I couldn't find any specific resource about when I want to use 'state' property, whether the validation is handled automatically by the middleware or should I handle the validation myself in a callback function?

Is there any security risks I should consider when using GUID in a 'state' parameter?

Pros/cons I should consider?

Regards,
A

Body:
This is a valid approach to use GUID as ProtocolMessage.State property value.

After setting ProtocolMessage.State in OnRedirectToIdentityProvider event

context.ProtocolMessage.State = myGuid;

Found out from source code that data is being deserialized with StateDataFormat.Unprotect() method. I used this to debug

context.Options.StateDataFormat.Unprotect("CfDJ8...yr7Rpx3DyQMwPw")

'state' value in query is actually a serialized AuthenticationProperties class.

The AuthenticationProperties class is generated by the middleware and ProtocolMessage.State value is actually stored as AuthenticationProperties.Items["OpenIdConnect.Userstate"] in the response.
As mentioned in the comment, middleware handles the validation of state.


问:
When using services.AddHttpClient, where is the HttpClient created?
I am trying to understand how HttpClient has been implemented for Captcha in Nop Commerce and for the sake of testability how creating new instance of HttpClient has been manage in Nop Commerce project.

I came across ValidateCaptchaAttribute and ValidateCaptchaFilter and I see HttpClient has been wrapped inside CaptchaHttpClient class
but I don't understand from where does CaptchaHttpClient receive dependency for HttpClient and from where constructor of CaptchaHttpClient class is being called.

Inside ServiceCollectionExtensions class I see below code:

```<code>public static void AddNopHttpClients(this IServiceCollection services)
 {
    //default client
    services.AddHttpClient(NopHttpDefaults.DefaultHttpClient).WithProxy();

    //client to request current store
    services.AddHttpClient<StoreHttpClient>();

    //client to request nopCommerce official site
    services.AddHttpClient<NopHttpClient>().WithProxy();

    //client to request reCAPTCHA service
    services.AddHttpClient<CaptchaHttpClient>().WithProxy();
 }
</code>```

But I don't see where HttpClient object is created:

```<code>var client = new HttpClient() // Where this is done?
</code>```

Am I perhaps missing something?

Nop Commerce Version = 4.20

答:
From the documentation:

Adds the IHttpClientFactory and related services to the IServiceCollection and configures a binding between the TClient type and a named HttpClient. The client name will be set to the type name of TClient.

Roughly translated, services.AddHttpClient<CaptchaHttpClient>() means that CaptchaHttpClient has a dependency on HttpClient. This says that when injecting HttpClient into CaptchaHttpClient, don't just create a new one - use an implementation of IHttpClientFactory to provide one and inject the HttpClient it creates.

This means that you're not managing the lifetime of the HttpClient. The ServiceProvider is doing that behind the scenes. (You're not responsible for creating the client factory either.)

This documentation explains why this exists and how it works.

A Typed Client is, effectively, a transient object, meaning that a new instance is created each time one is needed and it will receive a new HttpClient instance each time it's constructed. However, the HttpMessageHandler objects in the pool are the objects that are reused by multiple Http requests.

This means:

The thing you're registering - in this case CaptchaHttpClient is transient so that each time it's resolved, a new instance is created.

Each time it is created, a new HttpClient is created and injected.

Although the HttpClient is new, the HttpMessageHandler it depends upon is reused.

This uses a pool of HttpMessageHandler instances that we don't have to manage. Our class just depends on HttpClient without having to worry about the negative side effects that happen when we create/dispose an HttpClient each time we need one.

Body:
I am trying to understand how HttpClient has been implemented for Captcha in Nop Commerce and for the sake of testability how creating new instance of HttpClient has been manage in Nop Commerce project.

I came across ValidateCaptchaAttribute and ValidateCaptchaFilter and I see HttpClient has been wrapped inside CaptchaHttpClient class
but I don't understand from where does CaptchaHttpClient receive dependency for HttpClient and from where constructor of CaptchaHttpClient class is being called.

Inside ServiceCollectionExtensions class I see below code:

public static void AddNopHttpClients(this IServiceCollection services)
 {
    //default client
    services.AddHttpClient(NopHttpDefaults.DefaultHttpClient).WithProxy();

    //client to request current store
    services.AddHttpClient<StoreHttpClient>();

    //client to request nopCommerce official site
    services.AddHttpClient<NopHttpClient>().WithProxy();

    //client to request reCAPTCHA service
    services.AddHttpClient<CaptchaHttpClient>().WithProxy();
 }

But I don't see where HttpClient object is created:

var client = new HttpClient() // Where this is done?

Am I perhaps missing something?

Nop Commerce Version = 4.20


问:
How to setup an EJB timerDataSource in Open Liberty
I try to deploy a Java EE Application containing several EJB Timer Services (with persistence=true).
The server complains that no datasource was defined:

```<code>Caused by: javax.ejb.EJBException: See nested exception; nested exception is: java.lang.IllegalStateException: The ejbPersistentTimer feature is enabled, but the defaultEJBPersistentTimerExecutor persistent executor cannot be resolved. The most likely cause is that the DefaultDataSource datasource has not been configured. Persistent EJB timers require a datasource configuration for persistence.
</code>```

The ejbPersistentTimer-3.2 feature is turned on.
I can not find an example how to configure such a datasource in the server.xml file

I tried:

```<code><dataSource id="timerDataSource" jndiName="jdbc/timerDataSource">
</dataSource>

<databaseStore id="EJBTimerDatabaseStore"
    tablePrefix="EJBTimer_" dataSourceRef="timerDataSource" />
<persistentExecutor
    id="defaultEJBPersistentTimerExecutor"
    taskStoreRef="EJBTimerDatabaseStore" />
</code>```

But this seems to be not enoght? Did I need to activate DerbyDB as a feature too?

答:
It looks like your <dataSource> configuration is missing a few items:

A <jdbcDriver> which points to the JDBC driver jar that corresponds with the DB you are using

A <properties> element which identifies DB properties such as the DB server's hostname, port, and DB name.

Since you mentioned using DerbyDB, here is an example of what Derby config might look like:

<dataSource id="timerDataSource" jndiName="jdbc/timerDataSource">
    <jdbcDriver libraryRef="DerbyLib"/>
    <properties.derby.embedded databaseName="${server.config.dir}/data/EJBTimerDB" createDatabase="create"/>
</dataSource>

<library id="DerbyLib">
    <fileset dir="${server.config.dir}/derbyDriverDir/"/>
</library>
```

For additional info on configuring DataSources in Liberty, check out this doc:

Configuring relational database connectivity in Liberty

Body:
I try to deploy a Java EE Application containing several EJB Timer Services (with persistence=true).
The server complains that no datasource was defined:

Caused by: javax.ejb.EJBException: See nested exception; nested exception is: java.lang.IllegalStateException: The ejbPersistentTimer feature is enabled, but the defaultEJBPersistentTimerExecutor persistent executor cannot be resolved. The most likely cause is that the DefaultDataSource datasource has not been configured. Persistent EJB timers require a datasource configuration for persistence.

The ejbPersistentTimer-3.2 feature is turned on.
I can not find an example how to configure such a datasource in the server.xml file

I tried:

<dataSource id="timerDataSource" jndiName="jdbc/timerDataSource">
</dataSource>

<databaseStore id="EJBTimerDatabaseStore"
    tablePrefix="EJBTimer_" dataSourceRef="timerDataSource" />
<persistentExecutor
    id="defaultEJBPersistentTimerExecutor"
    taskStoreRef="EJBTimerDatabaseStore" />

But this seems to be not enoght? Did I need to activate DerbyDB as a feature too?

Body:
It looks like your <dataSource> configuration is missing a few items:

A <jdbcDriver> which points to the JDBC driver jar that corresponds with the DB you are using

A <properties> element which identifies DB properties such as the DB server's hostname, port, and DB name.

Since you mentioned using DerbyDB, here is an example of what Derby config might look like:

<dataSource id="timerDataSource" jndiName="jdbc/timerDataSource">
    <jdbcDriver libraryRef="DerbyLib"/>
    <properties.derby.embedded databaseName="${server.config.dir}/data/EJBTimerDB" createDatabase="create"/>
</dataSource>

<library id="DerbyLib">
    <fileset dir="${server.config.dir}/derbyDriverDir/"/>
</library>

For additional info on configuring DataSources in Liberty, check out this doc:

Configuring relational database connectivity in Liberty