问:
Server Tomcat v8.5 Server at localhost failed to start when I try to debug Eclipse JEE web project on local tomcat 8.5
I have found other stackoverflow questions similar to this one. The answers seem to be particular to those people's errors, so I gave up on them.

I did not have this error when I left off on this project as I recall. I don't recall changing anything before I came back to this project and got this error.

I want to debug my web app on a local tomcat 8.5 server. In Eclipse IDE for Enterprise Java Developers Version 2019-03(4.11.0), I right-click on my web project and select Debug As->Debug on Server. A dialog box appears and I choose the option to Manually define a new server. I select Tomcat v8.5 Server. I click the Finish button. Some red text in the debug window appear. Then a dialog box appears saying:

'Starting Tomcat v8.5 Server at localhost' has encountered a problem.

Server Tomcat v8.5 Server at localhost failed to start.

I have been able to start tomcat with startup.sh successfully, and have been able to shut down tomcat with shutdown.sh successfully, so I know tomcat works by itself.

I am able to run this web project on AWS Beanstalk.

Here is what it says in the debug window:

```<code>Jan 31, 2020 9:54:37 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'antiJARLocking' to 'true' did not find a matching property.
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.5.41
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 4 2019 09:17:16 UTC
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.5.41.0
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.14.6
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_211-b12
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/shinehah/eclipse-workspaces/eclipse-java-ee-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/shinehah/tomcat/apache-tomcat-8.5.41
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:56586
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -javaagent:/Users/shinehah/eclipse/jee-2019-03-3/Eclipse.app/Contents/Eclipse/configuration/org.eclipse.osgi/402/0/.cp/lib/javaagent-shaded.jar
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/shinehah/eclipse-workspaces/eclipse-java-ee-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/shinehah/tomcat/apache-tomcat-8.5.41
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/shinehah/eclipse-workspaces/eclipse-java-ee-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/shinehah/tomcat/apache-tomcat-8.5.41/endorsed
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jan 31, 2020 9:54:37 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/shinehah/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
Jan 31, 2020 9:54:38 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jan 31, 2020 9:54:38 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jan 31, 2020 9:54:38 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jan 31, 2020 9:54:38 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jan 31, 2020 9:54:38 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1816 ms
Jan 31, 2020 9:54:38 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Jan 31, 2020 9:54:38 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.5.41
Jan 31, 2020 9:54:39 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jan 31, 2020 9:54:39 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:882)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Realm[MemoryRealm]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5113)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Memory database file [/usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml] cannot be read
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:276)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 8 more
Caused by: java.io.FileNotFoundException: /usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at org.apache.tomcat.util.file.ConfigFileLoader.getInputStream(ConfigFileLoader.java:89)
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:258)
    ... 9 more

Jan 31, 2020 9:54:39 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:688)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:882)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 8 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Realm[MemoryRealm]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5113)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Memory database file [/usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml] cannot be read
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:276)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 8 more
Caused by: java.io.FileNotFoundException: /usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at org.apache.tomcat.util.file.ConfigFileLoader.getInputStream(ConfigFileLoader.java:89)
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:258)
    ... 9 more

Jan 31, 2020 9:54:39 AM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:688)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 13 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:882)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 8 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Realm[MemoryRealm]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5113)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Memory database file [/usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml] cannot be read
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:276)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 8 more
Caused by: java.io.FileNotFoundException: /usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at org.apache.tomcat.util.file.ConfigFileLoader.getInputStream(ConfigFileLoader.java:89)
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:258)
    ... 9 more

Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-nio-8080"]
Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-nio-8009"]
Jan 31, 2020 9:54:39 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service [Catalina]
Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-nio-8080"]
Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-nio-8009"]
</code>```

In the Problems pane, I see the following 4 errors:

```<code>Cannot change version of project facet Dynamic Web Module to 3.1.
JavaServer Faces 2.2 can not be installed : One or more constraints have not been satisfied.
JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer.
One or more constraints have not been satisfied.
</code>```

答:
It happens when some Jar files or other dependency related files of your project get corrupted. I was working on a small project when I got the same exception. I removed all the dependencies related to the project and reinstalled them. It started working for me.
Hope this helps!</p>

Body:
I have found other stackoverflow questions similar to this one. The answers seem to be particular to those people's errors, so I gave up on them.

I did not have this error when I left off on this project as I recall. I don't recall changing anything before I came back to this project and got this error.

I want to debug my web app on a local tomcat 8.5 server. In Eclipse IDE for Enterprise Java Developers Version 2019-03(4.11.0), I right-click on my web project and select Debug As->Debug on Server. A dialog box appears and I choose the option to Manually define a new server. I select Tomcat v8.5 Server. I click the Finish button. Some red text in the debug window appear. Then a dialog box appears saying:

'Starting Tomcat v8.5 Server at localhost' has encountered a problem.

Server Tomcat v8.5 Server at localhost failed to start.

I have been able to start tomcat with startup.sh successfully, and have been able to shut down tomcat with shutdown.sh successfully, so I know tomcat works by itself.

I am able to run this web project on AWS Beanstalk.

Here is what it says in the debug window:

Jan 31, 2020 9:54:37 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'antiJARLocking' to 'true' did not find a matching property.
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.5.41
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 4 2019 09:17:16 UTC
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.5.41.0
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.14.6
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_211.jdk/Contents/Home/jre
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_211-b12
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/shinehah/eclipse-workspaces/eclipse-java-ee-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/shinehah/tomcat/apache-tomcat-8.5.41
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -agentlib:jdwp=transport=dt_socket,suspend=y,address=localhost:56586
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -javaagent:/Users/shinehah/eclipse/jee-2019-03-3/Eclipse.app/Contents/Eclipse/configuration/org.eclipse.osgi/402/0/.cp/lib/javaagent-shaded.jar
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/shinehah/eclipse-workspaces/eclipse-java-ee-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/shinehah/tomcat/apache-tomcat-8.5.41
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/shinehah/eclipse-workspaces/eclipse-java-ee-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/shinehah/tomcat/apache-tomcat-8.5.41/endorsed
Jan 31, 2020 9:54:37 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jan 31, 2020 9:54:37 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/shinehah/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
Jan 31, 2020 9:54:38 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jan 31, 2020 9:54:38 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jan 31, 2020 9:54:38 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jan 31, 2020 9:54:38 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jan 31, 2020 9:54:38 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1816 ms
Jan 31, 2020 9:54:38 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service [Catalina]
Jan 31, 2020 9:54:38 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.5.41
Jan 31, 2020 9:54:39 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jan 31, 2020 9:54:39 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:882)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Realm[MemoryRealm]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5113)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Memory database file [/usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml] cannot be read
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:276)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 8 more
Caused by: java.io.FileNotFoundException: /usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at org.apache.tomcat.util.file.ConfigFileLoader.getInputStream(ConfigFileLoader.java:89)
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:258)
    ... 9 more

