问:
java.util.zip.ZipException: invalid entry compressed size (expected 449 but got 455 bytes)
Copy files from one zipfile subfolder to other zipfile subfolder. version and folder are subfolders name getting from frontend.

```<code>public String restore(String jobId, String version, String folder) {
    String fileName = String.valueOf(jobId) + ".zip";
    String versions[] = version.replaceAll("'", "")
        .replace("[", "")
        .replace("]", "")
        .split(",");
    String folders[] = folder.replaceAll("'", "").replace("[", "").replace("]", "").split(",");
    ArrayList<String> listofVersion, listofFolder = new ArrayList<>();

    File destinationFile = new File(env.getProperty("file.path") + fileName);
    File sourceFile = new File(env.getProperty("file.arcivePath") + fileName);

    FileInputStream in;
    FileOutputStream out;
    ZipInputStream zin;
    ZipOutputStream zipout;
    int BUFFER = (int) sourceFile.length();

    if (!destinationFile.exists()) {
        try {
            out = new FileOutputStream(destinationFile);
            zipout = new ZipOutputStream(out); //I get the "out" object from the servlet which tells the content type and and final zip file location.
            ZipEntry zEntry, ze;
            in = new FileInputStream(sourceFile);
            zin = new ZipInputStream(in);
            while ((zEntry = zin.getNextEntry()) != null) {
                System.out.println(zEntry);
                String entry = zEntry.getName();
                String entryList[] = entry.split("/");
                if (zEntry.isDirectory() && (entryList.length <= 1)) {
                    zipout.putNextEntry(zEntry);
                } else {
                    if (entryList.length >= 2) {
                        listofVersion = listVersionRestore(fileName);
                        for (int j = 0; j < versions.length; j++) {
                            for (int i = 0; i < listofVersion.size(); i++) {
                                if (listofVersion.get(i).equals(versions[j])) {
                                    if ((entryList.length == 2) && entryList[1].equals(versions[j])) {
                                        zipout.putNextEntry(zEntry);
                                    }
                                    if (entryList.length >= 3) {
                                        listofFolder = listFolderRestore(fileName, versions[j]);
                                        for (int l = 0; l < folders.length; l++) {
                                            for (int k = 0; k < listofFolder.size(); k++) {
                                                if (listofFolder.get(k).equals(folders[l])) {
                                                    if ((entryList.length == 3) && entryList[1].equals(versions[j]) && entryList[2].equals(folders[l])) {
                                                        zipout.putNextEntry(zEntry);
                                                    }

                                                    if ((entryList.length == 4) && entryList[1].equals(versions[j]) && entryList[2].equals(folders[l])) {
                                                        zipout.putNextEntry(zEntry);
                                                        byte[] buffer = new byte[BUFFER];
                                                        int len = 0;
                                                        while ((len = zin.read(buffer)) != -1) {
                                                            zipout.write(buffer, 0, len);
                                                        }

                                                        zipout.closeEntry();
                                                        in.close();
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            zipout.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }
    } else {
        return "Already Exists";
    }
    return "RestoredSuccessfully";
}
</code>```

Getting error as follow:

```<code>java.util.zip.ZipException: invalid entry compressed size (expected 449 but got 455 bytes)
at java.util.zip.ZipOutputStream.closeEntry(Unknown Source)
at prj.iopo.filesystem.FileSystemHandler.restore(FileSystemHandler.java:148)
at prj.iopo.filesystem.FileSystemHandler$$FastClassBySpringCGLIB$$f51baf3f.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at prj.iopo.filesystem.FileSystemHandler$$EnhancerBySpringCGLIB$$6d76d700.restore(<generated>)
at prj.iopo.controller.JobController.restore(JobController.java:99)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)89765042/1/2l/FS-restore.txt
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:213)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
</code>```

I'm getting an error at zipout.closeEntry();
But I can't remove this line.

答:
```<code>static copyZip() throws IOException {
    try (final ZipInputStream zis = new ZipInputStream(...);
         final ZipOutputStream zos = new ZipOutputStream(...)
    ) {
        copyZipContent(zis, zos);
    }
}

static void copyZipContent(final ZipInputStream zis, final ZipOutputStream zos) throws IOException {
    ZipEntry zisEntry;
    while ((zisEntry = zis.getNextEntry()) != null) {
        ZipEntry zosEntry = new ZipEntry(zisEntry.getName());
        zosEntry.setComment(zisEntry.getComment());
        zosEntry.setExtra(zisEntry.getExtra());
        zos.putNextEntry(zosEntry);
        IOUtils.copy(zis, zos);
        zos.closeEntry();
    }
    zos.finish();
}
</code>```

Body:
Copy files from one zipfile subfolder to other zipfile subfolder. version and folder are subfolders name getting from frontend.