Jan 31, 2020 9:54:39 AM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:688)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:882)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 8 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Realm[MemoryRealm]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5113)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Memory database file [/usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml] cannot be read
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:276)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 8 more
Caused by: java.io.FileNotFoundException: /usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at org.apache.tomcat.util.file.ConfigFileLoader.getInputStream(ConfigFileLoader.java:89)
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:258)
    ... 9 more

Jan 31, 2020 9:54:39 AM org.apache.catalina.startup.Catalina start
SEVERE: The required Server component failed to start so Tomcat is unable to start.
org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:688)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:353)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:493)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 7 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 9 more
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 11 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 13 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1423)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1413)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:953)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:882)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:942)
    ... 8 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/webproject10]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Failed to start component [Realm[MemoryRealm]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5113)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more
Caused by: org.apache.catalina.LifecycleException: Memory database file [/usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml] cannot be read
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:276)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 8 more
Caused by: java.io.FileNotFoundException: /usr/share/tomcat8/webapps/ROOT/WEB-INF/tomcat-users.xml (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at org.apache.tomcat.util.file.ConfigFileLoader.getInputStream(ConfigFileLoader.java:89)
    at org.apache.catalina.realm.MemoryRealm.startInternal(MemoryRealm.java:258)
    ... 9 more

Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-nio-8080"]
Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-nio-8009"]
Jan 31, 2020 9:54:39 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service [Catalina]
Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-nio-8080"]
Jan 31, 2020 9:54:39 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-nio-8009"]

In the Problems pane, I see the following 4 errors:

Cannot change version of project facet Dynamic Web Module to 3.1.
JavaServer Faces 2.2 can not be installed : One or more constraints have not been satisfied.
JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer.
One or more constraints have not been satisfied.


来源: stackexchange

问:
Create resources iterating through the values of a map rather key - terraform
I couldn’t figure out how I can loop through the sum of values of the below map.

```<code>variable "images" {
  default = {
    "rhel-8-factory-os-ready" = {
       "availability_zone" = "eu-fra-1ah"
       "flavor" = 4
       "instance_count" = 2
       "image_name" = "rhel-8-factory-os-ready"
    },
    "rhel-7-factory-os-ready" = {
       "availability_zone" = "eu-fra-1ai"
       "instance_count" = 3
       "flavor" = 3
       "image_name" = "rhel-7-factory-os-ready"
    },
    "rhel-6-factory-os-ready" = {
       "availability_zone" = "eu-fra-1ah"
       "instance_count" = 3
       "flavor" = 3
       "image_name" = "rhel-6-factory-os-ready"
    }
  }
}
</code>```

Here, I’ve to iterate through the sum of instance_count attribute of the all the keys & create instances based on the instance_count.

I could calculate the sum of instance_count, with below inbuilt functions.

```<code>locals {
  list_sum = length(flatten([for i in var.images: range(i["instance_count"])]))
}
</code>```

How can I iterate through the list_sum variable & create the resources based on instance_count?

I created below lists to create resources ::

```<code>locals {
  list_images = tolist(keys(var.images))
  list_instance_count = [for i in var.images: i["instance_count"]]
  list_flavors = [for i in var.images: i["flavor"]]
  list_image_names = [for i in var.images: i["image_name"]]
  list_availability_zones = [for i in var.images: i["availability_zone"]]
}
</code>```

My resource ::

```<code>resource "openstack_compute_instance_v2" "instance" {
  count = local.list_sum
  image_name = element(local.list_image_names, count.index +1 )
  flavor_id = element(local.list_flavors, (count.index + 1) )
  name = element(local.list_image_names, (count.index + 1) )
  security_groups = var.security_group
  availability_zone = element(local.list_availability_zones, (count.index + 1) )
  key_pair = "foptst"
  network {
    name = var.network_name
  }
}
</code>```

By now, you may be knowing that my iteration is incorrect. My resource block has to create the number of resources based on instance_count var ie., 2 instances of rhel-8-factory-os-ready, 3 instances of rhel-7-factory-os-ready and 3 instances of rhel-6-factory-os-ready.

Because of incorrect looping, I couldn’t get it. It would be great if someone could help me how to iterate properly to create resources as expected.

Many Thanks in advance,
Harsha

答:
```<code>locals {
  expanded_image_names = flatten([
    for key, value in var.images : [
      for counter in range(var.images[key]["instance_count"]): var.images[key]["image_name"]
    ]
  ])
}

output "expanded_image_names" {
  value = local.expanded_image_names
}
</code>```

This will produce:

```<code>expanded_image_names = [
  "rhel-6-factory-os-ready",
  "rhel-6-factory-os-ready",
  "rhel-6-factory-os-ready",
  "rhel-7-factory-os-ready",
  "rhel-7-factory-os-ready",
  "rhel-7-factory-os-ready",
  "rhel-8-factory-os-ready",
  "rhel-8-factory-os-ready",
]
</code>```

Then use them:

```<code>resource "openstack_compute_instance_v2" "instance" {
  count = local.list_sum
  image_name = element(local.expanded_image_names, count.index +1 )  # <-----
  ... # Do similar for the others.

  key_pair = "foptst"
  network {
    name = var.network_name
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I couldn’t figure out how I can loop through the sum of values of the below map.

variable "images" {
  default = {
    "rhel-8-factory-os-ready" = {
       "availability_zone" = "eu-fra-1ah"
       "flavor" = 4
       "instance_count" = 2
       "image_name" = "rhel-8-factory-os-ready"
    },
    "rhel-7-factory-os-ready" = {
       "availability_zone" = "eu-fra-1ai"
       "instance_count" = 3
       "flavor" = 3
       "image_name" = "rhel-7-factory-os-ready"
    },
    "rhel-6-factory-os-ready" = {
       "availability_zone" = "eu-fra-1ah"
       "instance_count" = 3
       "flavor" = 3
       "image_name" = "rhel-6-factory-os-ready"
    }
  }
}

Here, I’ve to iterate through the sum of instance_count attribute of the all the keys & create instances based on the instance_count.

I could calculate the sum of instance_count, with below inbuilt functions.

locals {
  list_sum = length(flatten([for i in var.images: range(i["instance_count"])]))
}

How can I iterate through the list_sum variable & create the resources based on instance_count?

I created below lists to create resources ::

locals {
  list_images = tolist(keys(var.images))
  list_instance_count = [for i in var.images: i["instance_count"]]
  list_flavors = [for i in var.images: i["flavor"]]
  list_image_names = [for i in var.images: i["image_name"]]
  list_availability_zones = [for i in var.images: i["availability_zone"]]
}

My resource ::

resource "openstack_compute_instance_v2" "instance" {
  count = local.list_sum
  image_name = element(local.list_image_names, count.index +1 )
  flavor_id = element(local.list_flavors, (count.index + 1) )
  name = element(local.list_image_names, (count.index + 1) )
  security_groups = var.security_group
  availability_zone = element(local.list_availability_zones, (count.index + 1) )
  key_pair = "foptst"
  network {
    name = var.network_name
  }
}

By now, you may be knowing that my iteration is incorrect. My resource block has to create the number of resources based on instance_count var ie., 2 instances of rhel-8-factory-os-ready, 3 instances of rhel-7-factory-os-ready and 3 instances of rhel-6-factory-os-ready.

Because of incorrect looping, I couldn’t get it. It would be great if someone could help me how to iterate properly to create resources as expected.

Many Thanks in advance,
Harsha

Body:
locals {
  expanded_image_names = flatten([
    for key, value in var.images : [
      for counter in range(var.images[key]["instance_count"]): var.images[key]["image_name"]
    ]
  ])
}

output "expanded_image_names" {
  value = local.expanded_image_names
}

This will produce:

expanded_image_names = [
  "rhel-6-factory-os-ready",
  "rhel-6-factory-os-ready",
  "rhel-6-factory-os-ready",
  "rhel-7-factory-os-ready",
  "rhel-7-factory-os-ready",
  "rhel-7-factory-os-ready",
  "rhel-8-factory-os-ready",
  "rhel-8-factory-os-ready",
]

Then use them:

resource "openstack_compute_instance_v2" "instance" {
  count = local.list_sum
  image_name = element(local.expanded_image_names, count.index +1 )  # <-----
  ... # Do similar for the others.

  key_pair = "foptst"
  network {
    name = var.network_name
  }
}


问:
Take 2 variables from a list search in another list
I am working with GeoNames dump file and would like to make a script working. It should:
1) take a row from first txt file, e.g.

Jalalabad, AF

2) Take "Jalalabad" as var1 and "AF" as var2 and use it in search in another txt file which has a line for example:

7053281 Jalālābād   Jalalabad   Bihsud,Jalalabad,Jalālābād,bhswd,jlal abad,بهسود,جلال آباد  34.42189    70.46353    A   ADM2    AF      18  801         0       571 Asia/Kabul  2018-02-13

If found in the 2nd list, I would like to copy whole row (example above) to third file, also in txt. This is my script:

```<code>myfile ='Geo.txt'
myfile2 = 'allADM.txt'

myfile3 = open('GeoSearch.txt','w',encoding="utf-8")

mylist = []
mylist2 = []

with open(myfile,'r',encoding='utf-8') as myfile:
    for row in myfile:
        row = row.split(", ")
        var1, var2 = row
        mylist.append(row)

with open(myfile2,'r',encoding='utf-8') as myfile2:
    for row in myfile2:
        row = row.strip()
        mylist2.append(row)

for i in mylist:
    if i[0] in mylist2.row and i[1] in mylist2.row:
            myfile3.write(f"{mylist2.row}\n")
    else:
        pass
</code>```

I get the error:
Traceback (most recent call last):
  File "C:/Users/xxx/Documents/python work/GeoNameSearch.py", line 24, in
    if i[0] in mylist2.row and i[1] in mylist2.row:
AttributeError: 'list' object has no attribute 'row'

myfile ='Geo.txt' - all the things I want to query

myfile2 = 'allADM.txt' - A massive dump file I want to search in

myfile 3 = output file

Any help appreciated!

EDIT1:
Changed the last part:

```<code>for i in mylist2:
    if var1 in i and var2 in i:
            myfile3.write(f"{i}\n")
    else:
        pass
</code>```

which resulted in that I got the last result from my search file (12.5k lines). Seems the variables var1 and var2 kept resetting so that it only searched it once.

EDIT2, second script (suggested below + tweaks) also returns empty list:

```<code>with open('Geo.txt', 'r', encoding='utf-8') as queries:
    search_data = set(queries.readlines())

with open('12.txt', 'r', encoding='utf-8') as dataset:
    data = dataset.readlines()

matching_lines = []

for params in search_data:
    param1, param2 = params.split(', ')

for line in data:
    if param1 in line and param2 in line:
        matching_lines.append(line)

with open('GeoSearch.txt', 'w', encoding='utf-8') as result:
    for res in matching_lines:
        result.write(f'{param1}|{param2}|{res}\n')
</code>```

答:
I would use sets to avoid repetition in your list, also I'm considering performance isn't an issue, otherwise you can open the result file before and write the line on each successful match.</p>

```<code>with open('Geo.txt') as queries:
  search_data = set(line.strip() for line in queries.readlines())

with open('allADM.txt') as dataset:
  data = [line.strip() for line in dataset.readlines()]

matching_lines = []

for params in search_data:
  param1, param2 = params.split(',')

  for line in data:
    if param1 in line and param2 in line:
      matching_lines.append(line)

with open('GeoSearch.txt', 'w') as result:
  for res in matching_lines:
    result.write(f'{res}\n')
</code>```

Body:
I am working with GeoNames dump file and would like to make a script working. It should:
1) take a row from first txt file, e.g.

Jalalabad, AF

2) Take "Jalalabad" as var1 and "AF" as var2 and use it in search in another txt file which has a line for example:

7053281 Jalālābād   Jalalabad   Bihsud,Jalalabad,Jalālābād,bhswd,jlal abad,بهسود,جلال آباد  34.42189    70.46353    A   ADM2    AF      18  801         0       571 Asia/Kabul  2018-02-13

If found in the 2nd list, I would like to copy whole row (example above) to third file, also in txt. This is my script:

myfile ='Geo.txt'
myfile2 = 'allADM.txt'

myfile3 = open('GeoSearch.txt','w',encoding="utf-8")

mylist = []
mylist2 = []

with open(myfile,'r',encoding='utf-8') as myfile:
    for row in myfile:
        row = row.split(", ")
        var1, var2 = row
        mylist.append(row)

with open(myfile2,'r',encoding='utf-8') as myfile2:
    for row in myfile2:
        row = row.strip()
        mylist2.append(row)

for i in mylist:
    if i[0] in mylist2.row and i[1] in mylist2.row:
            myfile3.write(f"{mylist2.row}\n")
    else:
        pass

I get the error:
Traceback (most recent call last):
  File "C:/Users/xxx/Documents/python work/GeoNameSearch.py", line 24, in
    if i[0] in mylist2.row and i[1] in mylist2.row:
AttributeError: 'list' object has no attribute 'row'

myfile ='Geo.txt' - all the things I want to query

myfile2 = 'allADM.txt' - A massive dump file I want to search in

myfile 3 = output file

Any help appreciated!

EDIT1:
Changed the last part:

for i in mylist2:
    if var1 in i and var2 in i:
            myfile3.write(f"{i}\n")
    else:
        pass

which resulted in that I got the last result from my search file (12.5k lines). Seems the variables var1 and var2 kept resetting so that it only searched it once.

EDIT2, second script (suggested below + tweaks) also returns empty list:

with open('Geo.txt', 'r', encoding='utf-8') as queries:
    search_data = set(queries.readlines())

with open('12.txt', 'r', encoding='utf-8') as dataset:
    data = dataset.readlines()

matching_lines = []

for params in search_data:
    param1, param2 = params.split(', ')

for line in data:
    if param1 in line and param2 in line:
        matching_lines.append(line)

with open('GeoSearch.txt', 'w', encoding='utf-8') as result:
    for res in matching_lines:
        result.write(f'{param1}|{param2}|{res}\n')

Body:
I would use sets to avoid repetition in your list, also I'm considering performance isn't an issue, otherwise you can open the result file before and write the line on each successful match.

with open('Geo.txt') as queries:
  search_data = set(line.strip() for line in queries.readlines())

with open('allADM.txt') as dataset:
  data = [line.strip() for line in dataset.readlines()]

matching_lines = []

for params in search_data:
  param1, param2 = params.split(',')

  for line in data:
    if param1 in line and param2 in line:
      matching_lines.append(line)

with open('GeoSearch.txt', 'w') as result:
  for res in matching_lines:
    result.write(f'{res}\n')


问:
Need SQL query for getting formatted and hourly filtered date into excel reports
I need script help for generating a report in excel from SQL database. Below is the generated report.
I have kept date selection & Points IDs for getting data. But I need report as below format. SQL database having every minute data for POiniID's for other reports purposes.

Below image from Query Result
Below Image for Required Format with Hourly base data
Used Script

```<code>Select
JCIHistorianDB.dbo.RawAnalog.PointName,
JCIHistorianDB.dbo.RawAnalog.PointID,
JCIHistorianDB.dbo.RawAnalog.PointSliceID,
JCIHistorianDB.dbo.RawAnalog.UTCDateTime,
JCIHistorianDB.dbo.RawAnalog.ActualValue
From
JCIHistorianDB.dbo.RawAnalog
where JCIHistorianDB.dbo.RawAnalog.UTCDateTime between ? and ?
AND JCIHistorianDB.dbo.RawAnalog.PointID IN (5478,2262,5480,2305,2304,2302,2303)
</code>```

答:
This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

```<code>insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=D:\testing.xls;',
    'SELECT * FROM [SheetName$]') select * from SQLServerTable
</code>```

2 Export data from Excel to new SQL Server table

```<code>select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=D:\testing.xls;HDR=YES',
    'SELECT * FROM [Sheet1$]')
</code>```

3 Export data from Excel to existing SQL Server table (edited)

```<code>Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=D:\testing.xls;HDR=YES',
    'SELECT * FROM [SheetName$]')
</code>```

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

```<code>EXEC sp_makewebtask
    @outputfile = 'd:\testing.xls',
    @query = 'Select * from Database_name..SQLServerTable',
    @colheaders =1,
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'
</code>```

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

```<code>create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
    information_schema.columns
where
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)
</code>```

After creating the procedure, execute it by supplying database name, table name and file path:

```<code>EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'
</code>```

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved.  I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following:
I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

```<code>update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99
</code>```

You can also add formulas to Excel using this:

```<code>update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'
</code>```

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server).  For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for
  distributed queries

Then run this:

```<code>sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
</code>```

'''
'''

repost from: T-SQL: Export to new Excel file

credit to: @JonH

Body:
I need script help for generating a report in excel from SQL database. Below is the generated report.
I have kept date selection & Points IDs for getting data. But I need report as below format. SQL database having every minute data for POiniID's for other reports purposes.

Below image from Query Result
Below Image for Required Format with Hourly base data
Used Script

Select
JCIHistorianDB.dbo.RawAnalog.PointName,
JCIHistorianDB.dbo.RawAnalog.PointID,
JCIHistorianDB.dbo.RawAnalog.PointSliceID,
JCIHistorianDB.dbo.RawAnalog.UTCDateTime,
JCIHistorianDB.dbo.RawAnalog.ActualValue
From
JCIHistorianDB.dbo.RawAnalog
where JCIHistorianDB.dbo.RawAnalog.UTCDateTime between ? and ?
AND JCIHistorianDB.dbo.RawAnalog.PointID IN (5478,2262,5480,2305,2304,2302,2303)

Body:
This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=D:\testing.xls;',
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select *
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=D:\testing.xls;HDR=YES',
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'Excel 8.0;Database=D:\testing.xls;HDR=YES',
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask
    @outputfile = 'd:\testing.xls',
    @query = 'Select * from Database_name..SQLServerTable',
    @colheaders =1,
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name
from
    information_schema.columns
where
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved.  I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following:
I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\test.xls;hdr=no',
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server).  For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for
  distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

'''
'''

repost from: T-SQL: Export to new Excel file

credit to: @JonH


问:
Passing variable from type std::function fails although the caller expect the exact same type
for some reason I cannot pass value to method with the exact type.

But if I cast the variable I wish to pass using decltype of itself, it somehow works (?)
Perhaps anybody know what's the reason.

Also, When I pass the lambda block to std::function it doesn't require any casting, although they're not exactly the same.

the following example demonstrate my findings :

```<code>#include <functional>