public String restore(String jobId, String version, String folder) {
    String fileName = String.valueOf(jobId) + ".zip";
    String versions[] = version.replaceAll("'", "")
        .replace("[", "")
        .replace("]", "")
        .split(",");
    String folders[] = folder.replaceAll("'", "").replace("[", "").replace("]", "").split(",");
    ArrayList<String> listofVersion, listofFolder = new ArrayList<>();

    File destinationFile = new File(env.getProperty("file.path") + fileName);
    File sourceFile = new File(env.getProperty("file.arcivePath") + fileName);

    FileInputStream in;
    FileOutputStream out;
    ZipInputStream zin;
    ZipOutputStream zipout;
    int BUFFER = (int) sourceFile.length();

    if (!destinationFile.exists()) {
        try {
            out = new FileOutputStream(destinationFile);
            zipout = new ZipOutputStream(out); //I get the "out" object from the servlet which tells the content type and and final zip file location.
            ZipEntry zEntry, ze;
            in = new FileInputStream(sourceFile);
            zin = new ZipInputStream(in);
            while ((zEntry = zin.getNextEntry()) != null) {
                System.out.println(zEntry);
                String entry = zEntry.getName();
                String entryList[] = entry.split("/");
                if (zEntry.isDirectory() && (entryList.length <= 1)) {
                    zipout.putNextEntry(zEntry);
                } else {
                    if (entryList.length >= 2) {
                        listofVersion = listVersionRestore(fileName);
                        for (int j = 0; j < versions.length; j++) {
                            for (int i = 0; i < listofVersion.size(); i++) {
                                if (listofVersion.get(i).equals(versions[j])) {
                                    if ((entryList.length == 2) && entryList[1].equals(versions[j])) {
                                        zipout.putNextEntry(zEntry);
                                    }
                                    if (entryList.length >= 3) {
                                        listofFolder = listFolderRestore(fileName, versions[j]);
                                        for (int l = 0; l < folders.length; l++) {
                                            for (int k = 0; k < listofFolder.size(); k++) {
                                                if (listofFolder.get(k).equals(folders[l])) {
                                                    if ((entryList.length == 3) && entryList[1].equals(versions[j]) && entryList[2].equals(folders[l])) {
                                                        zipout.putNextEntry(zEntry);
                                                    }

                                                    if ((entryList.length == 4) && entryList[1].equals(versions[j]) && entryList[2].equals(folders[l])) {
                                                        zipout.putNextEntry(zEntry);
                                                        byte[] buffer = new byte[BUFFER];
                                                        int len = 0;
                                                        while ((len = zin.read(buffer)) != -1) {
                                                            zipout.write(buffer, 0, len);
                                                        }

                                                        zipout.closeEntry();
                                                        in.close();
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            zipout.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }
    } else {
        return "Already Exists";
    }
    return "RestoredSuccessfully";
}

Getting error as follow:

java.util.zip.ZipException: invalid entry compressed size (expected 449 but got 455 bytes)
at java.util.zip.ZipOutputStream.closeEntry(Unknown Source)
at prj.iopo.filesystem.FileSystemHandler.restore(FileSystemHandler.java:148)
at prj.iopo.filesystem.FileSystemHandler$$FastClassBySpringCGLIB$$f51baf3f.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at prj.iopo.filesystem.FileSystemHandler$$EnhancerBySpringCGLIB$$6d76d700.restore(<generated>)
at prj.iopo.controller.JobController.restore(JobController.java:99)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:969)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:860)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)89765042/1/2l/FS-restore.txt
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:213)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

I'm getting an error at zipout.closeEntry();
But I can't remove this line.


来源: stackexchange

问:
Django: How to get current user in admin forms?
In Django's ModelAdmin, I need to display forms customized according to the permissions a user has. Is there a way of getting the current user object into the form class, so that i can customize the form in its __init__ method?

I think saving the current request in a thread local would be a possibility but this would be my last resort because I'm thinking it is a bad design approach.

答:
Here is what i did recently for a Blog:

```<code>class BlogPostAdmin(admin.ModelAdmin):
    form = BlogPostForm

    def get_form(self, request, *args, **kwargs):
        form = super(BlogPostAdmin, self).get_form(request, *args, **kwargs)
        form.current_user = request.user
        return form
</code>```

I can now access the current user in my forms.ModelForm by accessing self.current_user

ContentLicense: CC BY-SA 4.0

Body:
Here is what i did recently for a Blog:

class BlogPostAdmin(admin.ModelAdmin):
    form = BlogPostForm

    def get_form(self, request, *args, **kwargs):
        form = super(BlogPostAdmin, self).get_form(request, *args, **kwargs)
        form.current_user = request.user
        return form

I can now access the current user in my forms.ModelForm by accessing self.current_user


问:
Changing value of Java enum in debugger in Eclipse?
I am trying to force this expression in the if statement to be true in debugging:

```<code>enumFooValue = getValue()
if (enumFooValue == Foo.BAR)
</code>```

However, the value returned by getValue() is not Foo.BAR but Foo.BAZ. I have tried changing enumFooValue in the Eclipse debugger by changing the name to BAR and the ordinal value but this does not seem to work. I read that equality between an enum and another enum requires that the two objects be equal. Not sure how to proceed since I do not know the id of Foo.BAR if that is what is required.

答: Very simple: You do not try to change the ordinal or the name but the whole thing to Foo.BAR. </p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to force this expression in the if statement to be true in debugging:

enumFooValue = getValue()
if (enumFooValue == Foo.BAR)

However, the value returned by getValue() is not Foo.BAR but Foo.BAZ. I have tried changing enumFooValue in the Eclipse debugger by changing the name to BAR and the ordinal value but this does not seem to work. I read that equality between an enum and another enum requires that the two objects be equal. Not sure how to proceed since I do not know the id of Foo.BAR if that is what is required.


问:
Testing Ansible roles in Drone CI, systemd services not working
When testing Ansible roles, my systemd services fail to startup. This is the error I get,

```<code>TASK [memcached : Packages Present] ********************************************
changed: [localhost] => (item=[u'memcached', u'libmemcached'])

TASK [memcached : Service Enabled] *********************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Could not find the requested service memcached: host"}
</code>```

My .drone.yml

```<code>pipeline:
  build:
    image: samdoran/centos7-ansible
    privileged: true
    commands:
      - echo 'sslverify=0' >> /etc/yum.conf
      - yum install -y redhat-lsb-core python-devel openldap-devel git gcc gcc-c++ python2-pip
      - pip install -U pip tox
      - tox
</code>```

My docker-compose.yml

```<code>version: '2'

services:
  drone-server:
    image: drone/drone:0.8

    ports:
      - 8000:8000
      - 9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - /etc/ssl/certs/ca-bundle.crt:/etc/ssl/certs/ca-certificates.crt
    restart: always
    environment:
      - DRONE_OPEN=true
      - DRONE_HOST=https://example.server
      - DRONE_ADMIN=drone
      - DRONE_VOLUME=/etc/ssl/certs/ca-bundle.crt:/etc/ssl/certs/ca-certificates.crt
      - DRONE_GOGS_GIT_USERNAME=drone
      - DRONE_GOGS_GIT_PASSWORD=XXXXXXXX
      - DRONE_GOGS=true
      - DRONE_GOGS_URL=https://example.gogs
      - DRONE_SECRET=${DRONE_SECRET}

  drone-agent:
    image: drone/agent:0.8

    command: agent
    restart: always
    depends_on:
      - drone-server
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=${DRONE_SECRET}
      - DOCKER_API_VERSION=1.24
</code>```

I've tried to do a memcached install manually, starting a base centos:7 docker container from my fedora workstation, and the service starts as expected when --privileged. The drone dockers are running on a RHEL 7 host.  I have already set the repository to trusted, within the Drone interface.

答:
Add readonly rights to /sys/fs/cgroup to your volumessection:

    - /sys/fs/cgroup:/sys/fs/cgroup:ro

The full explanation here.

Body:
When testing Ansible roles, my systemd services fail to startup. This is the error I get,

TASK [memcached : Packages Present] ********************************************
changed: [localhost] => (item=[u'memcached', u'libmemcached'])

TASK [memcached : Service Enabled] *********************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Could not find the requested service memcached: host"}

My .drone.yml

pipeline:
  build:
    image: samdoran/centos7-ansible
    privileged: true
    commands:
      - echo 'sslverify=0' >> /etc/yum.conf
      - yum install -y redhat-lsb-core python-devel openldap-devel git gcc gcc-c++ python2-pip
      - pip install -U pip tox
      - tox

My docker-compose.yml

version: '2'

services:
  drone-server:
    image: drone/drone:0.8

    ports:
      - 8000:8000
      - 9000
    volumes:
      - /var/lib/drone:/var/lib/drone/
      - /etc/ssl/certs/ca-bundle.crt:/etc/ssl/certs/ca-certificates.crt
    restart: always
    environment:
      - DRONE_OPEN=true
      - DRONE_HOST=https://example.server
      - DRONE_ADMIN=drone
      - DRONE_VOLUME=/etc/ssl/certs/ca-bundle.crt:/etc/ssl/certs/ca-certificates.crt
      - DRONE_GOGS_GIT_USERNAME=drone
      - DRONE_GOGS_GIT_PASSWORD=XXXXXXXX
      - DRONE_GOGS=true
      - DRONE_GOGS_URL=https://example.gogs
      - DRONE_SECRET=${DRONE_SECRET}

  drone-agent:
    image: drone/agent:0.8

    command: agent
    restart: always
    depends_on:
      - drone-server
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - DRONE_SERVER=drone-server:9000
      - DRONE_SECRET=${DRONE_SECRET}
      - DOCKER_API_VERSION=1.24

I've tried to do a memcached install manually, starting a base centos:7 docker container from my fedora workstation, and the service starts as expected when --privileged. The drone dockers are running on a RHEL 7 host.  I have already set the repository to trusted, within the Drone interface.


问:
How to add object mask to call GetNetworkVlans using golang
```<code>func getPrivateVlan(env string) (string, error) {
// 1. Create a session
sess := session.New(user, pass)
// 2. Get a service
accountService := services.GetAccountService(sess)
// 3. Invoke a method:
vlans, err := accountService.GetNetworkVlans()
vlan := vlans[0]
log.Println(*vlan.Name)           //works
log.Println(*vlan.PrimaryRouter)  //Doesn't work
}
</code>```

The object returned is an array of vlans of type SoftLayer_Network_Vlan, https://sldn.softlayer.com/reference/datatypes/softlayer_network_vlan.
I am able to access the properties in column "Local Properties" (ie Name) but am unable to access the properties in column "Relational & Count Properties" (ie PrimaryRouter).
How can I add an object mask to my call in order to see these properties?

答:
The reason is that in order to obtain relational data from an object in the API you must declare an object mask in your API call, as far as I can see, it is not declared in your code, it should be something like this:

```<code>func getPrivateVlan(env string) (string, error) {
// 1. Create a session
sess := session.New(user, pass)
// 2. Get a service
accountService := services.GetAccountService(sess)

//declare Mask
object_mask := "id;name;primaryRouter"

// 3. Invoke a method including the Object mask:
vlans, err := accountService.Mask(object_mask).GetNetworkVlans()

vlan := vlans[0]
log.Println(*vlan.Name)           //works
log.Println(*vlan.PrimaryRouter)  //
}
</code>```

Try the following code for example:

```<code>package main

import (
"fmt"
"github.com/softlayer/softlayer-go/services"
"github.com/softlayer/softlayer-go/session"
"encoding/json"
)

func main() {
// SoftLayer API username and key
username := "set-me"
apikey   := "set-me"

// Create a session
sess := session.New(username, apikey)

// Get SoftLayer_Account service
service := services.GetAccountService(sess)

// Object-Mask to get specific Vlan's information
mask := "id;name;primaryRouter"

// Call to getNetworkVlans in order to retrieve vlans according to filter.
result, err := service.Mask(mask).GetNetworkVlans()
if err != nil {
    fmt.Printf("\n Unable to retrieve vlans:\n - %s\n", err)
    return
}

// Following helps to print the result in json format.
jsonFormat, jsonErr := json.MarshalIndent(result,"","     ")
if jsonErr != nil {
    fmt.Println(jsonErr)
    return
}
fmt.Println(string(jsonFormat))
}
</code>```

For more information please see below:

https://sldn.softlayer.com/article/object-masks#Property_Set

Body:
func getPrivateVlan(env string) (string, error) {
// 1. Create a session
sess := session.New(user, pass)
// 2. Get a service
accountService := services.GetAccountService(sess)
// 3. Invoke a method:
vlans, err := accountService.GetNetworkVlans()
vlan := vlans[0]
log.Println(*vlan.Name)           //works
log.Println(*vlan.PrimaryRouter)  //Doesn't work
}

The object returned is an array of vlans of type SoftLayer_Network_Vlan, https://sldn.softlayer.com/reference/datatypes/softlayer_network_vlan.
I am able to access the properties in column "Local Properties" (ie Name) but am unable to access the properties in column "Relational & Count Properties" (ie PrimaryRouter).
How can I add an object mask to my call in order to see these properties?

Body:
The reason is that in order to obtain relational data from an object in the API you must declare an object mask in your API call, as far as I can see, it is not declared in your code, it should be something like this:

func getPrivateVlan(env string) (string, error) {
// 1. Create a session
sess := session.New(user, pass)
// 2. Get a service
accountService := services.GetAccountService(sess)

//declare Mask
object_mask := "id;name;primaryRouter"

// 3. Invoke a method including the Object mask:
vlans, err := accountService.Mask(object_mask).GetNetworkVlans()

vlan := vlans[0]
log.Println(*vlan.Name)           //works
log.Println(*vlan.PrimaryRouter)  //
}

Try the following code for example:

package main

import (
"fmt"
"github.com/softlayer/softlayer-go/services"
"github.com/softlayer/softlayer-go/session"
"encoding/json"
)

func main() {
// SoftLayer API username and key
username := "set-me"
apikey   := "set-me"

// Create a session
sess := session.New(username, apikey)

// Get SoftLayer_Account service
service := services.GetAccountService(sess)

// Object-Mask to get specific Vlan's information
mask := "id;name;primaryRouter"

// Call to getNetworkVlans in order to retrieve vlans according to filter.
result, err := service.Mask(mask).GetNetworkVlans()
if err != nil {
    fmt.Printf("\n Unable to retrieve vlans:\n - %s\n", err)
    return
}

// Following helps to print the result in json format.
jsonFormat, jsonErr := json.MarshalIndent(result,"","     ")
if jsonErr != nil {
    fmt.Println(jsonErr)
    return
}
fmt.Println(string(jsonFormat))
}

For more information please see below:

https://sldn.softlayer.com/article/object-masks#Property_Set


问:
Sorted insert on a python list
Good morning everybody,
Here is my function that is supposed to make a recursive sorted insertion of a couple of data:

```<code>def sorted_insert(w_i,sim,neighbors):
    if neighbors==[]:
        neighbors.append((w_i,sim))
    elif neighbors[0][1]<sim:
        neighbors.insert(0,(w_i,sim))
    else:
        sorted_insert(w_i,sim,neighbors[1:])
    return neighbors
</code>```

The problem is, this function doesn't insert values in the middle, here is a series of insertions :

```<code>>>> n=[]
>>> n=sorted_insert("w1",0.6,n)
>>> n=sorted_insert("w1",0.3,n)
>>> n=sorted_insert("w1",0.5,n)
>>> n=sorted_insert("w1",0.8,n)
>>> n=sorted_insert("w1",0.7,n)
>>> n
[('w1', 0.8), ('w1', 0.6)]
</code>```

Is there someone that can correct my function ?
Thanks in advance.

答:
This should work.</p>

```<code>def sorted_insert(w_i,sim,neighbors, i=0):
    if len(neighbors) == i or sim > neighbors[i][1]:
        neighbors.insert(i, (w_i,sim))
    else:
        sorted_insert(w_i,sim,neighbors, i+1)
n=[]
sorted_insert("w1",0.6,n)
sorted_insert("w1",0.3,n)
sorted_insert("w1",0.5,n)
sorted_insert("w1",0.8,n)
sorted_insert("w1",0.7,n)
print n
# [('w1', 0.8), ('w1', 0.7), ('w1', 0.6), ('w1', 0.5), ('w1', 0.3)]
</code>```

Title: Sorted insert on a python list

Body:
Good morning everybody,
Here is my function that is supposed to make a recursive sorted insertion of a couple of data:

def sorted_insert(w_i,sim,neighbors):
    if neighbors==[]:
        neighbors.append((w_i,sim))
    elif neighbors[0][1]<sim:
        neighbors.insert(0,(w_i,sim))
    else:
        sorted_insert(w_i,sim,neighbors[1:])
    return neighbors

The problem is, this function doesn't insert values in the middle, here is a series of insertions :

>>> n=[]
>>> n=sorted_insert("w1",0.6,n)
>>> n=sorted_insert("w1",0.3,n)
>>> n=sorted_insert("w1",0.5,n)
>>> n=sorted_insert("w1",0.8,n)
>>> n=sorted_insert("w1",0.7,n)
>>> n
[('w1', 0.8), ('w1', 0.6)]

Is there someone that can correct my function ?
Thanks in advance.

Body:
This should work.

def sorted_insert(w_i,sim,neighbors, i=0):
    if len(neighbors) == i or sim > neighbors[i][1]:
        neighbors.insert(i, (w_i,sim))
    else:
        sorted_insert(w_i,sim,neighbors, i+1)
n=[]
sorted_insert("w1",0.6,n)
sorted_insert("w1",0.3,n)
sorted_insert("w1",0.5,n)
sorted_insert("w1",0.8,n)
sorted_insert("w1",0.7,n)
print n
# [('w1', 0.8), ('w1', 0.7), ('w1', 0.6), ('w1', 0.5), ('w1', 0.3)]


问:
Regarding the message of ignoring visible gpu devices
When running a tensorflow program leveraging GPU devices, I got the following message. What does the statement of Ignoring visible gpu
   device (device: 0, name: Quadro 5000, pci bus id: 0000:05:00.0) with Cuda
   compute capability 2.0. mean? What is to be ignored?

```<code>2017-12-04 16:06:17.784599: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with
properties:
name: Quadro 5000
major: 2 minor: 0 memoryClockRate (GHz) 1.026
pciBusID 0000:05:00.0
Total memory: 2.50GiB
Free memory: 2.22GiB
2017-12-04 16:06:17.784636: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0
2017-12-04 16:06:17.784645: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y
2017-12-04 16:06:17.784658: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:950] Ignoring visible gpu
device (device: 0, name: Quadro 5000, pci bus id: 0000:05:00.0) with Cuda
compute capability 2.0. The minimum required Cuda capability is 3.0.
</code>```

答:
TensorFlow prints this message when you have a GPU installed in the local machine but its compute capability is too low for TensorFlow to use that GPU for accelerated computation. As the error message states:

The minimum required Cuda capability is 3.0.

This means that you must use a CUDA-capable GPU with compute capability 3.0 or greater to use TensorFlow for GPU.

Body:
When running a tensorflow program leveraging GPU devices, I got the following message. What does the statement of Ignoring visible gpu
   device (device: 0, name: Quadro 5000, pci bus id: 0000:05:00.0) with Cuda
   compute capability 2.0. mean? What is to be ignored?

2017-12-04 16:06:17.784599: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with
properties:
name: Quadro 5000
major: 2 minor: 0 memoryClockRate (GHz) 1.026
pciBusID 0000:05:00.0
Total memory: 2.50GiB
Free memory: 2.22GiB
2017-12-04 16:06:17.784636: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0
2017-12-04 16:06:17.784645: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y
2017-12-04 16:06:17.784658: I
tensorflow/core/common_runtime/gpu/gpu_device.cc:950] Ignoring visible gpu
device (device: 0, name: Quadro 5000, pci bus id: 0000:05:00.0) with Cuda
compute capability 2.0. The minimum required Cuda capability is 3.0.


问:
php xpath screen scrape issue
Ok, this seems so simple but I can't get this coding working at all...

```<code>$html = new DOMDocument();
@$html->loadHtmlFile('http://www.groupon.com/deals/the-newfoundland-shop');
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query( "/html/body/div[@id='global_container']/div[@id='main']/div[@id='content']/div/div[1]/div[2]/div[@id='number_sold_container']/table[1]/tbody/tr/td" );
foreach ($nodelist as $n){
echo $n->nodeValue."\n";
}
$buys = "$n->nodeValue";
</code>```

Please help before I loose it...

Thanks

答:
First FAQ: the page looks proper XHTML, so you need to register the XHTML namespace URI http://www.w3.org/1999/xhtml with some prefix, and use that prefix in your XPath expression.

Second FAQ: you should note that original source has not tbody element. This is added by the browser.

ContentLicense: CC BY-SA 2.5

Title: php xpath screen scrape issue

Body:
Ok, this seems so simple but I can't get this coding working at all...

$html = new DOMDocument();
@$html->loadHtmlFile('http://www.groupon.com/deals/the-newfoundland-shop');
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query( "/html/body/div[@id='global_container']/div[@id='main']/div[@id='content']/div/div[1]/div[2]/div[@id='number_sold_container']/table[1]/tbody/tr/td" );
foreach ($nodelist as $n){
echo $n->nodeValue."\n";
}
$buys = "$n->nodeValue";

Please help before I loose it...

Thanks


问:
Correct regex for matching EXACTLY n instances of a pattern
Let's say I have the following:

```<code>1.) /some/text/here/with-dashes/010101/
2.) /some/text/here/too/
3.) /some/other/really-long/text/goes/here/019293847/
</code>```

I want to get the strings that contains EXACTLY 6 / so far these regex aren't working how I intended it to:

```<code>(/\w+[-]?\w+){6}
(/\w+[-]?\w+){6,6}
(/\w+[-]?\w+){,6}?
</code>```

These regex also matches strings with more than 6 / I want it to match strings with EXACTLY 6 /.

答:
Consider more_itertools.exactly_n a third-party library.

Code

```<code>iterable = "1.) /some/text/here/with-dashes/010101/"
pred = lambda x: x == "/"
n = 6

mit.exactly_n(iterable, n, pred)
# True
</code>```

Tests

```<code>f = mit.exactly_n

assert f("1.) /some/text/here/with-dashes/010101/", n, pred) == True
assert f("2.) /some/text/here/too/", n, pred) == False
assert f("3.) /some/other/really-long/text/goes/here/019293847/", n, pred) == False
</code>```

Body:
Let's say I have the following:

1.) /some/text/here/with-dashes/010101/
2.) /some/text/here/too/
3.) /some/other/really-long/text/goes/here/019293847/

I want to get the strings that contains EXACTLY 6 / so far these regex aren't working how I intended it to:

(/\w+[-]?\w+){6}
(/\w+[-]?\w+){6,6}
(/\w+[-]?\w+){,6}?

These regex also matches strings with more than 6 / I want it to match strings with EXACTLY 6 /.

Body:
Consider more_itertools.exactly_n a third-party library.

Code

iterable = "1.) /some/text/here/with-dashes/010101/"
pred = lambda x: x == "/"
n = 6

mit.exactly_n(iterable, n, pred)
# True

Tests

f = mit.exactly_n

assert f("1.) /some/text/here/with-dashes/010101/", n, pred) == True
assert f("2.) /some/text/here/too/", n, pred) == False
assert f("3.) /some/other/really-long/text/goes/here/019293847/", n, pred) == False


问:
Run a function before test get started
Is there a way to run a function before the tests get started?

For example:

```<code>object KkConsumerSpec extends Properties("Consumer")  {

  //Some preparation work here!!!!

  property("startsWith") = forAll { (a: String, b: String) =>
    (a+b).startsWith(a)
  }

}
</code>```

I want to run some functions before the test startsWith starts.

答: If I understand what you want to do, all you have to do is extend BeforeAndAfterAll and then override one of the beforeAll methods.

Title: Run a function before test get started

Body:
Is there a way to run a function before the tests get started?

For example:

object KkConsumerSpec extends Properties("Consumer")  {

  //Some preparation work here!!!!

  property("startsWith") = forAll { (a: String, b: String) =>
    (a+b).startsWith(a)
  }

}

I want to run some functions before the test startsWith starts.


问:
javascript regexp positive look behind to dynamicly replace/wrap text in URL
Using jQuery/Javascript, I want to match text within multiple containers and wrap a link around the text while using the matched text in the URL.

Input HTML:

```<code><div id="sampleText">
The dog jumped over the fence id:12345-6789 and ran into another fence id:98765-4321.
</div>

<div>
The dog continued to jump over fence id:12345-6789 and again ran into another fence id:98765-4321.
</div>
</code>```

Output HTML:

```<code><div>
The dog jumped over the fence id:<a href="123.45678.com.com?id=12345-6789">12345-6789</a> and ran into another fence id:<a href="123.45678.com?id=98765-4321">98765-4321</a>.
</div>

<div>
The dog continued to jump over fence id:<a href="123.45678.com.com?id=12345-6789">12345-6789</a> and again ran into another fence id:<a href="123.45678.com?id=98765-4321">98765-4321</a>.
</div>
</code>```

Here is what I have so far (not working)...

```<code>$("div:contains('fence id:')").html(function(_,html){
     var rx = new RegExp('fence id:[0-9A-Z-]+','gi');
     return html.replace(rx, '<a href="123.45678.com?id='+$1+'">'+$1+'</a>');
});
</code>```

答:
You're super close!

First, you need to make sure that your regex is actually capturing the id text by using () to create a capturing group:

```<code>var rx = new RegExp('fence id:([0-9A-Z-]+)','gi');
</code>```

Second, when referencing the capturing group using $1 you actually want to just include it right in the replacement string, rather than treating it as a variable:

```<code>return html.replace(rx, '<a href="123.45678.com?id=$1">$1</a>');
</code>```

$("div:contains('fence id:')").html(function(_,html){
     var rx = new RegExp('fence id:([0-9A-Z-]+)','gi');
     return html.replace(rx, '$1');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sampleText">
The dog jumped over the fence id:12345-6789 and ran into another fence id:98765-4321.
</div>

<div>
The dog continued to jump over fence id:12345-6789 and again ran into another fence id:98765-4321.
</div></code>```

Body:
Using jQuery/Javascript, I want to match text within multiple containers and wrap a link around the text while using the matched text in the URL.

Input HTML:

The dog jumped over the fence id:12345-6789 and ran into another fence id:98765-4321.

The dog continued to jump over fence id:12345-6789 and again ran into another fence id:98765-4321.

Output HTML:

The dog jumped over the fence id:12345-6789 and ran into another fence id:98765-4321.

The dog continued to jump over fence id:12345-6789 and again ran into another fence id:98765-4321.

Here is what I have so far (not working)...

$("div:contains('fence id:')").html(function(_,html){
     var rx = new RegExp('fence id:[0-9A-Z-]+','gi');
     return html.replace(rx, ''+$1+'');
});

Body:
You're super close!

First, you need to make sure that your regex is actually capturing the id text by using () to create a capturing group:

var rx = new RegExp('fence id:([0-9A-Z-]+)','gi');

Second, when referencing the capturing group using $1 you actually want to just include it right in the replacement string, rather than treating it as a variable:

return html.replace(rx, '<a href="123.45678.com?id=$1">$1</a>');

$("div:contains('fence id:')").html(function(_,html){
     var rx = new RegExp('fence id:([0-9A-Z-]+)','gi');
     return html.replace(rx, '<a href="123.45678.com?id=$1">$1</a>');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sampleText">
The dog jumped over the fence id:12345-6789 and ran into another fence id:98765-4321.
</div>

<div>
The dog continued to jump over fence id:12345-6789 and again ran into another fence id:98765-4321.
</div>


问:
VueJS 2.0: Deploying to sub-folder comes out blank?
I have been trying to deploy my Vue2 web app into a sub-folder in my domain, but it comes out blank. I've tried several different fixes such as changing the config/index.js to match the path in my live site, changed the index.html file generated in the dist folder to match the paths.

Console gives no errors.

What am I doing wrong?

答:
Assuming you're using webpack (set up through vue-cli), you need to set the subfolder in the config and pass it to the troute.

add ROUTER_BASE in the config/****.env.js file(s)

set the base of the router to ROUTER_BASE (https://router.vuejs.org/en/api/options.html#base)

module.exports = {
  NODE_ENV: '"production"',
  ROUTER_BASE: '/subfolder'
}

new VueRouter({
  base: process.env.ROUTER_BASE,
  // ...etc
})


问:
Call Swift class method from Objective-C
I am using Objective-C to consume a Swift Code that I am turning into a Framework/SDK eventually.
I can not invoke the class Methods specifically to Objective-C, and I am getting this error

No visible @interface for 'class' declares the selector 'method'

Swift File

```<code>public class Example {

    public class func testOne() -> NSString {
         return "testOne";
    }

    public func testTwo() -> NSString {
         return "testTwo";
    }

}
</code>```

Objective-C File

```<code>#import <ProjectModuleName-Swift.h>

@interface ...
@end

@implmentation ...
- (void) testing {
  Example *example = [[Example alloc] init];
  NSString *testOne = [example testOne]; // does not work ; No visible @interface for 'Example' declares the selector 'testOne'
  NSString *testTwo = [example testTwo]; // does work
}
@end
</code>```

Obviously, by declaring class func it should require a different way to invoke it through Objective-C, but I have not seen any docs on this topic.

An example or help would be much appreciated.

答:
Class methods are called on the class, not instances of the class:</p>

```<code>NSString *testOne = [Example testOne];
NSString *testTwo = [Example testTwo];
</code>```

Body:
I am using Objective-C to consume a Swift Code that I am turning into a Framework/SDK eventually.
I can not invoke the class Methods specifically to Objective-C, and I am getting this error

No visible @interface for 'class' declares the selector 'method'

Swift File

public class Example {

    public class func testOne() -> NSString {
         return "testOne";
    }

    public func testTwo() -> NSString {
         return "testTwo";
    }

}

Objective-C File

#import <ProjectModuleName-Swift.h>

@interface ...
@end

@implmentation ...
- (void) testing {
  Example *example = [[Example alloc] init];
  NSString *testOne = [example testOne]; // does not work ; No visible @interface for 'Example' declares the selector 'testOne'
  NSString *testTwo = [example testTwo]; // does work
}
@end

Obviously, by declaring class func it should require a different way to invoke it through Objective-C, but I have not seen any docs on this topic.

An example or help would be much appreciated.

Body:
Class methods are called on the class, not instances of the class:

NSString *testOne = [Example testOne];
NSString *testTwo = [Example testTwo];


问:
Cannot start session without errors in phpMyAdmin
I get the below error when pointing browser to phpMyAdmin

Cannot start session without errors, please check errors given in your PHP and/or webserver log file and configure your PHP installation properly.

I have checked everything and can't seem to figure out what the problem is.

In my php.ini file I have:

```<code>session.save_path = "/var/lib/php/session"
</code>```

Permissions:

```<code>drwxr-xr-x  2 root apache 4096 Feb 16 04:47 session
</code>```

Nothing seems to work. Even changing permission on session directory to 777.

答: Problem I found in Windows server 2016 was that the permissions were wrong on the temp directory used by PHP. I added IUSR.</p>

Body:
I get the below error when pointing browser to phpMyAdmin

Cannot start session without errors, please check errors given in your PHP and/or webserver log file and configure your PHP installation properly.

I have checked everything and can't seem to figure out what the problem is.

In my php.ini file I have:

session.save_path = "/var/lib/php/session"

Permissions:

drwxr-xr-x  2 root apache 4096 Feb 16 04:47 session

Nothing seems to work. Even changing permission on session directory to 777.


问:
Django Form Logic: Split and display prefilled values
Let's say I have a model that holds several different charfields.

models.py

```<code>class Items(models.Model):
    languages = models.Charfield(...)
    title = models.Charfield(...)
    audio = models.Charfield(...)
</code>```

The data is saved within each with a delimiter ("||").  I would like to create a form that splits the data then prefills the value with the saved data.

Theoretically:

```<code>{'languages': 'English||French||German'}
{'title': '1.1||Red Balloon||Banana'}
{'audio': 'yes||no||yes'}
</code>```

Would be split to:

```<code>{'languages': ['English', 'French', 'German']}
{'title': ['1.1', 'Red Balloon', 'Banana']}
{'audio': ['yes', 'no', 'yes']}
</code>```

Then each value would auto-populate the value field. Eventually displaying as:

```<code><tr>
  <td><input type="text" name="languages[]" value="English"></td>
  <td><input type="text" name="title[]" value="1.1"></td>
  <td><input type="text" name="audio[]" value="yes"></td>
</tr>
<tr>
  <td><input type="text" name="languages[]" value="French"></td>
  <td><input type="text" name="title[]" value="Red Balloon"></td>
  <td><input type="text" name="audio[]" value="no"></td>
</tr>
...
</code>```

As each row would have a different amount of 'languages', for example, what is the preferred way to create this type of form.  I am using Django 1.11. First question posted, so if I have missed something within this post, would you kindly let me know?  I also have searched for information related to this, however I have yet to find a solution. Thanks!

--Edited to reflect that charFields hold the user input.  In this example, the inputs 'languages' and 'title' are not consistent enough to use them as multiple-choice fields.

答:
Take a look at Django Formsets.

In your case you'd want to first define some sort of ItemForm:

```<code>from django import forms
class ItemForm(forms.Form):
    language = forms.CharField()
    setting = forms.CharField()
    audio = forms.CharField()
</code>```

In your views.py, you can then define a formset with the initial form data:

```<code>from django.forms import formset_factory
from myapp.forms import ItemForm

item = Items.objects.all()[0] # replace this with your actual query
languages = item.languages.split('||')
settings = item.settings.split('||')
audios = item.audio.split('||')
ItemFormSet = formset_factory(ItemForm, extra=len(languages))
formset = ItemFormSet(initial=[
    {'language': language,
     'setting': setting,
     'audio':audio,
    } for language, setting, audio in zip(languages, settings, audios)])
</code>```

Body:
Let's say I have a model that holds several different charfields.

models.py

class Items(models.Model):
    languages = models.Charfield(...)
    title = models.Charfield(...)
    audio = models.Charfield(...)

The data is saved within each with a delimiter ("||").  I would like to create a form that splits the data then prefills the value with the saved data.

Theoretically:

{'languages': 'English||French||German'}
{'title': '1.1||Red Balloon||Banana'}
{'audio': 'yes||no||yes'}

Would be split to:

{'languages': ['English', 'French', 'German']}
{'title': ['1.1', 'Red Balloon', 'Banana']}
{'audio': ['yes', 'no', 'yes']}

Then each value would auto-populate the value field. Eventually displaying as:

  <input type="text" name="languages[]" value="English">
  <input type="text" name="title[]" value="1.1">
  <input type="text" name="audio[]" value="yes">

  <input type="text" name="languages[]" value="French">
  <input type="text" name="title[]" value="Red Balloon">
  <input type="text" name="audio[]" value="no">

...

As each row would have a different amount of 'languages', for example, what is the preferred way to create this type of form.  I am using Django 1.11. First question posted, so if I have missed something within this post, would you kindly let me know?  I also have searched for information related to this, however I have yet to find a solution. Thanks!

--Edited to reflect that charFields hold the user input.  In this example, the inputs 'languages' and 'title' are not consistent enough to use them as multiple-choice fields.

Body:
Take a look at Django Formsets.

In your case you'd want to first define some sort of ItemForm:

from django import forms
class ItemForm(forms.Form):
    language = forms.CharField()
    setting = forms.CharField()
    audio = forms.CharField()

In your views.py, you can then define a formset with the initial form data:

from django.forms import formset_factory
from myapp.forms import ItemForm

item = Items.objects.all()[0] # replace this with your actual query
languages = item.languages.split('||')
settings = item.settings.split('||')
audios = item.audio.split('||')
ItemFormSet = formset_factory(ItemForm, extra=len(languages))
formset = ItemFormSet(initial=[
    {'language': language,
     'setting': setting,
     'audio':audio,
    } for language, setting, audio in zip(languages, settings, audios)])


问:
STM32 flashing disabled after flashing a code without R/W protection
I have some experience of StdPeriph libraries usage for programming stm32. But now I tried STM32Cube HAL with STM32CubeMX code generator. I generated a project with this options:

Middleware: FreeRTOS and FatFS via SDIO

Compiler is GCC

stm32f103ret6 MCU

I imported generated code to Eclipse environment. I made a binary and flashed it with "st-flash write ..." as usual. My test program successfuly wrote to USART1 "Hello" in cycle - this is no problem. But then, when I tried to flash another code, it failed with "unknown chip id". If I manually connect NRST to GND, st-flash gives:

```<code>...Flash: 0 bytes (0 KiB) in pages of 2048 bytes
</code>```

Full output:

```<code>2015-06-14T16:07:29 INFO src/stlink-common.c: Loading device parameters....
2015-06-14T16:07:29 INFO src/stlink-common.c: Device connected is: F1 High-density device, id 0x10036414
2015-06-14T16:07:29 INFO src/stlink-common.c: SRAM size: 0x10000 bytes (64 KiB), Flash: 0 bytes (0 KiB) in pages of 2048 bytes
</code>```

I tried to use ST-Link Utility from Windows, but it cannot connect to this MCU to change option bytes (connection to another devices with stm32 works well).
I tried to flash through USART1, but it failed.

Source code I flashed, of course, does not contain any read/write protection enabling. I tried 2 another MCU, but this error was reproduced.

How can I unbrick by MCUs and flash anything?

答: It's (BURIED) under Pinout | SYS | Debug of STM32CubeMX...set to Serial Wire or whatever.</p>

Body:
I have some experience of StdPeriph libraries usage for programming stm32. But now I tried STM32Cube HAL with STM32CubeMX code generator. I generated a project with this options:

Middleware: FreeRTOS and FatFS via SDIO

Compiler is GCC

stm32f103ret6 MCU

I imported generated code to Eclipse environment. I made a binary and flashed it with "st-flash write ..." as usual. My test program successfuly wrote to USART1 "Hello" in cycle - this is no problem. But then, when I tried to flash another code, it failed with "unknown chip id". If I manually connect NRST to GND, st-flash gives:

...Flash: 0 bytes (0 KiB) in pages of 2048 bytes

Full output:

2015-06-14T16:07:29 INFO src/stlink-common.c: Loading device parameters....
2015-06-14T16:07:29 INFO src/stlink-common.c: Device connected is: F1 High-density device, id 0x10036414
2015-06-14T16:07:29 INFO src/stlink-common.c: SRAM size: 0x10000 bytes (64 KiB), Flash: 0 bytes (0 KiB) in pages of 2048 bytes

I tried to use ST-Link Utility from Windows, but it cannot connect to this MCU to change option bytes (connection to another devices with stm32 works well).
I tried to flash through USART1, but it failed.

Source code I flashed, of course, does not contain any read/write protection enabling. I tried 2 another MCU, but this error was reproduced.

How can I unbrick by MCUs and flash anything?


问:
How do you round UP a number?
How does one round a number UP in Python?

I tried round(number) but it rounds the number down. Here is an example:

```<code>round(2.3) = 2.0
</code>```

and not 3, as I would like.

Then I tried int(number + .5) but it round the number down again! Example:

```<code>int(2.3 + .5) = 2
</code>```

Title: How do you round UP a number?

Body:
How does one round a number UP in Python?

I tried round(number) but it rounds the number down. Here is an example:

round(2.3) = 2.0

and not 3, as I would like.

Then I tried int(number + .5) but it round the number down again! Example:

int(2.3 + .5) = 2

Body:
Try this:

a = 211.0
print(int(a) + ((int(a) - a) != 0))


问:
Grails form g:textField parameters to Controller
I'm quite new to Grails and I've modified some previously existing button functionality so that it now should send 2 parameters to the controller. By the help of this tutorial I've written:

gsp:

```<code><div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><button type="button" class="close" data-dismiss="modal">×</button><h4 class="modal-title">Some Title</h4></div>
            <div class="modal-body">
                <g:form>
                    <div class="input-group">
                        <span class="input-group-addon">Parameter 1</span>
                        <g:textField name="parameter1" size="24" class="form-control" />
                    </div>
                    <div class="input-group">
                        <span class="input-group-addon">Parameter 2</span>
                        <g:textField name="parameter2" size="24" class="form-control" />
                    </div>
                    <g:actionSubmit action="myAction" value="Go" class="btn btn-success"
                                    data-toggle="tooltip" data-placement="top"
                                    title="${grailsApplication.config.myTitle}" />
                </g:form>
            </div>
        </div>
    </div>
</div>
</code>```

MyController:

```<code>// Though it is not mentioned in the tutorial, I've added 2 class properties.
// Otherwise I'd get a groovy.lang.MissingPropertyException
def parameter1
def parameter2

def myAction = {
    doSomething(parameter1, parameter2)
}

// previously :
// def myAction = {
//     doSomething()
// }
</code>```

The two parameters are 'null' when the method is invoked. What can I do to make the parameters being handled to the controller method?

File names, imports and things alike should not be the problem here as the call of the function does well without parameters. The modal is new to the code as it is used to get the values of parameter1 and parameter2. The modal itself works well, as long as the parameters are not in the signature of the controller's method.

I've tried "grails clean" according to this answer. Grails version 2.5.4

答:
I'm not sure of the exact version but from grails 2.x instead of closures you must use methods to define actions of a controller. This code should work

```<code>def myAction() {
    doSomething(params.parameter1, params.parameter2)
}
</code>```

Or it could be like this, assuming both parameters are strings

```<code>def myAction(final String parameter1, final String parameter2) {
    doSomething(parameter1, params)
}
</code>```

In the example that you share the form does not define a target action so you should go to the current action using the post method

Body:
I'm quite new to Grails and I've modified some previously existing button functionality so that it now should send 2 parameters to the controller. By the help of this tutorial I've written:

gsp:

<button type="button" class="close" data-dismiss="modal">×</button>
Some Title

                <g:form>

                        Parameter 1
                        <g:textField name="parameter1" size="24" class="form-control" />

                        Parameter 2
                        <g:textField name="parameter2" size="24" class="form-control" />

                    <g:actionSubmit action="myAction" value="Go" class="btn btn-success"
                                    data-toggle="tooltip" data-placement="top"
                                    title="${grailsApplication.config.myTitle}" />
                </g:form>

MyController:

// Though it is not mentioned in the tutorial, I've added 2 class properties.
// Otherwise I'd get a groovy.lang.MissingPropertyException
def parameter1
def parameter2

def myAction = {
    doSomething(parameter1, parameter2)
}

// previously :
// def myAction = {
//     doSomething()
// }

The two parameters are 'null' when the method is invoked. What can I do to make the parameters being handled to the controller method?

File names, imports and things alike should not be the problem here as the call of the function does well without parameters. The modal is new to the code as it is used to get the values of parameter1 and parameter2. The modal itself works well, as long as the parameters are not in the signature of the controller's method.

I've tried "grails clean" according to this answer. Grails version 2.5.4

Body:
I'm not sure of the exact version but from grails 2.x instead of closures you must use methods to define actions of a controller. This code should work

def myAction() {
    doSomething(params.parameter1, params.parameter2)
}

Or it could be like this, assuming both parameters are strings

def myAction(final String parameter1, final String parameter2) {
    doSomething(parameter1, params)
}

In the example that you share the form does not define a target action so you should go to the current action using the post method


问:
Pylint can't find SQLAlchemy query member
I have a Flask (v0.10.1) application using Flask-SQLAlchemy (v2.0) and I'm trying to configure Pylint to check it. Running with Python 3.4.2.

First error was:

```<code> Instance of 'SQLAlchemy' has no 'Table' member (no-member)
</code>```

And I fixed this one ignoring the check for member attributes on SQLAlchemy:

```<code>ignored-classes=SQLAlchemy
</code>```

But I'm having a problem with the query member on entities:

```<code>Class 'UserToken' has no 'query' member (no-member)
</code>```

Is there any way to fix this issue without having to ignore no-member errors on every query call?

Flask bootstrap:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
app = Flask(__name__)
db.init_app(app)
app.run()
</code>```

UserToken entity:

```<code>from app import db

class UserToken(db.Model):
    user_token_id = db.Column(db.Integer, primary_key=True, index=True)
    token_auth = db.Column(db.String(64), unique=True, nullable=False, index=True)
</code>```

The controller:

```<code>from entities import UserToken

token = UserToken.query.filter(
    UserToken.token_auth == token_hash,
).first()
</code>```

答:
Here's a version of joeforker's answer that dynamically adds all public methods from the Session object back into a scoped_session's locals at lint-time, instead of hardcoding a few well-known method names.

Define {path}/{to}/pylintplugins.py:

```<code>import sys

from astroid import MANAGER, scoped_nodes
from astroid.builder import AstroidBuilder
from sqlalchemy.orm import Session

def register(_linter):
    pass

def transform(cls):
    if cls.name == 'scoped_session':
        builder = AstroidBuilder(MANAGER)
        module_node = builder.module_build(sys.modules[Session.__module__])
        session_cls_node = [
            c for c in module_node.get_children()
            if getattr(c, "type", None) == "class" and c.name == Session.__name__
        ][0]

        for prop in Session.public_methods:
            cls.locals[prop] = [
                c for c in session_cls_node.get_children()
                if getattr(c, "type", None) == "method" and c.name == prop
            ]

MANAGER.register_transform(scoped_nodes.Class, transform)
</code>```

And in your .pylintrc file:

```<code>load-plugins={path}.{to}.pylintplugins
</code>```

Body:
I have a Flask (v0.10.1) application using Flask-SQLAlchemy (v2.0) and I'm trying to configure Pylint to check it. Running with Python 3.4.2.

First error was:

 Instance of 'SQLAlchemy' has no 'Table' member (no-member)

And I fixed this one ignoring the check for member attributes on SQLAlchemy:

ignored-classes=SQLAlchemy

But I'm having a problem with the query member on entities:

Class 'UserToken' has no 'query' member (no-member)

Is there any way to fix this issue without having to ignore no-member errors on every query call?

Flask bootstrap:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
app = Flask(__name__)
db.init_app(app)
app.run()

UserToken entity:

from app import db

class UserToken(db.Model):
    user_token_id = db.Column(db.Integer, primary_key=True, index=True)
    token_auth = db.Column(db.String(64), unique=True, nullable=False, index=True)

The controller:

from entities import UserToken

token = UserToken.query.filter(
    UserToken.token_auth == token_hash,
).first()

Body:
Here's a version of joeforker's answer that dynamically adds all public methods from the Session object back into a scoped_session's locals at lint-time, instead of hardcoding a few well-known method names.

Define {path}/{to}/pylintplugins.py:

import sys

from astroid import MANAGER, scoped_nodes
from astroid.builder import AstroidBuilder
from sqlalchemy.orm import Session

def register(_linter):
    pass

def transform(cls):
    if cls.name == 'scoped_session':
        builder = AstroidBuilder(MANAGER)
        module_node = builder.module_build(sys.modules[Session.__module__])
        session_cls_node = [
            c for c in module_node.get_children()
            if getattr(c, "type", None) == "class" and c.name == Session.__name__
        ][0]

        for prop in Session.public_methods:
            cls.locals[prop] = [
                c for c in session_cls_node.get_children()
                if getattr(c, "type", None) == "method" and c.name == prop
            ]

MANAGER.register_transform(scoped_nodes.Class, transform)

And in your .pylintrc file:

load-plugins={path}.{to}.pylintplugins


问:
HttpWebRequest times out on second call
Why does the following code Timeout the second (and subsequent) time it is run?

The code hangs at:

```<code>using (Stream objStream = request.GetResponse().GetResponseStream())
</code>```

and then causes a WebException saying that the request has timed out.

I have tried this with a WebRequest and HttpWebRequest

Edit: It seems the code is falling over in request.GetResponse()

Edit: This post suggests it may be a GC issue --> http://www.vbforums.com/showthread.php?t=610043 - as per this post the issue is mitigated if Fiddler is open in the background.

The server is there and available for requests.

```<code>    private string GetQLMResponse(string URL)
    {
        HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
        request.Credentials = new NetworkCredential(Settings.Default.LicenseUser, Settings.Default.LicensePassword);
        request.KeepAlive = false;
        request.Timeout = 5000;
        request.Proxy = null;

        // Read stream
        string responseString = String.Empty;
        try
        {
            using (var response = request.GetResponse())
            {
                using (Stream objStream = response.GetResponseStream())
                {
                    using (StreamReader objReader = new StreamReader(objStream))
                    {
                        responseString = objReader.ReadToEnd();
                        objReader.Close();
                    }
                    objStream.Flush();
                    objStream.Close();
                }
                response.Close();
            }
        }
        catch (WebException ex)
        {
            throw new LicenseServerUnavailableException();
        }
        finally
        {
            request.Abort();
            request = null;
            GC.Collect();
        }
        return responseString;
    }
</code>```

Thrown WebException is:

{"The operation has timed out"}
      [System.Net.WebException]: {"The operation has timed out"}
      Data: {System.Collections.ListDictionaryInternal}
      HelpLink: null
      InnerException: null
      Message: "The operation has timed out"
      Source: "System"
      StackTrace: "   at System.Net.HttpWebRequest.GetResponse()\r\n   at IQX.Licensing.License.GetQLMResponse(String URL) in C:\Users\jd\SVN\jd\Products\Development\JAD.Licensing\JAD.Licensing\License.cs:line 373"
      TargetSite: {System.Net.WebResponse GetResponse()}

Update: OK So the following code now works. The servicePoint was setting the timeout to be near 4 minutes. Changing ServicePoint.ConnectionLeaseTimeout on the request object means that the request is now destroyed after 5000ms. Thanks to all for your help and also to these 2 pages:

http://blogs.msdn.com/b/adarshk/archive/2005/01/02/345411.aspx

http://msdn.microsoft.com/en-us/library/6hszazfz(v=VS.80).aspx

```<code>private string GetQLMResponse(string URL)
{
    HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
    request.Credentials = new NetworkCredential(Settings.Default.LicenseUser, Settings.Default.LicensePassword);
    request.KeepAlive = false;
    request.Timeout = 5000;
    request.Proxy = null;

    request.ServicePoint.ConnectionLeaseTimeout = 5000;
    request.ServicePoint.MaxIdleTime = 5000;

    // Read stream
    string responseString = String.Empty;
    try
    {
        using (WebResponse response = request.GetResponse())
        {
            using (Stream objStream = response.GetResponseStream())
            {
                using (StreamReader objReader = new StreamReader(objStream))
                {
                    responseString = objReader.ReadToEnd();
                    objReader.Close();
                }
                objStream.Flush();
                objStream.Close();
            }
            response.Close();
        }
    }
    catch (WebException ex)
    {
        throw new LicenseServerUnavailableException();
    }
    finally
    {
        request.Abort();
    }
    return responseString;
}
</code>```

答:
By any chance were you using a test app with the default name of WindowsFormsAppN? I had the same problem that I spent a week debugging because it worked in my production code but not in a simple test solution I was building. In the end, I determined this behavior was unique to using the default solution name instead of a properly named solution.

Edit: I discovered my issue was related to using BitDefender as my AV software. The WindowsFormsAppN programs were all blocked.

Title: HttpWebRequest times out on second call

Body:
Why does the following code Timeout the second (and subsequent) time it is run?

The code hangs at:

using (Stream objStream = request.GetResponse().GetResponseStream())

and then causes a WebException saying that the request has timed out.

I have tried this with a WebRequest and HttpWebRequest

Edit: It seems the code is falling over in request.GetResponse()

Edit: This post suggests it may be a GC issue --> http://www.vbforums.com/showthread.php?t=610043 - as per this post the issue is mitigated if Fiddler is open in the background.

The server is there and available for requests.

    private string GetQLMResponse(string URL)
    {
        HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
        request.Credentials = new NetworkCredential(Settings.Default.LicenseUser, Settings.Default.LicensePassword);
        request.KeepAlive = false;
        request.Timeout = 5000;
        request.Proxy = null;

        // Read stream
        string responseString = String.Empty;
        try
        {
            using (var response = request.GetResponse())
            {
                using (Stream objStream = response.GetResponseStream())
                {
                    using (StreamReader objReader = new StreamReader(objStream))
                    {
                        responseString = objReader.ReadToEnd();
                        objReader.Close();
                    }
                    objStream.Flush();
                    objStream.Close();
                }
                response.Close();
            }
        }
        catch (WebException ex)
        {
            throw new LicenseServerUnavailableException();
        }
        finally
        {
            request.Abort();
            request = null;
            GC.Collect();
        }
        return responseString;
    }

Thrown WebException is:

{"The operation has timed out"}
      [System.Net.WebException]: {"The operation has timed out"}
      Data: {System.Collections.ListDictionaryInternal}
      HelpLink: null
      InnerException: null
      Message: "The operation has timed out"
      Source: "System"
      StackTrace: "   at System.Net.HttpWebRequest.GetResponse()\r\n   at IQX.Licensing.License.GetQLMResponse(String URL) in C:\Users\jd\SVN\jd\Products\Development\JAD.Licensing\JAD.Licensing\License.cs:line 373"
      TargetSite: {System.Net.WebResponse GetResponse()}

Update: OK So the following code now works. The servicePoint was setting the timeout to be near 4 minutes. Changing ServicePoint.ConnectionLeaseTimeout on the request object means that the request is now destroyed after 5000ms. Thanks to all for your help and also to these 2 pages:

http://blogs.msdn.com/b/adarshk/archive/2005/01/02/345411.aspx

http://msdn.microsoft.com/en-us/library/6hszazfz(v=VS.80).aspx

private string GetQLMResponse(string URL)
{
    HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
    request.Credentials = new NetworkCredential(Settings.Default.LicenseUser, Settings.Default.LicensePassword);
    request.KeepAlive = false;
    request.Timeout = 5000;
    request.Proxy = null;

    request.ServicePoint.ConnectionLeaseTimeout = 5000;
    request.ServicePoint.MaxIdleTime = 5000;

    // Read stream
    string responseString = String.Empty;
    try
    {
        using (WebResponse response = request.GetResponse())
        {
            using (Stream objStream = response.GetResponseStream())
            {
                using (StreamReader objReader = new StreamReader(objStream))
                {
                    responseString = objReader.ReadToEnd();
                    objReader.Close();
                }
                objStream.Flush();
                objStream.Close();
            }
            response.Close();
        }
    }
    catch (WebException ex)
    {
        throw new LicenseServerUnavailableException();
    }
    finally
    {
        request.Abort();
    }
    return responseString;
}


问:
Is is possible to apply this data-frame transform?
Turn this data-frame :

```<code>  Name  │  car
  ──────┼────────
  John  │  Volvo
  John  │  Fiat
  Paul  │  Dacia
</code>```

Into this? :

```<code>  Name  │  car_1  │   car_2
  ──────┼─────────┼─────────
  John  │  Volvo  │   Fiat
  Paul  │  Dacia  │   NaN
</code>```

for an arbitrary number of duplicates (arbitrary number of cars a person ) IDs in the first table.

答:
By using unstack

```<code>df1=df1.assign(numer=df1.groupby('Name').cumcount()).set_index(['Name','numer']).unstack()
df1
Out[256]:
         car
numer      0     1
Name
John   Volvo  Fiat
Paul   Dacia  None

df1.columns=df1.columns.map('{0[0]}_{0[1]}'.format)
df1
Out[261]:
       car_0  car_1
Name
John  Volvo  Fiat
Paul  Dacia  None
</code>```

Body:
Turn this data-frame :

  Name  │  car
  ──────┼────────
  John  │  Volvo
  John  │  Fiat
  Paul  │  Dacia

Into this? :

  Name  │  car_1  │   car_2
  ──────┼─────────┼─────────
  John  │  Volvo  │   Fiat
  Paul  │  Dacia  │   NaN

for an arbitrary number of duplicates (arbitrary number of cars a person ) IDs in the first table.

Body:
By using unstack

df1=df1.assign(numer=df1.groupby('Name').cumcount()).set_index(['Name','numer']).unstack()
df1
Out[256]:
         car
numer      0     1
Name
John   Volvo  Fiat
Paul   Dacia  None

df1.columns=df1.columns.map('{0[0]}_{0[1]}'.format)
df1
Out[261]:
       car_0  car_1
Name
John  Volvo  Fiat
Paul  Dacia  None


问:
Cannot read property addEvenListener of null
I am attempting to create a basic single page application (without any frameworks), which will give users tutorials on certain subjects.

I am getting an error with the javascript for the page as follows:

Uncaught TypeError: Cannot read property 'addEventListener' of null

Here is the javascript I use to load in the json data:

```<code>var btn = document.getElementById("btn");

btn.addEventListener("click", function(){
  var TutRequest = new XMLHttpRequest();
  TutRequest.open('GET', 'https://api.myjson.com/bins/iyvun');
  TutRequest.onLoad = function(){
    var TutData = JSON.parse(TutRequest.responseText);
    console.log(TutData[2]);
   };
 TutRequest.send();
})
</code>```

This is my HTML code :

```<code><html>
<head>
    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">
    <script src="javaScript.js"></script>
</head>

<body>

    <header>
    <h1>SPA tutorials</h1>

        <nav role="navigation">
            <ul>
                <li><a href="#the-default-view"><button id="btn">the default view</button></a></li>
                <li><a href="#some-view"><button id="btn2">some view</button></a></li>
                <li><a href="#another-view"><button id="btn3">another view</button></a></li>
            </ul>

        </nav>
    </header>

</body>
</code>```

The output of the code should be the json data from the URL provided in the JS code but I seem to only get this error with anything I'm trying.

Any help with this is appreciated.

答:
That happen because the DOM isn't fully loaded when the script run, put you JS include at the end of the body tag when the elements that you want to attach the event to are ready and loaded like :</p>

```<code><html>
<head>
    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>

    <header>
    <h1>SPA tutorials</h1>

        <nav role="navigation">
            <ul>
                <li><a href="#the-default-view"><button id="btn">the default view</button></a></li>
                <li><a href="#some-view"><button id="btn2">some view</button></a></li>
                <li><a href="#another-view"><button id="btn3">another view</button></a></li>
            </ul>

        </nav>
    </header>

    <script src="javaScript.js"></script>
</body>
</html>
</code>```

Body:
I am attempting to create a basic single page application (without any frameworks), which will give users tutorials on certain subjects.

I am getting an error with the javascript for the page as follows:

Uncaught TypeError: Cannot read property 'addEventListener' of null

Here is the javascript I use to load in the json data:

var btn = document.getElementById("btn");

btn.addEventListener("click", function(){
  var TutRequest = new XMLHttpRequest();
  TutRequest.open('GET', 'https://api.myjson.com/bins/iyvun');
  TutRequest.onLoad = function(){
    var TutData = JSON.parse(TutRequest.responseText);
    console.log(TutData[2]);
   };
 TutRequest.send();
})

This is my HTML code :

    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">

SPA tutorials

<button id="btn">the default view</button>

<button id="btn2">some view</button>

<button id="btn3">another view</button>

The output of the code should be the json data from the URL provided in the JS code but I seem to only get this error with anything I'm trying.

Any help with this is appreciated.

Body:
That happen because the DOM isn't fully loaded when the script run, put you JS include at the end of the body tag when the elements that you want to attach the event to are ready and loaded like :

<html>
<head>
    <meta name="viewport" content="width=devide-width, initial-scale=1"/>
    <title>SPA Tutorial page</title>
    <link rel="stylesheet" href="css/styles.css">
</head>

<body>

    <header>
    <h1>SPA tutorials</h1>

        <nav role="navigation">
            <ul>
                <li><a href="#the-default-view"><button id="btn">the default view</button></a></li>
                <li><a href="#some-view"><button id="btn2">some view</button></a></li>
                <li><a href="#another-view"><button id="btn3">another view</button></a></li>
            </ul>

        </nav>
    </header>

    <script src="javaScript.js"></script>
</body>
</html>


问:
Cant load this JSON into my table
I 've got a simple thing:

There's a JSON with books objects,every book has a title,author and year.
I would like to choose one option from the list and display chosen property in a table.I've used an example from W3 but right now i'm stuck and nothing works as it should...

Link's here

```<code>function change_myselect(sel) {
    var obj, dbParam, xmlhttp, myObj, x, txt = "";
    obj = { "table":sel, "limit":20 };
    dbParam = JSON.stringify(obj);
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            txt += "<table border='1'>"
            for (x in myObj) {
                txt += "<tr><td>" + myObj[x].name + "</td></tr>";
            }
            txt += "</table>"
            document.getElementById("demo").innerHTML = txt;
        }
    };
    xmlhttp.open("GET", "generated.json", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("x=" + dbParam);
}
</code>```

答:
The problem is quite easy to spot with a debugger line

```<code>console.log(myObj)
</code>```

It is an object and you are trying to loop over it. You want to be looping over the key in the object that holds the array.

```<code>console.log(myObj.books);
</code>```

Title: Cant load this JSON into my table

Body:
I 've got a simple thing:

There's a JSON with books objects,every book has a title,author and year.
I would like to choose one option from the list and display chosen property in a table.I've used an example from W3 but right now i'm stuck and nothing works as it should...

Link's here

function change_myselect(sel) {
    var obj, dbParam, xmlhttp, myObj, x, txt = "";
    obj = { "table":sel, "limit":20 };
    dbParam = JSON.stringify(obj);
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            txt += "
"
            for (x in myObj) {
                txt += "
" + myObj[x].name + "
";
            }
            txt += "
"
            document.getElementById("demo").innerHTML = txt;
        }
    };
    xmlhttp.open("GET", "generated.json", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("x=" + dbParam);
}

Body:
The problem is quite easy to spot with a debugger line

console.log(myObj)

It is an object and you are trying to loop over it. You want to be looping over the key in the object that holds the array.

console.log(myObj.books);


问:
BottomNavigationView with FloatingActionButton inside CoordinatorLayout dont match position
I want to hide my bottom bar on scroll but a FAB should stay on the screen.

If I put the FAB on top of BottomNavigationView using anchors but it appears behind it.

If I put layout_insetEdge="bottom" to the BottomNavigationView then it works but make my tests fail (https://issuetracker.google.com/issues/70162122) so I cannot use that at the moment.

Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/mainLayout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true"
  tools:context=".screens.main.MainActivity">

  <FrameLayout
    android:id="@+id/mainContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/scrolling_view_behaviour" />

  <android.support.design.widget.FloatingActionButton
    android:id="@+id/mainNewQuestionButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/spacing_8dp"
    app:layout_anchor="@+id/mainBottomNavigationView"
    app:layout_anchorGravity="top|right|end"
    app:srcCompat="@drawable/create_question"
    tools:visibility="visible" />

  <android.support.design.widget.BottomNavigationView
    android:id="@+id/mainBottomNavigationView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:itemBackground="@color/my_gray"
    app:itemIconTint="@drawable/selector_bottombar_item"
    app:itemTextColor="@drawable/selector_bottombar_item"
    app:layout_anchor="@id/mainContainer"
    app:layout_anchorGravity="bottom"
    app:layout_behavior="@string/hide_bottom_navigation_view_behaviour"
    app:menu="@menu/bottom_navigation_main" />

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
You seem to be having a Z-Ordering issue here.
You could try the fab.bringToFront() followed by fab.invalidate() for api's below 21, and ViewCompat.setZ(fab, someFloat) for api's above 21.

I used these methods to bring a custom FloatingActionMenu, consisting of a series of FAB's I wrote for a project, to the front so they would overlap everything on the screen.

Body:
I want to hide my bottom bar on scroll but a FAB should stay on the screen.

If I put the FAB on top of BottomNavigationView using anchors but it appears behind it.

If I put layout_insetEdge="bottom" to the BottomNavigationView then it works but make my tests fail (https://issuetracker.google.com/issues/70162122) so I cannot use that at the moment.

Layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/mainLayout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true"
  tools:context=".screens.main.MainActivity">

  <FrameLayout
    android:id="@+id/mainContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/scrolling_view_behaviour" />

  <android.support.design.widget.FloatingActionButton
    android:id="@+id/mainNewQuestionButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/spacing_8dp"
    app:layout_anchor="@+id/mainBottomNavigationView"
    app:layout_anchorGravity="top|right|end"
    app:srcCompat="@drawable/create_question"
    tools:visibility="visible" />

  <android.support.design.widget.BottomNavigationView
    android:id="@+id/mainBottomNavigationView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:itemBackground="@color/my_gray"
    app:itemIconTint="@drawable/selector_bottombar_item"
    app:itemTextColor="@drawable/selector_bottombar_item"
    app:layout_anchor="@id/mainContainer"
    app:layout_anchorGravity="bottom"
    app:layout_behavior="@string/hide_bottom_navigation_view_behaviour"
    app:menu="@menu/bottom_navigation_main" />

</android.support.design.widget.CoordinatorLayout>