class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(f) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    //B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
    B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
};

class C {
public:
    C(std::function<void(std::string&,int)> f) {
        //b = new B(f); --> this one trigger casting error, why ?
        b = new B((decltype(f)) f);
    }
    B *b;
};

int main(int argc, const char * argv[]) {
    // this works for some reason, even though C c'tor expect std::function ... why ?
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}

</code>```

答:
If you get an rvalue ref and want to pass this parameter as parameter to any function you call, you have to use std::move to keep it as an rvalue ref.

An explanation why and how std::move must be used, can you find here

BTW: I have no idea why you need to have revalue ref in your functions/constructors but that is something which might be useful in your real code.

Your code will be something like that:

```<code>class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(std::move(f)) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    B(std::function<void(std::string&, int)> &&f) : A(std::move(f)) { }
};

class C {
public:
    // ATTENTION: Here you use not an rvalue ref, so you create a copy
    // which later will be moved. Can be ok, dependent on what you want
    // to achieve
    C(std::function<void(std::string&,int)> f):b( new B(std::move(f))) { }
    B *b;
};

int main() {
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}
</code>```

Body:
for some reason I cannot pass value to method with the exact type.

But if I cast the variable I wish to pass using decltype of itself, it somehow works (?)
Perhaps anybody know what's the reason.

Also, When I pass the lambda block to std::function it doesn't require any casting, although they're not exactly the same.

the following example demonstrate my findings :

#include <functional>

class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(f) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    //B(std::function<void(std::string&, int)> &&f) : A(f) { } --> fail on casting error, why ?
    B(std::function<void(std::string&, int)> &&f) : A((decltype(f)) f) { }
};

class C {
public:
    C(std::function<void(std::string&,int)> f) {
        //b = new B(f); --> this one trigger casting error, why ?
        b = new B((decltype(f)) f);
    }
    B *b;
};

int main(int argc, const char * argv[]) {
    // this works for some reason, even though C c'tor expect std::function ... why ?
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}

Body:
If you get an rvalue ref and want to pass this parameter as parameter to any function you call, you have to use std::move to keep it as an rvalue ref.

An explanation why and how std::move must be used, can you find here

BTW: I have no idea why you need to have revalue ref in your functions/constructors but that is something which might be useful in your real code.

Your code will be something like that:

class A {
public:
    A(std::function<void(std::string&, int)> &&f): _f(std::move(f)) { }

    std::function<void(std::string&,int)> _f;
};

class B : public A {
public:
    B(std::function<void(std::string&, int)> &&f) : A(std::move(f)) { }
};

class C {
public:
    // ATTENTION: Here you use not an rvalue ref, so you create a copy
    // which later will be moved. Can be ok, dependent on what you want
    // to achieve
    C(std::function<void(std::string&,int)> f):b( new B(std::move(f))) { }
    B *b;
};

int main() {
    C c([=](std::string&a, int b) {
        printf("%s %d\n", a.c_str(), b);
    });
}


问:
SQL Server "CREATE PROCEDURE" not executing when procedure contains a join to a non-existent SEQUENCE?
Does anyone know why the following CREATE PROCEDURE statement does not work (it says "Commands completed successfully", but the procedure is not being created:

```<code>CREATE PROCEDURE [dbo].[TestProc]
AS
BEGIN
    DECLARE @TV TABLE (lKey int null)

    UPDATE @TV
    SET lKey = 0 --a.lKey
    FROM @TV
    CROSS JOIN
        -- Joining to select from non-existant sequence.
        (SELECT NEXT VALUE FOR TestSeqDoesntExist AS lKey) a
END
GO
</code>```

It appears to be something to do with the sequence not existing in the database - substituting an existing sequence object causes the procedure to be created as expected.

I would have expected the procedure to be created, but to fail on executing with an error about the sequence not existing.

I'm using SSMS v17.9 connecting to a SQL Server 2017 database (v14.0.1000.169).

答:
It appears that this issue has been fixed by Cumulative Update 19 for SQL Server 2017 https://support.microsoft.com/en-us/help/4535007/cumulative-update-19-for-sql-server-2017

Although it is not completely obvious to me which of the documented fixes relate (if any), I updated my local Developer installation and the procedure is now created as expected.

Thanks to @Larnu and @[Jeroen Mostert] for pointing me in the right direction.

Body:
Does anyone know why the following CREATE PROCEDURE statement does not work (it says "Commands completed successfully", but the procedure is not being created:

CREATE PROCEDURE [dbo].[TestProc]
AS
BEGIN
    DECLARE @TV TABLE (lKey int null)

    UPDATE @TV
    SET lKey = 0 --a.lKey
    FROM @TV
    CROSS JOIN
        -- Joining to select from non-existant sequence.
        (SELECT NEXT VALUE FOR TestSeqDoesntExist AS lKey) a
END
GO

It appears to be something to do with the sequence not existing in the database - substituting an existing sequence object causes the procedure to be created as expected.

I would have expected the procedure to be created, but to fail on executing with an error about the sequence not existing.

I'm using SSMS v17.9 connecting to a SQL Server 2017 database (v14.0.1000.169).


问:
How to remove xpath from extract_first() output?
I'm new to Python, so apologies in advance for any idiocy.

I'm scraping information from a website, and am extracting elements using .extract_first().

What I wanted the output to be was just the text of the element, ie 'Bob Smith'. But instead, it seems like the xpath is being printed around the name:

Relevant code:

```<code>sel = Selector(text=driver.page_source)
name = sel.xpath('//li[@class="inline t-24 t-black t-normal break-words"]').extract_first()
if name:
     name = name.strip()
print(name)
</code>```

Output:

```<code>'<li class="inline t-24 t-black t-normal break-words">\n            Bob Smith\n          </li>'
</code>```

I tried finding a solution online, but haven't found one that deals with this issue in the context of extract_first() . How do I get rid of the xpath so the output being printed is just the element text? Thanks.

答:
Try using

```<code>name = sel.xpath('normalize-space(//li[@class="inline t-24 t-black t-normal break-words"])').extract_first()
</code>```

My output from the html in your question:

Bob Smith

Body:
I'm new to Python, so apologies in advance for any idiocy.

I'm scraping information from a website, and am extracting elements using .extract_first().

What I wanted the output to be was just the text of the element, ie 'Bob Smith'. But instead, it seems like the xpath is being printed around the name:

Relevant code:

sel = Selector(text=driver.page_source)
name = sel.xpath('//li[@class="inline t-24 t-black t-normal break-words"]').extract_first()
if name:
     name = name.strip()
print(name)

Output:

'
\n            Bob Smith\n
'

I tried finding a solution online, but haven't found one that deals with this issue in the context of extract_first() . How do I get rid of the xpath so the output being printed is just the element text? Thanks.

Body:
Try using

name = sel.xpath('normalize-space(//li[@class="inline t-24 t-black t-normal break-words"])').extract_first()

My output from the html in your question:

Bob Smith


问:
GCP stackdriver logging logs format changed in bucket from folder per container to stdout\stderr
i have a question, similar as describe here: GKE kubernetes container stdout logs format changed

in old version of stackdriver i had 1 sink with filter like this:

```<code>resource.type=container,
resource.namespace_id=[NAMESPACE_NAME]
resource.pod_id=[POD_NAME]
</code>```

and logs was stored in bucket pretty well, like this:

```<code>logName=projects/[PROJECT-NAME]/logs/[CONTAINER-NAME]
</code>```

...so i had folders whith logs for each container.

But now i updated my stackdriver logging+monitoring to last version and now i have 2 folders stdout\stderr which contains all logs for all containers!

```<code>logName=projects/[PROJECT-NAME]/logs/stdout
logName=projects/[PROJECT-NAME]/logs/stderr
</code>```

All logs from many containers stored in this single folders! This is pretty uncomfortable =(

I'v read about this in docs: https://cloud.google.com/monitoring/kubernetes-engine/migration#changes_in_log_entry_contents

The logName field might change. Stackdriver Kubernetes Engine Monitoring log entries use stdout or stderr in their log names whereas Legacy Stackdriver used a wider variety of names, including the container name. The container name is still available as a resource label.

...but i can't find solution! Please, help me, how to make container per folder logging, like it was in old version of stackdriver?

答:
Here is a workaround that has been suggested:

Create a different sink for each of your containers filtered by
resource.labels.container_name

Export each sink to a different
bucket

Note: If you configure each separate sink to the same bucket the logs will be combined.

More details at Google Issue Tracker

Body:
i have a question, similar as describe here: GKE kubernetes container stdout logs format changed

in old version of stackdriver i had 1 sink with filter like this:

resource.type=container,
resource.namespace_id=[NAMESPACE_NAME]
resource.pod_id=[POD_NAME]

and logs was stored in bucket pretty well, like this:

logName=projects/[PROJECT-NAME]/logs/[CONTAINER-NAME]

...so i had folders whith logs for each container.

But now i updated my stackdriver logging+monitoring to last version and now i have 2 folders stdout\stderr which contains all logs for all containers!

logName=projects/[PROJECT-NAME]/logs/stdout
logName=projects/[PROJECT-NAME]/logs/stderr

All logs from many containers stored in this single folders! This is pretty uncomfortable =(

I'v read about this in docs: https://cloud.google.com/monitoring/kubernetes-engine/migration#changes_in_log_entry_contents

The logName field might change. Stackdriver Kubernetes Engine Monitoring log entries use stdout or stderr in their log names whereas Legacy Stackdriver used a wider variety of names, including the container name. The container name is still available as a resource label.

...but i can't find solution! Please, help me, how to make container per folder logging, like it was in old version of stackdriver?


问:
Cannot find a differ supporting object '[object Object]' of type 'object'. - context menu issues
I have issues with context menu. I am not sure why, I made similar thing many times but now I am unable to pass it. When I deleted this line:

```<code><div *ngFor="let element of contextMenu">
</div>
</code>```

Context menu works fine (but I need this line to fill my context menu.
This is part of html:

```<code><mat-menu #contextMenu="matMenu">
    <ng-template matMenuContent>
    <div *ngFor="let element of contextMenu">
    </div>
    </ng-template>
</mat-menu>
</code>```

And my context menu object:

```<code>  @Input() contextMenu: MenuElement[];
</code>```

And html with filled input:

```<code>  <lib-mp-file-explorer
          [fileElements]="fileElements | async"
          [path]="currentPath"
          [canNavigateUp]="canNavigateUp"
          [topMenu]="topMenu"
          [contextMenu]="contextMenu"
          (folderAdded)="addFolder($event)"
          (elementRemoved)="removeElement($event)"
          (navigatedDown)="navigateToFolder($event)"
          (navigatedUp)="navigateUp()"
          (elementRenamed)="renameElement($event)"
          (elementMoved)="moveElement($event)"
        >
  </lib-mp-file-explorer>
</code>```

And my construction:

```<code>this.contextMenu = [
      {
        name: 'Open in Mark',
        icon: 'M',
        action: undefined,
        disabled: true
      },
      ...
]
</code>```

I hate this error now:

core.js:5828 ERROR Error: Cannot find a differ supporting object
  '[object Object]' of type 'object'. NgFor only supports binding to
  Iterables such as Arrays.

But my array is iterable T.T

答:
You can check what there are actual values in your contextMenu:

```<code><p>contextMenu {{ contextMenu | json }}
</code>```

However, your error says that it is object, so you can use keyvalue pipe since Angular 6:

```<code><div *ngFor="let item of contextMenu | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>
</code>```

Body:
I have issues with context menu. I am not sure why, I made similar thing many times but now I am unable to pass it. When I deleted this line:

Context menu works fine (but I need this line to fill my context menu.
This is part of html:

<mat-menu #contextMenu="matMenu">
    <ng-template matMenuContent>

    </ng-template>
</mat-menu>

And my context menu object:

  @Input() contextMenu: MenuElement[];

And html with filled input:

  <lib-mp-file-explorer
          [fileElements]="fileElements | async"
          [path]="currentPath"
          [canNavigateUp]="canNavigateUp"
          [topMenu]="topMenu"
          [contextMenu]="contextMenu"
          (folderAdded)="addFolder($event)"
          (elementRemoved)="removeElement($event)"
          (navigatedDown)="navigateToFolder($event)"
          (navigatedUp)="navigateUp()"
          (elementRenamed)="renameElement($event)"
          (elementMoved)="moveElement($event)"
        >
  </lib-mp-file-explorer>

And my construction:

this.contextMenu = [
      {
        name: 'Open in Mark',
        icon: 'M',
        action: undefined,
        disabled: true
      },
      ...
]

I hate this error now:

core.js:5828 ERROR Error: Cannot find a differ supporting object
  '[object Object]' of type 'object'. NgFor only supports binding to
  Iterables such as Arrays.

But my array is iterable T.T

Body:
You can check what there are actual values in your contextMenu:

<p>contextMenu {{ contextMenu | json }}

However, your error says that it is object, so you can use keyvalue pipe since Angular 6:

<div *ngFor="let item of contextMenu | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>


问:
Add marginal density plot based on subset of plotted data
I have a line plot p generated from a long/melted dataframe DF.

I would now like to add a marginal density plot along the y axis to show the distribution of score at t5. I have just come across ggExtra::ggMarginal, but the tutorials I've found only seem to work with scatter plots and not with subsets of the main plot's data.

Here's the structure of DF:

```<code>> str(DF)
'data.frame':   600 obs. of  3 variables:
 $ ID      : int  1 2 3 4 5 6 7 8 9 10 ...
 $ variable: Factor w/ 6 levels "t0","t1","t2",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : num  0.737 0.33 0.526 0.737 0.357 ...
</code>```

And here's my line plot p:

I tried this...

```<code># the code that produces the line plot above
p <- ggplot(DF, aes(x = variable, y = value, color = ID, group = ID))+
  geom_line() +
  theme_bw() +
  ylim(0, 1) +
  labs(x = "Time", y = "Score", color = "ID", subtitle = "")+
  theme(legend.position = "none")

#trying to add marginal density plot based on subsetted t5 scores
p <- ggMarginal(p, data = DF[which(DF$variable == "t5"),], x = value, type = "density")
</code>```

But it throws this error: Error: No geom_point layer was found in your scatter plot

Does ggMarginal only work with scatter plots? How might I add a marginal density plot of score at t5 to the right side y axis?

答:
I'll go ahead and answer my own question following @ricoderks comment.

It seems the solution is to just plot an invisible scatter plot. Here's the code that worked:

```<code>p <- ggplot(DF, aes(x = variable, y = value, color = ID, group = ID))+
  geom_line() +
  geom_point(data = DF[which(DF$variable == "t5"),], alpha = 0)+
  theme_bw() +
  ylim(0, 1) +
  labs(x = "Time", y = "Score", color = "ID", subtitle = "")+
  theme(legend.position = "none")
p <- ggMarginal(p, type = "density", margins = "y", size = 6, color = "steelblue4")
</code>```

Body:
I have a line plot p generated from a long/melted dataframe DF.

I would now like to add a marginal density plot along the y axis to show the distribution of score at t5. I have just come across ggExtra::ggMarginal, but the tutorials I've found only seem to work with scatter plots and not with subsets of the main plot's data.

Here's the structure of DF:

> str(DF)
'data.frame':   600 obs. of  3 variables:
 $ ID      : int  1 2 3 4 5 6 7 8 9 10 ...
 $ variable: Factor w/ 6 levels "t0","t1","t2",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value   : num  0.737 0.33 0.526 0.737 0.357 ...

And here's my line plot p:

I tried this...

# the code that produces the line plot above
p <- ggplot(DF, aes(x = variable, y = value, color = ID, group = ID))+
  geom_line() +
  theme_bw() +
  ylim(0, 1) +
  labs(x = "Time", y = "Score", color = "ID", subtitle = "")+
  theme(legend.position = "none")

#trying to add marginal density plot based on subsetted t5 scores
p <- ggMarginal(p, data = DF[which(DF$variable == "t5"),], x = value, type = "density")

But it throws this error: Error: No geom_point layer was found in your scatter plot

Does ggMarginal only work with scatter plots? How might I add a marginal density plot of score at t5 to the right side y axis?

Body:
I'll go ahead and answer my own question following @ricoderks comment.

It seems the solution is to just plot an invisible scatter plot. Here's the code that worked:

p <- ggplot(DF, aes(x = variable, y = value, color = ID, group = ID))+
  geom_line() +
  geom_point(data = DF[which(DF$variable == "t5"),], alpha = 0)+
  theme_bw() +
  ylim(0, 1) +
  labs(x = "Time", y = "Score", color = "ID", subtitle = "")+
  theme(legend.position = "none")
p <- ggMarginal(p, type = "density", margins = "y", size = 6, color = "steelblue4")


问:
Determine a locale change inherited from a parent element
I am trying to write a locale-aware custom element. To format its output, it looks up lang attributes on itself and its parent elements, falling back on the browser navigator.language UI localization.

```<code>format (d, m, s) {
    const lang = (this.closest('[lang]') || document.querySelector('html')).lang;

    let list = navigator.languages;
    try {
        list = Intl.getCanonicalLocales(lang);
    } catch (e) {}

    const format = new Intl.NumberFormat(list, {
        maximumFractionDigits: 2
    }).format;

    return `${d}° ${m}′ ${format(Math.round(s * 100) / 100)}″`;
}
</code>```

That will give me the best possible information each time the component changes its value. But it doesn't cover cases where the lang attribute is changed during runtime. If the attribute is changed on the component itself, I can observe its change:

```<code>static get observedAttributes() { return ['lang']; }

attributeChangedCallback (name, oldValue, newValue) {
  if (name === 'lang') // trigger re-rendering
}
</code>```

But how would I go about detecting change if it happens on a parent element or even the browser UI from which the setting is inherited?

A MutationObserver seems to be an awkward choice: I would have to attach it to every element in the parent chain, but can't assume that list to remain static - I would have to re-attach the Observer on every adopted or connected event of the component.

答:
A possible solution would be that when the element is added to the page it recursively searches for the first parent/ancestor that has a lang attribute, adds a MutationObserver to it and responds to changes to that specific parent element.

IMO attempting to observe changes for all parents is an inefficient design choice and also sounds like an overkill feature.

I have not tried this personally, but to detect a change to the browser language, look into the languagechange event.

Body:
I am trying to write a locale-aware custom element. To format its output, it looks up lang attributes on itself and its parent elements, falling back on the browser navigator.language UI localization.

format (d, m, s) {
    const lang = (this.closest('[lang]') || document.querySelector('html')).lang;

    let list = navigator.languages;
    try {
        list = Intl.getCanonicalLocales(lang);
    } catch (e) {}

    const format = new Intl.NumberFormat(list, {
        maximumFractionDigits: 2
    }).format;

    return `${d}° ${m}′ ${format(Math.round(s * 100) / 100)}″`;
}

That will give me the best possible information each time the component changes its value. But it doesn't cover cases where the lang attribute is changed during runtime. If the attribute is changed on the component itself, I can observe its change:

static get observedAttributes() { return ['lang']; }

attributeChangedCallback (name, oldValue, newValue) {
  if (name === 'lang') // trigger re-rendering
}

But how would I go about detecting change if it happens on a parent element or even the browser UI from which the setting is inherited?

A MutationObserver seems to be an awkward choice: I would have to attach it to every element in the parent chain, but can't assume that list to remain static - I would have to re-attach the Observer on every adopted or connected event of the component.


问:
Why can't I use ~0 to initialize signed char?
I wrote like this:

```<code>#include <stdio.h>
#include <limits.h>

main()
{
    signed char i = ~0;
    printf("%zu\n", i);
    return 0;
}
</code>```

But the result is 4294967295 instead of -1. Why does this happen?

答:
you are printing i value using %zu. In unisgned format -1=2^32-1 which is equals to
4294967295. Compiler uses the formula 2^(sizeoftype in bits)-n to convert signed values to unsigned.</p>

Body:
I wrote like this:

#include <stdio.h>
#include <limits.h>

main()
{
    signed char i = ~0;
    printf("%zu\n", i);
    return 0;
}

But the result is 4294967295 instead of -1. Why does this happen?


问:
Python Beautifulsoup Scraper not scraping images
I have the below code:-

```<code>import requests
from bs4 import BeautifulSoup

url = ""

page = requests.get(url, headers=HEADERS, verify=True)
soup = BeautifulSoup(page.content, 'html.parser')
images = soup.find_all("img")
for image in images:
    image_url = image['src']
    print(image_url)
    if url not in image_url:  #This is to identify absolute/relative links
        link = urllib.parse.urljoin(url, image_url)
    else:
        link = image_url
</code>```

I am working my way through thousands of URLs that I have agreement to scrape images from. Nonetheless, the URLs for some images aren't being detected. An example of a URL that returns no links in below below:-

https://www.lerryn-cornwall.co.uk/

Checking the source view, there are image links such as:-

```<code>link rel="apple-touch-icon" href="https://primarysite-prod.s3.amazonaws.com/theme/LerrynCofEPrimarySchool/apple-touch-icon-precomposed.png">
</code>```

Any suggestions on handling every possible eventuality of image links in thousands of web pages? I'm thinking of instead of looking for the img['src'] tag, I simply process 'soup' and look for any strings containing '.png' for example and then append these to a list. Is there a better means?

答:
Try following css selector.check if that helps.

```<code>for item in soup.select('[href*=".png"],[src*=".png"]'):
    print(item)
</code>```

Body:
I have the below code:-

import requests
from bs4 import BeautifulSoup

url = ""

page = requests.get(url, headers=HEADERS, verify=True)
soup = BeautifulSoup(page.content, 'html.parser')
images = soup.find_all("img")
for image in images:
    image_url = image['src']
    print(image_url)
    if url not in image_url:  #This is to identify absolute/relative links
        link = urllib.parse.urljoin(url, image_url)
    else:
        link = image_url

I am working my way through thousands of URLs that I have agreement to scrape images from. Nonetheless, the URLs for some images aren't being detected. An example of a URL that returns no links in below below:-

https://www.lerryn-cornwall.co.uk/

Checking the source view, there are image links such as:-

link rel="apple-touch-icon" href="https://primarysite-prod.s3.amazonaws.com/theme/LerrynCofEPrimarySchool/apple-touch-icon-precomposed.png">

Any suggestions on handling every possible eventuality of image links in thousands of web pages? I'm thinking of instead of looking for the img['src'] tag, I simply process 'soup' and look for any strings containing '.png' for example and then append these to a list. Is there a better means?

Body:
Try following css selector.check if that helps.

for item in soup.select('[href*=".png"],[src*=".png"]'):
    print(item)


问:
Correct approach to avoid rendering view in Action
I currently use an ajax post back to an action to create a new database object and then return the rendered html for a view of that object. I then inject that html into the page.

I was wondering, since MVC does easily allow you to render views to HTML from within controllers, if there was a better (or more correct) approach to the problem.

(I currently use this code to render the view as html in the action).

Any and all ideas appreciated.

答:
It's true you can render it using PartialView or doing it custom via JSON (PartialView is just so much easier!).

It really depends on your implementation and choices regarding graceful degradation.

What I usually do is:

```<code>[HttpGet]
public ActionResult SignIn()
{
    //Check if it is an AJAX request
    if (Request.IsAjaxRequest())
        return PartialView();
    else
         return View();
}
</code>```

So it is possible to get your cake and eat it too.

Truth be told there are various ways to get this view from the server. You could use the asp.net mvc ajax js library, use .getJSON or .ajax, or even do it via JQuery using .load: http://api.jquery.com/load/

ContentLicense: CC BY-SA 3.0

Body:
It's true you can render it using PartialView or doing it custom via JSON (PartialView is just so much easier!).

It really depends on your implementation and choices regarding graceful degradation.

What I usually do is:

[HttpGet]
public ActionResult SignIn()
{
    //Check if it is an AJAX request
    if (Request.IsAjaxRequest())
        return PartialView();
    else
         return View();
}

So it is possible to get your cake and eat it too.

Truth be told there are various ways to get this view from the server. You could use the asp.net mvc ajax js library, use .getJSON or .ajax, or even do it via JQuery using .load: http://api.jquery.com/load/


问:
Animated graph using matplotlib issue?
I am trying to plot an animated graph for some data I have.The code works perfectly fine but I would like to see the line going down slowly and in steps.I tried adjusting the interval but it plots too fast.Can anyone tell me where I am doing wrong?The code is below</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

max_x = 12
max_rand = 0.5

x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [0.2993408770000, 0.2861708408982, 0.2798758117082,
                                                         0.2798758117081, 0.2576574556766,
                                                         0.2569827358085, 0.2462213069654, 0.2461901361123,
                                                         0.2455803085695, 0.2455803085695, 0.2455803085695,
                                                         0.2455803085695])

def init():  # give a clean slate to start
    line.set_ydata([np.nan] * len(x))
    return line,

def animate(i):  # update the y values (every 1000ms)
    line.set_ydata(np.array([0.2993408770000, 0.2861708408982, 0.2798758117082,
                             0.2798758117081, 0.2576574556766,
                             0.2569827358085, 0.2462213069654, 0.2461901361123,
                             0.2455803085695, 0.2455803085695, 0.2455803085695,
                             0.2455803085695]))
    return line,

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=1000, blit=True, save_count=5)

plt.show()
</code>```

答:
You're not changing the position of y inside the animate function, so there will be no movement. You would need to change the position depending on the input parameter i.

In the code below, there is a y0 representing a starting position (for example zero), and y1 represents the end position. The variable numsteps controls in how many steps the curve moves from the starting to the final position. The interval is lowered to get a smoother animation.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

max_x = 12
max_rand = 0.5
num_steps = 200

x = np.arange(0, max_x)
# y0 : starting position of the curve
y0 = x*0
# y1 : final position of the curve
y1 = np.array([0.2993408770000, 0.2861708408982, 0.2798758117082, 0.2798758117081, 0.2576574556766, 0.2569827358085,
               0.2462213069654, 0.2461901361123, 0.2455803085695, 0.2455803085695, 0.2455803085695, 0.2455803085695])

ax.set_ylim(0, max_rand)
line, = ax.plot(x, y0, color='crimson')

def init():  # give a clean slate to start
    line.set_ydata(np.full_like(x, np.NaN))
    return line,

def animate(i):  # update the y values (every 100ms)
    line.set_ydata(y0 * (1 - i / num_steps) + y1 * i / num_steps)
    return line,

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=100, blit=True, save_count=5, frames=num_steps, repeat=False)
plt.show()
```

Title: Animated graph using matplotlib issue?

Body:
I am trying to plot an animated graph for some data I have.The code works perfectly fine but I would like to see the line going down slowly and in steps.I tried adjusting the interval but it plots too fast.Can anyone tell me where I am doing wrong?The code is below

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

max_x = 12
max_rand = 0.5

x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [0.2993408770000, 0.2861708408982, 0.2798758117082,
                                                         0.2798758117081, 0.2576574556766,
                                                         0.2569827358085, 0.2462213069654, 0.2461901361123,
                                                         0.2455803085695, 0.2455803085695, 0.2455803085695,
                                                         0.2455803085695])

def init():  # give a clean slate to start
    line.set_ydata([np.nan] * len(x))
    return line,

def animate(i):  # update the y values (every 1000ms)
    line.set_ydata(np.array([0.2993408770000, 0.2861708408982, 0.2798758117082,
                             0.2798758117081, 0.2576574556766,
                             0.2569827358085, 0.2462213069654, 0.2461901361123,
                             0.2455803085695, 0.2455803085695, 0.2455803085695,
                             0.2455803085695]))
    return line,

ani = animation.FuncAnimation(
    fig, animate, init_func=init, interval=1000, blit=True, save_count=5)

plt.show()


问:
Insert data to database not working (PHP-SQL)
My insert data sql command in my PHP code is not working. Can anyone help please?

I have a registration form that takes the values from the input fields (name, lastname, email, username and password)

The values that the user inputs in this fields should be saved into my table "users" whith columns (ID [which is the primary key /INT], name [TEXT], lastname[TEXT], e-mail [VARCHAR], username[VARCHAR] and password [VARCHAR]) .

Here is my current code:

if (isset ($_POST['name'],$_POST['lastname'],$_POST['email'],$_POST['username'], $_POST['password']))
    {
        //connect to database
        $conn = mysqli_connect ('localhost', 'root', '', 'test_database');

        if ($conn)
        {
            $sql="SELECT username FROM users WHERE username = '" . $_POST['username'] . "';";
            $query = mysqli_query ($conn, $sql);
            $result = mysqli_fetch_array ($query);

            if ($result ['username'])
            {
                header ('Location: ' . $_SERVER['PHP_SELF'] . '?errno=1');
            }
            else
            {
                $sql="INSERT INTO users (ID, name, lastname, e-mail, username, password) VALUES (' ','" .$_POST['name'] . "' ,'" . $_POST['lastname']. "' ,'" . $_POST['email']. "' ,'" . $_POST['username']. "' ,'" . $_POST['password']. "');";
                mysqli_query ($conn, $sql);
                mysqli_close ($conn);
                //registration completed, redirect to index page
                //header ('Location:index.php?reg=1');

            }
        }

        else
        {
            echo 'connection error';
        }

    }
```

答:
you use ' ' to insert id. the id should be autoincrement and unique. you cannot insert a white space to all.
try to remove id from insert into query. turn your query into this</p>

```<code>$sql="INSERT INTO users (name, lastname, e-mail, username, password) VALUES ('" .$_POST['name'] . "' ,'" . $_POST['lastname']. "' ,'" . $_POST['email']. "' ,'" . $_POST['username']. "' ,'" . $_POST['password']. "');";
</code>```

Body:
you use ' ' to insert id. the id should be autoincrement and unique. you cannot insert a white space to all.
try to remove id from insert into query. turn your query into this

$sql="INSERT INTO users (name, lastname, e-mail, username, password) VALUES ('" .$_POST['name'] . "' ,'" . $_POST['lastname']. "' ,'" . $_POST['email']. "' ,'" . $_POST['username']. "' ,'" . $_POST['password']. "');";