问:
Seed data import failed on jboss-javaee6-webapp
I am trying to get a basic Seam 3 webapplication to work and use the jboss-javaee6-webapp to achieve this goal. Using the manual at http://seamframework.org/Documentation/CDIQuickstartForMavenUsers.

However, I am running into some problems which I haven't been able to solve for days. I have basically no experience in JavaEE so the solution is probably really easy.

What I've done? I've simply generated a new maven project based on the supplied archetype and didn't change anything about it. I've installed Eclipse Helios including JBoss Tools and downloaded JBoss 6.0.0 and got Eclipse to deploy the application to the server succesfully.

While deploying, an exception occurs in the example code. To be specific the following exceptions occurs:

```<code>09:29:20,712 WARN  [seam3-example] Seed data import failed.: java.lang.NullPointerException
        at org.jboss.weld.integration.persistence.JBossJpaServices.resolvePersistenceContext(JBossJpaServices.java:59) [:6.0.0.Final]
    at org.jboss.weld.util.Beans.injectEEFields(Beans.java:781) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:181) [:6.0.0.Final]
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:176) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:142) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:339) [:6.0.0.Final]
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:67) [:6.0.0.Final]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:669) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractReceiverBean.getReceiver(AbstractReceiverBean.java:84) [:6.0.0.Final]
    at org.jboss.weld.bean.ProducerField$1.produce(ProducerField.java:134) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:361) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.createUnderlying(EEResourceProducerField.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.access$000(EEResourceProducerField.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField$EEResourceCallable.call(EEResourceProducerField.java:80) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.CallableMethodHandler.invoke(CallableMethodHandler.java:50) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:62) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:125) [:6.0.0.Final]
    at org.jboss.weldx.persistence.org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.persist(org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.java)
    at nl.jdi.examples.data.SeedDataImporter.importData(SeedDataImporter.java:51) [:]
...
</code>```

I've searched for a solution for this exact exception but I could barely find anything about it. This probably means that I've overlooked something very simple. So I've analysed the exception and found the following:

The exception message is from the example code (SeedDataImporter.java:61)

The exception itself (NullPointer) is thrown somewhere in the weld code

The problem seems to be purely persistence related (it can't find the PersistenceContext?)

Since the problem is persistence related, I've tried to change the persistence.xml however this didn't pay out. I think the problem is within the JDNI/Persistence.xml/Server config domain, however I can't be sure.

Can anybody point me in the right direction?

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary">
    <jta-data-source>jdbc/__default</jta-data-source>
    <properties>
        <!-- Properties for Hibernate (default provider for JBoss AS) -->
        <property name="hibernate.hbm2ddl.auto" value="create-drop" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="false" />
        <!-- Properties for EclipseLink (default provider for GlassFish) -->
        <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
        <property name="eclipselink.logging.level" value="FINE" />
    </properties>
</persistence-unit>
</code>```

Edit:

When I try to deploy the unchanged application to GlassFish 3.1 within Eclipse I get the following error:

```<code>cannot Deploy seam3-example
Deployment Error for module: seam3-example: Error occurred during deployment: Exception while loading the app : javax.ejb.CreateException: Initialization failed for Singleton SeedDataImporter. Please see server.log for more details.

Cannot create tables for application seam3-example. The expected DDL file seam3-example_primary_createDDL.jdbc is not available.

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.
</code>```

答:
I think it is a persistance.xml problem because you have:

```<code><jta-data-source>jdbc/__default</jta-data-source>
</code>```

and this is default for Glassfish AS

Try this:

```<code><jta-data-source>java:/DefaultDS</jta-data-source>
</code>```

This is default for JBoss

Do you run JBoss AS in default domain?

Body:
I am trying to get a basic Seam 3 webapplication to work and use the jboss-javaee6-webapp to achieve this goal. Using the manual at http://seamframework.org/Documentation/CDIQuickstartForMavenUsers.

However, I am running into some problems which I haven't been able to solve for days. I have basically no experience in JavaEE so the solution is probably really easy.

What I've done? I've simply generated a new maven project based on the supplied archetype and didn't change anything about it. I've installed Eclipse Helios including JBoss Tools and downloaded JBoss 6.0.0 and got Eclipse to deploy the application to the server succesfully.

While deploying, an exception occurs in the example code. To be specific the following exceptions occurs:

09:29:20,712 WARN  [seam3-example] Seed data import failed.: java.lang.NullPointerException
        at org.jboss.weld.integration.persistence.JBossJpaServices.resolvePersistenceContext(JBossJpaServices.java:59) [:6.0.0.Final]
    at org.jboss.weld.util.Beans.injectEEFields(Beans.java:781) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:181) [:6.0.0.Final]
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:176) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:142) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:339) [:6.0.0.Final]
    at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:67) [:6.0.0.Final]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:669) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractReceiverBean.getReceiver(AbstractReceiverBean.java:84) [:6.0.0.Final]
    at org.jboss.weld.bean.ProducerField$1.produce(ProducerField.java:134) [:6.0.0.Final]
    at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:361) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.createUnderlying(EEResourceProducerField.java:170) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.access$000(EEResourceProducerField.java:54) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField$EEResourceCallable.call(EEResourceProducerField.java:80) [:6.0.0.Final]
    at org.jboss.weld.bean.builtin.CallableMethodHandler.invoke(CallableMethodHandler.java:50) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:62) [:6.0.0.Final]
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:125) [:6.0.0.Final]
    at org.jboss.weldx.persistence.org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.persist(org$jboss$weld$bean-jboss$classloader:id="vfs:$$$Users$sander$Workspaces$eclipse$web-dev-32$$metadata$$plugins$org$jboss$ide$eclipse$as$core$JBoss_6$0_Runtime_Server1306911969901$deploy$seam3-example$war"-ProducerField-nl$jdi$examples$data$MemberRepositoryProducer$em_$$_WeldProxy.java)
    at nl.jdi.examples.data.SeedDataImporter.importData(SeedDataImporter.java:51) [:]
...

I've searched for a solution for this exact exception but I could barely find anything about it. This probably means that I've overlooked something very simple. So I've analysed the exception and found the following:

The exception message is from the example code (SeedDataImporter.java:61)

The exception itself (NullPointer) is thrown somewhere in the weld code

The problem seems to be purely persistence related (it can't find the PersistenceContext?)

Since the problem is persistence related, I've tried to change the persistence.xml however this didn't pay out. I think the problem is within the JDNI/Persistence.xml/Server config domain, however I can't be sure.

Can anybody point me in the right direction?

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary">
    <jta-data-source>jdbc/__default</jta-data-source>
    <properties>

        <property name="hibernate.hbm2ddl.auto" value="create-drop" />
        <property name="hibernate.show_sql" value="true" />
        <property name="hibernate.format_sql" value="false" />

        <property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
        <property name="eclipselink.logging.level" value="FINE" />
    </properties>
</persistence-unit>

Edit:

When I try to deploy the unchanged application to GlassFish 3.1 within Eclipse I get the following error:

cannot Deploy seam3-example
Deployment Error for module: seam3-example: Error occurred during deployment: Exception while loading the app : javax.ejb.CreateException: Initialization failed for Singleton SeedDataImporter. Please see server.log for more details.

Cannot create tables for application seam3-example. The expected DDL file seam3-example_primary_createDDL.jdbc is not available.

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.

Body:
I think it is a persistance.xml problem because you have:

<jta-data-source>jdbc/__default</jta-data-source>

and this is default for Glassfish AS

Try this:

<jta-data-source>java:/DefaultDS</jta-data-source>

This is default for JBoss

Do you run JBoss AS in default domain?


来源: stackexchange

问:
Duplicate elements in java.util.Set
java.util.Set implementations removes the duplicate elements.

How are duplicates elements deleted internally in a java.util.Set?

答:
Adds the specified element to the set if it is not already present.
If the set already contains the element, the call leaves the set unchanged and returns false.In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.</p>

ContentLicense: CC BY-SA 4.0

Title: Duplicate elements in java.util.Set


问:
Why dose my mail lose some part of the content while being sent?
My code sends an email with received values.

My code:

```<code>    self.alert = email.message.EmailMessage()
    self.alert['Subject'] = my_subject
    content1 = ''

    content2 = 'ABCDEFGHIJ1ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ'
    self.alert.set_content(content) #content1 or content2
    self.alert['From'] = my_from
    self.alert['To'] = my_to
    self.smtp.send_message(self.alert)
</code>```

(content1 is six consecutive 가나다라마.
In any reason, I cannot type it in the above code block.. The site rejects to post that. Maybe it's not English..?)

When I give content1, the mail of the receiver shows only some part of the content.

가나다라마가나다라마가나다라마가나다

On the other hand, for content2, even though the length is much longer than content1, it shows all the characters in the received email.

content1 contains Korean.

Does the language have to do with this problem?

When I do the same thing on my Mac, it sends Korean well.

But this problem happens when I use a remote server.

Any thought is appreciated :)

答: I still don't know why, but after I tried with python3.6, the issue was gone.   </p>

Body:
My code sends an email with received values.

My code:

    self.alert = email.message.EmailMessage()
    self.alert['Subject'] = my_subject
    content1 = ''

    content2 = 'ABCDEFGHIJ1ABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJABCDEFGHIJ'
    self.alert.set_content(content) #content1 or content2
    self.alert['From'] = my_from
    self.alert['To'] = my_to
    self.smtp.send_message(self.alert)

(content1 is six consecutive 가나다라마.
In any reason, I cannot type it in the above code block.. The site rejects to post that. Maybe it's not English..?)

When I give content1, the mail of the receiver shows only some part of the content.

가나다라마가나다라마가나다라마가나다

On the other hand, for content2, even though the length is much longer than content1, it shows all the characters in the received email.

content1 contains Korean.

Does the language have to do with this problem?

When I do the same thing on my Mac, it sends Korean well.

But this problem happens when I use a remote server.

Any thought is appreciated :)


问:
Compress Video files in NodeJS
I am improving the performance of my application.

I want to compress images and videos to minimum size without any quality loss i.e. lossless compression.

For images, i've used imagemin package. It works well with png format, but for jpeg, its very inefficient.

For videos, i can't find any way to minimize video size without scaling down the resolution and without any quality loss.

答: Jimp is very good for image compression and resizing Jimp

ContentLicense: CC BY-SA 3.0

Title: Compress Video files in NodeJS


问:
Problem adding std::filesystem to CMake Project
I am new to CMake projects and I want to use the file system library in my project. I am running Ubuntu 18.04 with GCC 8.2 and CMake 3.13. In order to achieve this I tried two options:

Option 1

```<code>cmake_minimum_required(VERSION 3.13)
project(TheFsProject)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-std=c++17 -lstdc++fs")
</code>```

This does not help as the compiler still cannot find the file system
library during compile time.

Option 2 (copied from:
https://www.scivision.co/cmake-cpp-17-filesystem/)

```<code>make_minimum_required(VERSION 3.13)
project(TheFsProject)

set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(CMAKE_REQUIRED_FLAGS -std=c++17)
include(CheckCXXSymbolExists)
CHECK_CXX_SYMBOL_EXISTS(std::filesystem::path::preferred_separator cxx17fs)

if(cxx17fs)
  add_executable(TheFsProject main.cpp)
  set_property(TARGET TheFsProject PROPERTY CXX_STANDARD 17)
endif()
</code>```

This does not help either as I get a CMake error which I don't
understand.

```<code>(CHECK_CXX_SYMBOL_EXISTS):
 CHECK_CXX_SYMBOL_EXISTS Macro invoked with incorrect arguments for macro named: CHECK_CXX_SYMBOL_EXISTS
</code>```

I feel out of my depth on this topic which is why I came here. I don't mind putting extra work into finding out more but I don't know anymore where to look. Any help would be appreciated!

EDIT 1

Thanks for the replies so far! I made Option 3 based on your feedback:

```<code>cmake_minimum_required(VERSION 3.13)
project(TheFsProject)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(TheFsProject main.cpp)
target_link_libraries(TheFsProject stdc++fs)
</code>```

Sadly it doesn't fix my problem. It still issues an error during compilation that it can't find the compilation header.

EDIT 2

Thanks for all the replies so far. All of these help. I tried Ashkan his answer last (because it seemed intimidating). This one returns

Compiler is missing file system capabilities.

so I'm guessing something is wrong on that end. This is useful in the sense that I now know it's probably not due to my CMake file. I now have to find out why the compiler does support the file system header though...

EDIT 3

Strictly speaking this question is answered because my question is about the CMake file. I am going to mark Ashkan his answer as the solution simply because it produced the next step in my troubleshooting search. If I could I would also mark lubgr his answer because I think that's a really good answer as well. Thanks everyone!

答:
I have found a case when try_compile was not enough: when using the Intel C++ compiler (icpc (ICC) 19.1.1.216 20200306) in C++17 mode running on MacOS "Mojave" 10.14.6. The test program recommended by @Ashkan compiled without errors, and it even ran. However, my code uses fs::path::filename() at one point and that resulted in a runtime linker error (dyld: lazy symbol binding failed: Symbol not found:). In other words: the header is there, the implementation apparently isn't (?). I didn't investigate this any further.

The solution is to use try_run instead of try_compile and (in my case) fall back to boost::filesystem if std::filesystem is not yet supported.

Here is the relevant CMake code section:

```<code>try_run(RUNS_WITH_STDFS COMPILES_WITH_STDFS
    "${CMAKE_BINARY_DIR}/try"
    "${CMAKE_SOURCE_DIR}/cmake/has_stdfs.cc"
    CMAKE_FLAGS CMAKE_CXX_STANDARD=17 CMAKE_CXX_STANDARD_REQUIRED=ON
    )
if (RUNS_WITH_STDFS STREQUAL "FAILED_TO_RUN")
    message(STATUS "Using boost::filesystem instead of std::filesystem")
    set(_boost_components ${_boost_components} filesystem system)
    add_definitions(-DUSE_BOOST_FILESYSTEM)
else()
    message(STATUS "std::filesystem supported")
endif()
</code>```

Note that the variable RUNS_WITH_STDFS is not set to NO in case of failure but to "FAILED_TO_RUN" which is not interpreted as a FALSE Boolean (see CMake if() docs:

if() True if the constant is 1, ON, YES, TRUE, Y, or a
  non-zero number. False if the constant is 0, OFF, NO, FALSE, N,
  IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.

so I had to string-compare its value.

The little test program also changed a bit compared to @Ashkan's solution:

```<code>// == PROGRAM has_stdfs.cc ==

// Check if std::filesystem is available
// Source: https://stackoverflow.com/a/54290906
// with modifications

#include <filesystem>
namespace fs = std::filesystem;

int main(int argc, char* argv[]) {
    fs::path somepath{ "dir1/dir2/filename.txt" };
    auto fname = somepath.filename();
    return 0;
}
</code>```

Body:
I am new to CMake projects and I want to use the file system library in my project. I am running Ubuntu 18.04 with GCC 8.2 and CMake 3.13. In order to achieve this I tried two options:

Option 1

cmake_minimum_required(VERSION 3.13)
project(TheFsProject)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-std=c++17 -lstdc++fs")

This does not help as the compiler still cannot find the file system
library during compile time.

Option 2 (copied from:
https://www.scivision.co/cmake-cpp-17-filesystem/)

make_minimum_required(VERSION 3.13)
project(TheFsProject)

set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(CMAKE_REQUIRED_FLAGS -std=c++17)
include(CheckCXXSymbolExists)
CHECK_CXX_SYMBOL_EXISTS(std::filesystem::path::preferred_separator cxx17fs)

if(cxx17fs)
  add_executable(TheFsProject main.cpp)
  set_property(TARGET TheFsProject PROPERTY CXX_STANDARD 17)
endif()

This does not help either as I get a CMake error which I don't
understand.

(CHECK_CXX_SYMBOL_EXISTS):
 CHECK_CXX_SYMBOL_EXISTS Macro invoked with incorrect arguments for macro named: CHECK_CXX_SYMBOL_EXISTS

I feel out of my depth on this topic which is why I came here. I don't mind putting extra work into finding out more but I don't know anymore where to look. Any help would be appreciated!

EDIT 1

Thanks for the replies so far! I made Option 3 based on your feedback:

cmake_minimum_required(VERSION 3.13)
project(TheFsProject)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(TheFsProject main.cpp)
target_link_libraries(TheFsProject stdc++fs)

Sadly it doesn't fix my problem. It still issues an error during compilation that it can't find the compilation header.

EDIT 2

Thanks for all the replies so far. All of these help. I tried Ashkan his answer last (because it seemed intimidating). This one returns

Compiler is missing file system capabilities.

so I'm guessing something is wrong on that end. This is useful in the sense that I now know it's probably not due to my CMake file. I now have to find out why the compiler does support the file system header though...

EDIT 3

Strictly speaking this question is answered because my question is about the CMake file. I am going to mark Ashkan his answer as the solution simply because it produced the next step in my troubleshooting search. If I could I would also mark lubgr his answer because I think that's a really good answer as well. Thanks everyone!

Body:
I have found a case when try_compile was not enough: when using the Intel C++ compiler (icpc (ICC) 19.1.1.216 20200306) in C++17 mode running on MacOS "Mojave" 10.14.6. The test program recommended by @Ashkan compiled without errors, and it even ran. However, my code uses fs::path::filename() at one point and that resulted in a runtime linker error (dyld: lazy symbol binding failed: Symbol not found:). In other words: the header is there, the implementation apparently isn't (?). I didn't investigate this any further.

The solution is to use try_run instead of try_compile and (in my case) fall back to boost::filesystem if std::filesystem is not yet supported.

Here is the relevant CMake code section:

try_run(RUNS_WITH_STDFS COMPILES_WITH_STDFS
    "${CMAKE_BINARY_DIR}/try"
    "${CMAKE_SOURCE_DIR}/cmake/has_stdfs.cc"
    CMAKE_FLAGS CMAKE_CXX_STANDARD=17 CMAKE_CXX_STANDARD_REQUIRED=ON
    )
if (RUNS_WITH_STDFS STREQUAL "FAILED_TO_RUN")
    message(STATUS "Using boost::filesystem instead of std::filesystem")
    set(_boost_components ${_boost_components} filesystem system)
    add_definitions(-DUSE_BOOST_FILESYSTEM)
else()
    message(STATUS "std::filesystem supported")
endif()

Note that the variable RUNS_WITH_STDFS is not set to NO in case of failure but to "FAILED_TO_RUN" which is not interpreted as a FALSE Boolean (see CMake if() docs:

if() True if the constant is 1, ON, YES, TRUE, Y, or a
  non-zero number. False if the constant is 0, OFF, NO, FALSE, N,
  IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.

so I had to string-compare its value.

The little test program also changed a bit compared to @Ashkan's solution:

// == PROGRAM has_stdfs.cc ==

// Check if std::filesystem is available
// Source: https://stackoverflow.com/a/54290906
// with modifications

#include <filesystem>
namespace fs = std::filesystem;

int main(int argc, char* argv[]) {
    fs::path somepath{ "dir1/dir2/filename.txt" };
    auto fname = somepath.filename();
    return 0;
}


问:
python string operation. sticked words separation
I have a pretty challenging problem here I need your help.

the problem is this:

I have a string for example "abcde"

Now, I want to separate this string into any possible ordered combinations as a list of strings.
for example,

```<code>my_function('abcde')

output =
[
 ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'de'],
 ['a', 'b', 'cde'],
 ['a', 'bced'],
 ['a', 'b', 'cd', 'e'],
 ['a', 'bc', 'd', 'e'],
 ['a', 'bc', 'de'],
 ['a', 'bcd', 'e'],
 ['a', 'bcde'],
 ['ab', 'c', 'd', 'e'],
 ['ab', 'c', 'de'],
 ['ab', 'cd', 'e'],
 ['ab', 'cde'],
 ['abc','d','e'],
 ['abc', 'de'],
 ['abcd', 'e'],
 ['abcde']
]
</code>```

It is not quite the permutation since the order matters.

答:
i got 16 items and you have 17 :-)</p>

```<code>    def fn(base_str):
        result = [[base_str]]
        for i in range(1, len(base_str)):
            child = fn(base_str[i:])
            for x in child:
                x.insert(0, base_str[0:i])
            result = child + result
        return result

    print(fn("abcde"))
</code>```

Body:
I have a pretty challenging problem here I need your help.

the problem is this:

I have a string for example "abcde"

Now, I want to separate this string into any possible ordered combinations as a list of strings.
for example,

my_function('abcde')

output =
[
 ['a', 'b', 'c', 'd', 'e'],
 ['a', 'b', 'c', 'de'],
 ['a', 'b', 'cde'],
 ['a', 'bced'],
 ['a', 'b', 'cd', 'e'],
 ['a', 'bc', 'd', 'e'],
 ['a', 'bc', 'de'],
 ['a', 'bcd', 'e'],
 ['a', 'bcde'],
 ['ab', 'c', 'd', 'e'],
 ['ab', 'c', 'de'],
 ['ab', 'cd', 'e'],
 ['ab', 'cde'],
 ['abc','d','e'],
 ['abc', 'de'],
 ['abcd', 'e'],
 ['abcde']
]

It is not quite the permutation since the order matters.

Body:
i got 16 items and you have 17 :-)

    def fn(base_str):
        result = [[base_str]]
        for i in range(1, len(base_str)):
            child = fn(base_str[i:])
            for x in child:
                x.insert(0, base_str[0:i])
            result = child + result
        return result

    print(fn("abcde"))


问:
iPhone Simulator - Simulate a slow connection?
Is there a way to slow down the internet connection to the iPhone Simulator, so as to mimic how the App might react when you are in a slow spot on the cellular network?</p>

答:
I would argue that a slow connection isn't enough to simulate real-work mobile data network behaviour - since there is also much more packet loss, higher latencies and more dropped connections too.

Here is a handy script I found to configure the firewall to emulate these parameters:

http://pmilosev-notes.blogspot.com/2011/02/ios-simulator-testing-over-different.html

```<code>
#!/bin/sh
if [ "$#" -ne "3" ]
then
    echo "Usage:\n$0 <bandwidth in kpbs> <delay in ms> <packet loss ratio>";
    exit 1
fi

BW=$1
DELAY=$2
PLR=$3
sudo ipfw pipe 1 config bw ${BW}Kbit/s delay $DELAY plr $PLR
sudo ipfw add 1 pipe 1 all from me to not me
sudo ipfw add 2 pipe 1 all from not me to me
echo "RETURN to stop connection noise"
read
sudo ipfw delete 1
sudo ipfw delete 2
exit 0
</code>```

Some suggested values you can use:

Scenario
Bw (Kbit)
delay (ms)
pr (ratio)

2.5G mobile
(GPRS)
50
200

3G mobile
1000
200
0.2

VSAT
5000
500
0.2

Busy LAN on VSAT
300
500
0.4

Body:
I would argue that a slow connection isn't enough to simulate real-work mobile data network behaviour - since there is also much more packet loss, higher latencies and more dropped connections too.

Here is a handy script I found to configure the firewall to emulate these parameters:

http://pmilosev-notes.blogspot.com/2011/02/ios-simulator-testing-over-different.html

#!/bin/sh
if [ "$#" -ne "3" ]
then
    echo "Usage:\n$0 <bandwidth in kpbs> <delay in ms> <packet loss ratio>";
    exit 1
fi

BW=$1
DELAY=$2
PLR=$3
sudo ipfw pipe 1 config bw ${BW}Kbit/s delay $DELAY plr $PLR
sudo ipfw add 1 pipe 1 all from me to not me
sudo ipfw add 2 pipe 1 all from not me to me
echo "RETURN to stop connection noise"
read
sudo ipfw delete 1
sudo ipfw delete 2
exit 0

Some suggested values you can use:

Scenario
Bw (Kbit)
delay (ms)
pr (ratio)

2.5G mobile
(GPRS)
50
200

3G mobile
1000
200
0.2

VSAT
5000
500
0.2

Busy LAN on VSAT
300
500
0.4


问:
I am not clear on the meaning of the best_score_ from GridSearchCV
I ran an experiment with several models and generated a best score for each of them to help me decide on the one to choose for the final model.  The best score results have been generated with the following code:

```<code>print(f'Ridge score is {np.sqrt(ridge_grid_search.best_score_ * -1)}')
print(f'Lasso score is {np.sqrt(lasso_grid_search.best_score_ * -1)}')
print(f'ElasticNet score is {np.sqrt(ElasticNet_grid_search.best_score_ * -1)}')
print(f'KRR score is {np.sqrt(KRR_grid_search.best_score_ * -1)}')
print(f'GradientBoosting score is {np.sqrt(gradientBoost_grid_search.best_score_ * -1)}')
print(f'XGBoosting score is {np.sqrt(XGB_grid_search.best_score_ * -1)}')
print(f'LGBoosting score is {np.sqrt(LGB_grid_search.best_score_ * -1)}')

</code>```

The results are posted here:

```<code>Ridge score is 0.11353489315048314
Lasso score is 0.11118171778462431
ElasticNet score is 0.11122236468840378
KRR score is 0.11322596291030147
GradientBoosting score is 0.11111049287476948
XGBoosting score is 0.11404604560959673
LGBoosting score is 0.11299104859531962

</code>```

I am not sure how to choose the best model.  Is XGBoosting my best model in this case?

答:
Your code is not provided however from the name of ridge_grid_search I suppose you are using sklearn.model_selection.GridSearchCV for model selection. GridSearch should be used to tune the hyperparameters of a single model and should not be used to compare different models with each other. ridge_grid_search.best_score_ returns the best score achieved by the best hyperparameters found during the grid search og the given algorithm.

For model comparison you should use a cross validation algorithm such as k-fold cross validation While using cross validation make sure every model is trained and tested on the same training/testing sets for fair comparison.

Body:
I ran an experiment with several models and generated a best score for each of them to help me decide on the one to choose for the final model.  The best score results have been generated with the following code:

print(f'Ridge score is {np.sqrt(ridge_grid_search.best_score_ * -1)}')
print(f'Lasso score is {np.sqrt(lasso_grid_search.best_score_ * -1)}')
print(f'ElasticNet score is {np.sqrt(ElasticNet_grid_search.best_score_ * -1)}')
print(f'KRR score is {np.sqrt(KRR_grid_search.best_score_ * -1)}')
print(f'GradientBoosting score is {np.sqrt(gradientBoost_grid_search.best_score_ * -1)}')
print(f'XGBoosting score is {np.sqrt(XGB_grid_search.best_score_ * -1)}')
print(f'LGBoosting score is {np.sqrt(LGB_grid_search.best_score_ * -1)}')

The results are posted here:

Ridge score is 0.11353489315048314
Lasso score is 0.11118171778462431
ElasticNet score is 0.11122236468840378
KRR score is 0.11322596291030147
GradientBoosting score is 0.11111049287476948
XGBoosting score is 0.11404604560959673
LGBoosting score is 0.11299104859531962

I am not sure how to choose the best model.  Is XGBoosting my best model in this case?


问:
Create WCF MSI Install Package with Advanced Installer Extension
I was asked to work on a WCF project that was created in Visual Studio 2013. I didn't have VS 2013 installed, so I used VS2019. I have to create an installer to allow QA to install the service. I found  and read about VS2019 Advanced Installer Extension. I created the MSI file. During my testing, it went through the install process successfully and copied the files to the appropriate directory. However, the service did not appear under the service window after installing. I clicked on "Add Project Output" and added a primary output and selected all other dependencies that are related to the projects. That did not solve the issue. I've read online that a custom action can be created, but there was no clear instructions or steps on how to create a custom action. Has anyone able to create and install a WCF service with Advanced Installer Extension? Am I missing a something?</p>

答:
Advanced Installer offers predefined support to install services, there is no need to go with a custom action. For details, please check the How to install a service article.

By default, the VS Extension will create a project of Simple type. To have access to Services feature you need to upgrade the project to Professional from the project options.

Since you mention custom action approach, if you need to integrate C# custom actions in the installer, check the How to integrate and debug custom actions artticle. You can debug your C# custom actions by attaching on the installation process from Visual Studio. Or, if you prefer Powershell custom action approach.


问:
NumPy array is not JSON serializable
After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:

```<code>array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) is not JSON serializable
</code>```

What does this mean?

答:
use NumpyEncoder it will process json dump successfully.without throwing - NumPy array is not JSON serializable</p>

```<code>import numpy as np
import json
from numpyencoder import NumpyEncoder
arr = array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64)
json.dumps(arr,cls=NumpyEncoder)
</code>```

Title: NumPy array is not JSON serializable

Body:
After creating a NumPy array, and saving it as a Django context variable, I receive the following error when loading the webpage:

array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64) is not JSON serializable

What does this mean?

Body:
use NumpyEncoder it will process json dump successfully.without throwing - NumPy array is not JSON serializable

import numpy as np
import json
from numpyencoder import NumpyEncoder
arr = array([   0,  239,  479,  717,  952, 1192, 1432, 1667], dtype=int64)
json.dumps(arr,cls=NumpyEncoder)


问:
vanilla javascript to Reactjs component?
I have a little vanilla javascript code, and am hoping to convert it into a React component. I really dont know where to begin, and I have a few questions that seem be very simple.

First, how do i even get started converting this to React? Do i place all of these variables in the constructor, or in the render (before the return) Is all of this inline styling sufficient, without any external CSS?

This is the class (d3-based KMeans clustering visualization):

```<code>var flag = false;
var WIDTH = d3.select("#kmeans")[0][0].offsetWidth - 20;
var HEIGHT = Math.max(300, WIDTH * .7);
var svg = d3.select("#kmeans svg")
  .attr('width', WIDTH)
  .attr('height', HEIGHT)
  .style('padding', '10px')
  .style('background', '#223344')
  .style('cursor', 'pointer')
  .style('-webkit-user-select', 'none')
  .style('-khtml-user-select', 'none')
  .style('-moz-user-select', 'none')
  .style('-ms-user-select', 'none')
  .style('user-select', 'none')
  .on('click', function() {
    d3.event.preventDefault();
    step();
  });

d3.selectAll("#kmeans button")
  .style('padding', '.5em .8em');

d3.selectAll("#kmeans label")
  .style('display', 'inline-block')
  .style('width', '15em');

var lineg = svg.append('g');
var dotg = svg.append('g');
var centerg = svg.append('g');
d3.select("#step")
  .on('click', function() { step(); draw(); });
d3.select("#restart")
  .on('click', function() { restart(); draw(); });
d3.select("#reset")
  .on('click', function() { init(); draw(); });

var groups = [], dots = [];

function step() {
  d3.select("#restart").attr("disabled", null);
  if (flag) {
    moveCenter();
    draw();
  } else {
    updateGroups();
    draw();
  }
  flag = !flag;
}

function init() {
  d3.select("#restart").attr("disabled", "disabled");

  //var N = parseInt(d3.select('#N')[0][0].value, 10);
 //var K = parseInt(d3.select('#K')[0][0].value, 10);
 var N = 700;
 var K = 9;

  groups = [];
  for (var i = 0; i < K; i++) {
    var g = {
      dots: [],
      color: 'hsl(' + (i * 360 / K) + ',100%,50%)',
      center: {
        x: Math.random() * WIDTH,
        y: Math.random() * HEIGHT
      },
      init: {
        center: {}
      }
    };
    g.init.center = {
      x: g.center.x,
      y: g.center.y
    };
    groups.push(g);
  }

  dots = [];
  flag = false;
  for (i = 0; i < N; i++) {
    var dot ={
      x: Math.random() * WIDTH,
      y: Math.random() * HEIGHT,
      group: undefined
    };
    dot.init = {
      x: dot.x,
      y: dot.y,
      group: dot.group
    };
    dots.push(dot);
  }
}

function restart() {
  flag = false;
  d3.select("#restart").attr("disabled", "disabled");

  groups.forEach(function(g) {
    g.dots = [];
    g.center.x = g.init.center.x;
    g.center.y = g.init.center.y;
  });

  for (var i = 0; i < dots.length; i++) {
    var dot = dots[i];
    dots[i] = {
      x: dot.init.x,
      y: dot.init.y,
      group: undefined,
      init: dot.init
    };
  }
}

function draw() {
  var circles = dotg.selectAll('circle')
    .data(dots);
  circles.enter()
    .append('circle');
  circles.exit().remove();
  circles
    .transition()
    .duration(500)
    .attr('cx', function(d) { return d.x; })
    .attr('cy', function(d) { return d.y; })
    .attr('fill', function(d) { return d.group ? d.group.color : '#ffffff'; })
    .attr('r', 5);

  if (dots[0].group) {
    var l = lineg.selectAll('line')
      .data(dots);
    var updateLine = function(lines) {
      lines
        .attr('x1', function(d) { return d.x; })
        .attr('y1', function(d) { return d.y; })
        .attr('x2', function(d) { return d.group.center.x; })
        .attr('y2', function(d) { return d.group.center.y; })
        .attr('stroke', function(d) { return d.group.color; });
    };
    updateLine(l.enter().append('line'));
    updateLine(l.transition().duration(500));
    l.exit().remove();
  } else {
    lineg.selectAll('line').remove();
  }

  var c = centerg.selectAll('path')
    .data(groups);
  var updateCenters = function(centers) {
    centers
      .attr('transform', function(d) { return "translate(" + d.center.x + "," + d.center.y + ") rotate(45)";})
      .attr('fill', function(d,i) { return d.color; })
      .attr('stroke', '#aabbcc');
  };
  c.exit().remove();
  updateCenters(c.enter()
    .append('path')
    .attr('d', d3.svg.symbol().type('cross'))
    .attr('stroke', '#aabbcc'));
  updateCenters(c
    .transition()
    .duration(500));}

function moveCenter() {
  groups.forEach(function(group, i) {
    if (group.dots.length == 0) return;

    // get center of gravity
    var x = 0, y = 0;
    group.dots.forEach(function(dot) {
      x += dot.x;
      y += dot.y;
    });

    group.center = {
      x: x / group.dots.length,
      y: y / group.dots.length
    };
  });

}

function updateGroups() {
  groups.forEach(function(g) { g.dots = []; });
  dots.forEach(function(dot) {
    // find the nearest group
    var min = Infinity;
    var group;
    groups.forEach(function(g) {
      var d = Math.pow(g.center.x - dot.x, 2) + Math.pow(g.center.y - dot.y, 2);
      if (d < min) {
        min = d;
        group = g;
      }
    });

    // update group
    group.dots.push(dot);
    dot.group = group;
  });
}

init(); draw();

</code>```

Any help in understanding (or or course providing converted code) would be so helpful.

答:
If you're beginning from scratch, set up a boiler plate.For e.g create-react-app

Install d3 library in this project

Create a component for this and import and render that component in your app.js

Make these variables as part of the state of the component and method inside the component as class methods

Body:
I have a little vanilla javascript code, and am hoping to convert it into a React component. I really dont know where to begin, and I have a few questions that seem be very simple.

First, how do i even get started converting this to React? Do i place all of these variables in the constructor, or in the render (before the return) Is all of this inline styling sufficient, without any external CSS?

This is the class (d3-based KMeans clustering visualization):

var flag = false;
var WIDTH = d3.select("#kmeans")[0][0].offsetWidth - 20;
var HEIGHT = Math.max(300, WIDTH * .7);
var svg = d3.select("#kmeans svg")
  .attr('width', WIDTH)
  .attr('height', HEIGHT)
  .style('padding', '10px')
  .style('background', '#223344')
  .style('cursor', 'pointer')
  .style('-webkit-user-select', 'none')
  .style('-khtml-user-select', 'none')
  .style('-moz-user-select', 'none')
  .style('-ms-user-select', 'none')
  .style('user-select', 'none')
  .on('click', function() {
    d3.event.preventDefault();
    step();
  });

d3.selectAll("#kmeans button")
  .style('padding', '.5em .8em');

d3.selectAll("#kmeans label")
  .style('display', 'inline-block')
  .style('width', '15em');

var lineg = svg.append('g');
var dotg = svg.append('g');
var centerg = svg.append('g');
d3.select("#step")
  .on('click', function() { step(); draw(); });
d3.select("#restart")
  .on('click', function() { restart(); draw(); });
d3.select("#reset")
  .on('click', function() { init(); draw(); });

var groups = [], dots = [];

function step() {
  d3.select("#restart").attr("disabled", null);
  if (flag) {
    moveCenter();
    draw();
  } else {
    updateGroups();
    draw();
  }
  flag = !flag;
}

function init() {
  d3.select("#restart").attr("disabled", "disabled");

  //var N = parseInt(d3.select('#N')[0][0].value, 10);
 //var K = parseInt(d3.select('#K')[0][0].value, 10);
 var N = 700;
 var K = 9;

  groups = [];
  for (var i = 0; i < K; i++) {
    var g = {
      dots: [],
      color: 'hsl(' + (i * 360 / K) + ',100%,50%)',
      center: {
        x: Math.random() * WIDTH,
        y: Math.random() * HEIGHT
      },
      init: {
        center: {}
      }
    };
    g.init.center = {
      x: g.center.x,
      y: g.center.y
    };
    groups.push(g);
  }

  dots = [];
  flag = false;
  for (i = 0; i < N; i++) {
    var dot ={
      x: Math.random() * WIDTH,
      y: Math.random() * HEIGHT,
      group: undefined
    };
    dot.init = {
      x: dot.x,
      y: dot.y,
      group: dot.group
    };
    dots.push(dot);
  }
}

function restart() {
  flag = false;
  d3.select("#restart").attr("disabled", "disabled");

  groups.forEach(function(g) {
    g.dots = [];
    g.center.x = g.init.center.x;
    g.center.y = g.init.center.y;
  });

  for (var i = 0; i < dots.length; i++) {
    var dot = dots[i];
    dots[i] = {
      x: dot.init.x,
      y: dot.init.y,
      group: undefined,
      init: dot.init
    };
  }
}

function draw() {
  var circles = dotg.selectAll('circle')
    .data(dots);
  circles.enter()
    .append('circle');
  circles.exit().remove();
  circles
    .transition()
    .duration(500)
    .attr('cx', function(d) { return d.x; })
    .attr('cy', function(d) { return d.y; })
    .attr('fill', function(d) { return d.group ? d.group.color : '#ffffff'; })
    .attr('r', 5);

  if (dots[0].group) {
    var l = lineg.selectAll('line')
      .data(dots);
    var updateLine = function(lines) {
      lines
        .attr('x1', function(d) { return d.x; })
        .attr('y1', function(d) { return d.y; })
        .attr('x2', function(d) { return d.group.center.x; })
        .attr('y2', function(d) { return d.group.center.y; })
        .attr('stroke', function(d) { return d.group.color; });
    };
    updateLine(l.enter().append('line'));
    updateLine(l.transition().duration(500));
    l.exit().remove();
  } else {
    lineg.selectAll('line').remove();
  }

  var c = centerg.selectAll('path')
    .data(groups);
  var updateCenters = function(centers) {
    centers
      .attr('transform', function(d) { return "translate(" + d.center.x + "," + d.center.y + ") rotate(45)";})
      .attr('fill', function(d,i) { return d.color; })
      .attr('stroke', '#aabbcc');
  };
  c.exit().remove();
  updateCenters(c.enter()
    .append('path')
    .attr('d', d3.svg.symbol().type('cross'))
    .attr('stroke', '#aabbcc'));
  updateCenters(c
    .transition()
    .duration(500));}

function moveCenter() {
  groups.forEach(function(group, i) {
    if (group.dots.length == 0) return;

    // get center of gravity
    var x = 0, y = 0;
    group.dots.forEach(function(dot) {
      x += dot.x;
      y += dot.y;
    });

    group.center = {
      x: x / group.dots.length,
      y: y / group.dots.length
    };
  });

}

function updateGroups() {
  groups.forEach(function(g) { g.dots = []; });
  dots.forEach(function(dot) {
    // find the nearest group
    var min = Infinity;
    var group;
    groups.forEach(function(g) {
      var d = Math.pow(g.center.x - dot.x, 2) + Math.pow(g.center.y - dot.y, 2);
      if (d < min) {
        min = d;
        group = g;
      }
    });

    // update group
    group.dots.push(dot);
    dot.group = group;
  });
}

init(); draw();

Any help in understanding (or or course providing converted code) would be so helpful.


问:
HTTP status code for "no data available" from an external datasource
Scenario:

A POST request is sent to process an order that will result in data retrieval from an external datasource.

There are three possible results:

The datasource returned data for the request

No data was available for the request (this is viewed as an error)

The datasource couldn't be accessed (may be down for maintenance)

An obvious response for 1 is 200: OK or 201: Created (an entity is created from this request).

What status codes would be appropriate for 2 and 3?

Status codes I have considered:

503: Service Unavailable when datasource is down

500: Internal Server Error when datasource is down

502: Bad Gateway when "no data available"

404: Not Found when "no data available"

403: Forbidden when "no data available"

412: Precondition Failed when "no data available"

答:
In my opinion the best way to handle this is with a 200 no result object.

Why?

You have a response that you can do something with without a lot of trouble. I searched, everything worked correctly but there wasn't anything in the database to give a result. Therefore, result = null and a message explaining as much. If something found this in the network calls it is not a security risk.

If you are concerned with a security risk then a 204 is probably the best approach.

res.status(200).send({
   result: null,
   message: 'No result'
});
```


问:
How do you have unique ListView elements in Xamarin, while also using RecycleElement?
Outline of functionality: I have a ListView that uses RecycleElements in Xamarin. The ListView is made up of large images, with a little heart ImageButton on top of each item. When the heart is clicked to favourite the image, it turns from white to red.

Problem: When I click a heart inside item 0 and then scroll down, item 4 will also have a red heart - which should not happen. This is due to the ListView using RecycleElements.

What I need: The heart ImageButton must be unique for each item in the list, while also allowing me to keep RecycleElements as the CachingStrategy to improve performance. The heart needs to unique as it shouldn't show every 5th item in the list as being favourited.

Is there a way of having the ImageButton be unique, while also being able to use RecycleElements? Or is there a work-around that would allow something like this? I haven't been able to come up with a solution.

XAML:

```<code><ListView x:Name="MealsListView" VerticalOptions="FillAndExpand" ItemsSource="{Binding Meals}" ItemTapped="OnMealItemClicked"
                  CachingStrategy="RecycleElement" SeparatorVisibility="None"  HasUnevenRows="True" Grid.Row="0">

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>

                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>

                            <StackLayout Margin="15,10,15,30" Grid.Row="0" Grid.RowSpan="5" Grid.ColumnSpan="2">
                                <Frame CornerRadius="5" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"
                                       HeightRequest="500" WidthRequest="1000" Padding="0" IsClippedToBounds="True">
                                    <Image Source="{Binding ImageUrl}" Aspect="AspectFill"></Image>
                                </Frame>
                            </StackLayout>

                            <ImageButton ClassId="HeartButton" Clicked="OnHeartClicked" Source="heartWhite_64x64.png" VerticalOptions="Start" HorizontalOptions="Center"
                                   HeightRequest="40" WidthRequest="40" Margin="310,-50,0,0" Grid.Row="1" Grid.Column="0" Grid.RowSpan="2" Grid.ColumnSpan="2"/>

                            <Label Text="{Binding Name}" TextColor="Black" FontSize="Medium" FontAttributes="Bold" HorizontalTextAlignment="Start"
                                   Margin="15,-30,15,40" Grid.Column="0" Grid.Row="5"/>

                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

C#:

```<code>private void OnHeartClicked(object sender, System.EventArgs e)
        {
            // change enabled state
            m_enableHeart = (m_enableHeart == true) ? false : true;
            ImageButton heartImage = (ImageButton)sender;

            // change heart colour
            if (m_enableHeart)
            {
                // show red heart
                heartImage.Source = ImageSource.FromFile("heartRed_64x64.png");
            }
            else
            {
                // show white heart
                heartImage.Source = ImageSource.FromFile("heartWhite_64x64.png");
            }
        }
</code>```

答:
Do you want to achieve the result like following GIF?

I use two images to make a test. Add a I add a Isfavourite property in model, If the Isfavourite is true I set the Image to hamburger ， if the Isfavourite is false I set the Image to  Clover. In the  Layout.xaml I use Command to achieve it in ImageButton, here is ImageButton code.

```<code><ImageButton Source="{Binding Image}"
             Command="{Binding BindingContext.ChangeImage, Source={x:Reference Name=mylistview} }"
             CommandParameter="{Binding .}"
                               Aspect="AspectFill"
                               HeightRequest="150"
                               WidthRequest="150"
                               HorizontalOptions="Center"  />
</code>```

Here is my layout code.

```<code>   <ListView x:Name="mylistview" ItemsSource="{Binding persons}"   CachingStrategy="RecycleElement" SeparatorVisibility="None"  HasUnevenRows="True" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell >
                        <StackLayout>
                            <Frame HasShadow="True"
                                   BorderColor="DarkGray"
                                   CornerRadius="5"
                                   Margin="20"
                                   HeightRequest="300"
                                   HorizontalOptions="Center"
                                   VerticalOptions="CenterAndExpand" >
                                <StackLayout>
                                    <Label Text="{Binding Name}"
                               FontAttributes="Bold"
                               FontSize="Large"
                               HorizontalOptions="Center"
                               VerticalOptions="Center" />
                                    <ImageButton Source="{Binding Image}" Command="{Binding BindingContext.ChangeImage, Source={x:Reference Name=mylistview} }"  CommandParameter="{Binding .}"
                               Aspect="AspectFill"
                               HeightRequest="150"
                               WidthRequest="150"
                               HorizontalOptions="Center"  />

                                </StackLayout>
                            </Frame>

                        </StackLayout>

                    </ViewCell>
                </DataTemplate>

            </ListView.ItemTemplate>
          </ListView>
</code>```

Here is layout background code.

```<code> public partial class MainPage : ContentPage
    {

        public MainPage()
        {
           InitializeComponent();

            this.BindingContext= new PersonsViewModel(Navigation);

        }
    }
}
</code>```

Here is viewModel code.

```<code>  public class PersonsViewModel
    {

        public ObservableCollection<Person> persons { get; set; }

        public ICommand ChangeImage { protected set; get; }

        public PersonsViewModel(INavigation navigation)
        {

            persons = new ObservableCollection<Person>();
            persons.Add(new Person() { Name=  "Leon1" ,Image= "Clover.png", Count=1 , Isfavourite=false});
            persons.Add(new Person() { Name = "Leon2", Image = "Clover.png", Count = 2 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon3", Image = "Clover.png", Count = 3 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon4", Image = "Clover.png", Count = 4 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon5", Image = "Clover.png", Count = 5, Isfavourite = false });
            persons.Add(new Person() { Name = "Leon6", Image = "Clover.png", Count = 6 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon7", Image = "Clover.png", Count = 7, Isfavourite = false });
            persons.Add(new Person() { Name = "Leon8", Image = "Clover.png", Count = 8 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon9", Image = "Clover.png", Count = 9 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon10", Image = "Clover.png", Count = 10 , Isfavourite = false });

            ChangeImage = new Command<Person>((key) =>
            {
                var person = key as Person;

                 person.Isfavourite = !person.Isfavourite;

           //    m_enableHeart = (m_enableHeart == true) ? false : true;

                if (person.Isfavourite)
                {
                    // show red heart
                    person.Image = "icon.png";
                }
                else
                {
                    // show white heart
                    person.Image = "Clover.png";
                }

            });

        }
    }
}
</code>```

Here is my model code.

```<code>    public class Person: INotifyPropertyChanged
    {

        bool _isfavourite = false;
        public bool Isfavourite
        {
            get
            {
                return _isfavourite;
            }

            set
            {
                if (_isfavourite != value)
                {
                    _isfavourite = value;
                    OnPropertyChanged("Isfavourite");

                }
            }

        }

        bool _changed =false;
        public bool Changed {
            get {
                return _changed;
            }

            set
            {
                if (_changed != value)
                {
                    _changed = value;
                    OnPropertyChanged("Changed");

                }
            }

        }

        public int Count { get; set; }
        string name;
        public string Name
        {
            set
            {
                if (name != value)
                {
                    name = value;
                    OnPropertyChanged("Name");

                }
            }
            get
            {
                return name;
            }
        }

        string image;
        public string Image
        {
            set
            {
                if (image != value)
                {
                    image = value;
                    OnPropertyChanged("Image");

                }
            }
            get
            {
                return image;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}
</code>```

Body:
Outline of functionality: I have a ListView that uses RecycleElements in Xamarin. The ListView is made up of large images, with a little heart ImageButton on top of each item. When the heart is clicked to favourite the image, it turns from white to red.

Problem: When I click a heart inside item 0 and then scroll down, item 4 will also have a red heart - which should not happen. This is due to the ListView using RecycleElements.

What I need: The heart ImageButton must be unique for each item in the list, while also allowing me to keep RecycleElements as the CachingStrategy to improve performance. The heart needs to unique as it shouldn't show every 5th item in the list as being favourited.

Is there a way of having the ImageButton be unique, while also being able to use RecycleElements? Or is there a work-around that would allow something like this? I haven't been able to come up with a solution.

XAML:

<ListView x:Name="MealsListView" VerticalOptions="FillAndExpand" ItemsSource="{Binding Meals}" ItemTapped="OnMealItemClicked"
                  CachingStrategy="RecycleElement" SeparatorVisibility="None"  HasUnevenRows="True" Grid.Row="0">

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>

                            <Grid.RowDefinitions>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>

                            <StackLayout Margin="15,10,15,30" Grid.Row="0" Grid.RowSpan="5" Grid.ColumnSpan="2">
                                <Frame CornerRadius="5" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand"
                                       HeightRequest="500" WidthRequest="1000" Padding="0" IsClippedToBounds="True">
                                    <Image Source="{Binding ImageUrl}" Aspect="AspectFill"></Image>
                                </Frame>
                            </StackLayout>

                            <ImageButton ClassId="HeartButton" Clicked="OnHeartClicked" Source="heartWhite_64x64.png" VerticalOptions="Start" HorizontalOptions="Center"
                                   HeightRequest="40" WidthRequest="40" Margin="310,-50,0,0" Grid.Row="1" Grid.Column="0" Grid.RowSpan="2" Grid.ColumnSpan="2"/>

                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

C#:

private void OnHeartClicked(object sender, System.EventArgs e)
        {
            // change enabled state
            m_enableHeart = (m_enableHeart == true) ? false : true;
            ImageButton heartImage = (ImageButton)sender;

            // change heart colour
            if (m_enableHeart)
            {
                // show red heart
                heartImage.Source = ImageSource.FromFile("heartRed_64x64.png");
            }
            else
            {
                // show white heart
                heartImage.Source = ImageSource.FromFile("heartWhite_64x64.png");
            }
        }

Body:
Do you want to achieve the result like following GIF?

I use two images to make a test. Add a I add a Isfavourite property in model, If the Isfavourite is true I set the Image to hamburger ， if the Isfavourite is false I set the Image to  Clover. In the  Layout.xaml I use Command to achieve it in ImageButton, here is ImageButton code.

<ImageButton Source="{Binding Image}"
             Command="{Binding BindingContext.ChangeImage, Source={x:Reference Name=mylistview} }"
             CommandParameter="{Binding .}"
                               Aspect="AspectFill"
                               HeightRequest="150"
                               WidthRequest="150"
                               HorizontalOptions="Center"  />

Here is my layout code.

   <ListView x:Name="mylistview" ItemsSource="{Binding persons}"   CachingStrategy="RecycleElement" SeparatorVisibility="None"  HasUnevenRows="True" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell >
                        <StackLayout>
                            <Frame HasShadow="True"
                                   BorderColor="DarkGray"
                                   CornerRadius="5"
                                   Margin="20"
                                   HeightRequest="300"
                                   HorizontalOptions="Center"
                                   VerticalOptions="CenterAndExpand" >
                                <StackLayout>
                                    <Label Text="{Binding Name}"
                               FontAttributes="Bold"
                               FontSize="Large"
                               HorizontalOptions="Center"
                               VerticalOptions="Center" />
                                    <ImageButton Source="{Binding Image}" Command="{Binding BindingContext.ChangeImage, Source={x:Reference Name=mylistview} }"  CommandParameter="{Binding .}"
                               Aspect="AspectFill"
                               HeightRequest="150"
                               WidthRequest="150"
                               HorizontalOptions="Center"  />

                                </StackLayout>
                            </Frame>

                        </StackLayout>

                    </ViewCell>
                </DataTemplate>

            </ListView.ItemTemplate>
          </ListView>

Here is layout background code.

 public partial class MainPage : ContentPage
    {

        public MainPage()
        {
           InitializeComponent();

            this.BindingContext= new PersonsViewModel(Navigation);

        }
    }
}

Here is viewModel code.

  public class PersonsViewModel
    {

        public ObservableCollection<Person> persons { get; set; }

        public ICommand ChangeImage { protected set; get; }

        public PersonsViewModel(INavigation navigation)
        {

            persons = new ObservableCollection<Person>();
            persons.Add(new Person() { Name=  "Leon1" ,Image= "Clover.png", Count=1 , Isfavourite=false});
            persons.Add(new Person() { Name = "Leon2", Image = "Clover.png", Count = 2 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon3", Image = "Clover.png", Count = 3 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon4", Image = "Clover.png", Count = 4 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon5", Image = "Clover.png", Count = 5, Isfavourite = false });
            persons.Add(new Person() { Name = "Leon6", Image = "Clover.png", Count = 6 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon7", Image = "Clover.png", Count = 7, Isfavourite = false });
            persons.Add(new Person() { Name = "Leon8", Image = "Clover.png", Count = 8 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon9", Image = "Clover.png", Count = 9 , Isfavourite = false });
            persons.Add(new Person() { Name = "Leon10", Image = "Clover.png", Count = 10 , Isfavourite = false });

            ChangeImage = new Command<Person>((key) =>
            {
                var person = key as Person;

                 person.Isfavourite = !person.Isfavourite;

           //    m_enableHeart = (m_enableHeart == true) ? false : true;

                if (person.Isfavourite)
                {
                    // show red heart
                    person.Image = "icon.png";
                }
                else
                {
                    // show white heart
                    person.Image = "Clover.png";
                }

            });

        }
    }
}

Here is my model code.

    public class Person: INotifyPropertyChanged
    {

        bool _isfavourite = false;
        public bool Isfavourite
        {
            get
            {
                return _isfavourite;
            }

            set
            {
                if (_isfavourite != value)
                {
                    _isfavourite = value;
                    OnPropertyChanged("Isfavourite");

                }
            }

        }

        bool _changed =false;
        public bool Changed {
            get {
                return _changed;
            }

            set
            {
                if (_changed != value)
                {
                    _changed = value;
                    OnPropertyChanged("Changed");

                }
            }

        }

        public int Count { get; set; }
        string name;
        public string Name
        {
            set
            {
                if (name != value)
                {
                    name = value;
                    OnPropertyChanged("Name");

                }
            }
            get
            {
                return name;
            }
        }

        string image;
        public string Image
        {
            set
            {
                if (image != value)
                {
                    image = value;
                    OnPropertyChanged("Image");

                }
            }
            get
            {
                return image;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }
}


问:
Android LayoutPosition is -1 causing OutOfBoundsException
I've created an app that has a list of cards within a RecyclerView that each have functionality of their own. I wanted to have each card choose the next color from an array defined in my colors.xml. In order to accomplish this, within my ViewHolder initialization, I set the background color of the card using cardContainer.setBackgroundColor(colors[this.layoutPosition % colors.size]. This would make it so that the colors would be cycled when more cards are created. However, I seem to be encountering the issue where my layout position is negative despite there being a set number of cards (25) created at the beginning.

While trying to search around and find the cause, I read here that if you call notifyDataSetChanged() the adapterPosition will become -1. While I am not using adapterPosition here, I thought that maybe it would be a similar issue, however, I am not adding any additional data at the time of the creation of the list items.

My ViewHolder code can be seen below. This is where the issue arises, but if any additional code is necessary feel free to ask.

```<code>    class ViewHolder(itemView : View, private val listener: HabitClickListener) : RecyclerView.ViewHolder(itemView) {
        val habitTitle: TextView = itemView.habitTitle
        val streak: TextView = itemView.dayCounter
        val cardContainer: LinearLayout = itemView.cardContainer

        private val decreaseCounterButton : Button = itemView.decreaseCounterButton
        private val increaseCounterButton : Button = itemView.increaseCounterButton

        init {
            chooseCardColor() // Choose the color for each card from the available colors
            itemView.setOnClickListener {
                listener.onCardClick(this.layoutPosition)
            }
            decreaseCounterButton.setOnClickListener {
                listener.onDecrease(this.layoutPosition)
            }
            increaseCounterButton.setOnClickListener {
                listener.onIncrease(this.layoutPosition)
            }
        }

        private fun chooseCardColor() {
            val colors = itemView.resources.getIntArray(R.array.cardColors)
            cardContainer.setBackgroundColor(colors[this.layoutPosition % colors.size])
        }
    }
</code>```

答:
I will try to simplify this further, you should  use the getAdapterPosition of ViewHolder

In recyclerview, storing the data and displaying the data are two separate things(Notice how you can use different managers(LinearLayoutManager, GridLayoutManager) to present the data in a different way.When some data changes in recyclerview, it notifies the ui to change what is shown in the screen. Even though it is really small, there is a delay between the change in the content of recyclerview and change in layout, that's why these two behave differently.

My information in this may be outdated but also don't just use the position variable as it can be inconsistent when another element is added/deleted to recyclerview due to how onBindViewHolder()(existing variables position wasn't updated when a new element is added/deleted) behaves. Instead use getAdapterPosition().

Edit: Quick fix if you don't want to deal with viewHolder gimmicks.

Add a new field to your custom object which decides what color it should be. Then make this calculation in your fragment/activity by looking at the index of your object in the list instead of doing the calculation in the viewHolder. Now you can set the color you want inside the viewHolderby looking at your object's new field. Of course you should be careful when adding/deleting a new object when you do this, but same holds true when you do it via viewHolder

Body:
I've created an app that has a list of cards within a RecyclerView that each have functionality of their own. I wanted to have each card choose the next color from an array defined in my colors.xml. In order to accomplish this, within my ViewHolder initialization, I set the background color of the card using cardContainer.setBackgroundColor(colors[this.layoutPosition % colors.size]. This would make it so that the colors would be cycled when more cards are created. However, I seem to be encountering the issue where my layout position is negative despite there being a set number of cards (25) created at the beginning.

While trying to search around and find the cause, I read here that if you call notifyDataSetChanged() the adapterPosition will become -1. While I am not using adapterPosition here, I thought that maybe it would be a similar issue, however, I am not adding any additional data at the time of the creation of the list items.

My ViewHolder code can be seen below. This is where the issue arises, but if any additional code is necessary feel free to ask.

    class ViewHolder(itemView : View, private val listener: HabitClickListener) : RecyclerView.ViewHolder(itemView) {
        val habitTitle: TextView = itemView.habitTitle
        val streak: TextView = itemView.dayCounter
        val cardContainer: LinearLayout = itemView.cardContainer

        private val decreaseCounterButton : Button = itemView.decreaseCounterButton
        private val increaseCounterButton : Button = itemView.increaseCounterButton

        init {
            chooseCardColor() // Choose the color for each card from the available colors
            itemView.setOnClickListener {
                listener.onCardClick(this.layoutPosition)
            }
            decreaseCounterButton.setOnClickListener {
                listener.onDecrease(this.layoutPosition)
            }
            increaseCounterButton.setOnClickListener {
                listener.onIncrease(this.layoutPosition)
            }
        }

        private fun chooseCardColor() {
            val colors = itemView.resources.getIntArray(R.array.cardColors)
            cardContainer.setBackgroundColor(colors[this.layoutPosition % colors.size])
        }
    }


问:
Wait for a (web) server to start before running another program in Inno Setup [Run] section
My Inno Setup installer contains a small webserver and a desktop application. Both of these are standalone executables. On installation I want to start a the webserver so that it is up an running before starting up the desktop app. I'm trying to achieve this in the [Run] section of my Inno Setup script as follows:

```<code>[Run]
Filename: "{app}\Server\{#ServerExeName}"; \
    Description: "{cm:LaunchProgram,{#StringChange(ServerName, '&', '&&')}}"; \
    Flags: waituntilidle runascurrentuser
Filename: "{app}\App\{#AppExeName}"; \
    Description: "{cm:LaunchProgram,{#StringChange(AppName, '&', '&&')}}"; \
    Flags: nowait postinstall
</code>```

This does not work in the sense that the installer does not finish properly, os hangs waiting for the server (ServerExeName). I guess it is waiting for the server to go into an idle state which does not happen. (Same thing goes for the 'waituntilterminated' flag since the server will and shall not terminate). What is the preferred Inno Setup way of making  sure the server has started before continuing (starting the other application)?

I'm running Inno Setup 5.6.1u, but I can upgrade if needed. The web server is CherryPy web server bundled to an exe using PyInstaller. The application is custom made wxWidgets based GUI.

答:
waituntilidle is very specific thing. It internally uses WaitForInputIdle WinAPI function. Read more about it to understand, when it can be used.

If it does not fit your server application, you will have to implement some sort of signal in it, that Inno Setup can look for. On *nix systems, a pidfile is commonly used for this purpose. Or use a mutex or other similar mechanism.

Even easier might be to add a function/switch to your application (not the server) that will make it wait until the server is running.

Body:
My Inno Setup installer contains a small webserver and a desktop application. Both of these are standalone executables. On installation I want to start a the webserver so that it is up an running before starting up the desktop app. I'm trying to achieve this in the [Run] section of my Inno Setup script as follows:

[Run]
Filename: "{app}\Server\{#ServerExeName}"; \
    Description: "{cm:LaunchProgram,{#StringChange(ServerName, '&', '&&')}}"; \
    Flags: waituntilidle runascurrentuser
Filename: "{app}\App\{#AppExeName}"; \
    Description: "{cm:LaunchProgram,{#StringChange(AppName, '&', '&&')}}"; \
    Flags: nowait postinstall

This does not work in the sense that the installer does not finish properly, os hangs waiting for the server (ServerExeName). I guess it is waiting for the server to go into an idle state which does not happen. (Same thing goes for the 'waituntilterminated' flag since the server will and shall not terminate). What is the preferred Inno Setup way of making  sure the server has started before continuing (starting the other application)?

I'm running Inno Setup 5.6.1u, but I can upgrade if needed. The web server is CherryPy web server bundled to an exe using PyInstaller. The application is custom made wxWidgets based GUI.


问:
What happened when invoking locals() in python3?
I'm using Python3.7.2

The code which makes me confused looks like this:

```<code>def foo(cond):
    if cond:
        z = 1
        return z
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)
</code>```

Here is the result it prints:

```<code>{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2}
</code>```

The exec function changes the local namespace, but when I execute locals(), variable z disappeared.

However, if I change the code like this:

```<code>def foo(cond):
    if cond:
        return 1
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)
</code>```

The result will be:

```<code>{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
</code>```

I'm really confused. :(

答:
Compare your code with the following:

def foo(cond):
    if cond:
        return 1
    else:
        loc = locals().copy()
        # ——————————————^
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)
```

<p>It produces</p>

```{'cond': False}
{'cond': False, 'loc': {'cond': False}, 'x': 1, 'y': 2, 'z': 3}
```

as you might expect. The reason is that locals() is a reference, not a value.

Body:
I'm using Python3.7.2

The code which makes me confused looks like this:

def foo(cond):
    if cond:
        z = 1
        return z
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)

Here is the result it prints:

{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2}

The exec function changes the local namespace, but when I execute locals(), variable z disappeared.

However, if I change the code like this:

def foo(cond):
    if cond:
        return 1
    else:
        loc = locals()
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)

The result will be:

{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}
{'cond': False, 'loc': {...}, 'x': 1, 'y': 2, 'z': 3}

I'm really confused. :(

Body:
Compare your code with the following:

def foo(cond):
    if cond:
        return 1
    else:
        loc = locals().copy()
        # ——————————————^
        x = 1
        locals()['y'] = 2
        exec("z = x + y")
        print(loc)
        print(locals())

foo(False)

It produces

{'cond': False}
{'cond': False, 'loc': {'cond': False}, 'x': 1, 'y': 2, 'z': 3}

as you might expect. The reason is that locals() is a reference, not a value.


问:
Why does Rust Closure take ownership before being called
I'm going through the Rust book, and I'm on the chapter describing closures. I'm a bit confused about why the following example errors due to the closure taking ownership:

```<code>fn main() {
let x = vec![1, 2, 3];

let equal_to_x = move |z| z == x;

println!("can't use x here: {:?}", x);

let y = vec![1, 2, 3];

assert!(equal_to_x(y));
}
</code>```

Namely, why does equal_to_x take ownership of x before it's even called? Shouldn't the compiler know that the closure hasn't been called (because it is owned by main) and thus x can still be owned by the outside scope of main?

答:
Because a closure is essentially a struct with a function associated with it. I find it easier to think of closures like this:

```<code>struct MyClosure{
    x: Vec<i32>
};

impl MyClosure {
    pub fn execute(self, z: Vec<i32>) -> bool {
        z == self.x
    }
}
</code>```

If thought of like this, your code is equivalent to

```<code>let equal_to_x  = MyClosure {
    x
};
</code>```

so you can see why the move has happened.

Body:
I'm going through the Rust book, and I'm on the chapter describing closures. I'm a bit confused about why the following example errors due to the closure taking ownership:

fn main() {
let x = vec![1, 2, 3];

let equal_to_x = move |z| z == x;

println!("can't use x here: {:?}", x);

let y = vec![1, 2, 3];

assert!(equal_to_x(y));
}

Namely, why does equal_to_x take ownership of x before it's even called? Shouldn't the compiler know that the closure hasn't been called (because it is owned by main) and thus x can still be owned by the outside scope of main?

Body:
Because a closure is essentially a struct with a function associated with it. I find it easier to think of closures like this:

struct MyClosure{
    x: Vec<i32>
};

impl MyClosure {
    pub fn execute(self, z: Vec<i32>) -> bool {
        z == self.x
    }
}

If thought of like this, your code is equivalent to

let equal_to_x  = MyClosure {
    x
};

so you can see why the move has happened.


问:
Laravel: pagination on search method not updating the url
I'm currently working on a project where one page displays all items currently in the db, and I use laravel's pagination. This works perfectly fine. But the page also has a search functionality to search for specific items. This is where I encounter my problem.

At the moment the, after the search the first page is displayed fine, but when I press the buttons to go to any other page I get always the first page (the page refreshes but the url doesn't change and I get page 1 again). If I manually change the url to the href on the link it works but pressing the button doesn't change the url. page number is not appending.

Here is my controller

```<code>public function searchItems(Request $request)
  {
    if (!Auth::check() || !Auth::user()->is_admin()) return redirect('/login');

    $request->validate([

      'admin-query' => 'required|min:3',

    ]);

    $query = $request->input('admin-query');

    $items_aux = DB::select("SELECT id, ts_rank_cd(textsearch, query) AS rank FROM \"item\", to_tsquery('english','.$query')
      AS query, to_tsvector(name || ' ' || description) AS textsearch WHERE query @@ textsearch ORDER BY rank DESC");

    $ids = array();
    for ($i = 0; $i < sizeof($items_aux); $i++) {
      $ids[$i] = $items_aux[$i]->id;
    }

    $categories = Category::orderBy('id', 'DESC')->get();

    $items = Item::whereIn('id', $ids)->orderBy('id', 'DESC')->paginate(10);
    $pagination = $items->appends(array(
      'adim-query' => Input::get('admin-query')
    ));

    foreach ($items as $item) {

      $img_url = Product_Image::where('id_item', '=', $item->id)->first()['url'];
      if (Storage::disk('public')->exists($img_url)) {
        $item->img = Storage::url($img_url);
      } else {
        $item->img = null;
      }
    }

    return view('pages.adminproducts', ['items' => $items, 'categories'=>$categories]);
  }
</code>```

My Routes:

```<code>Route::get('admin-items/search', 'AdminItemsController@searchItems');
</code>```

My Form:

```<code><div class="form col-sm-8 col-md-8 col-lg-4 text-center pt-0">
            <!--form-->
            <form action="/admin-items/search" method="GET" class="header-search-form" role="search">

            <input type="text" name="admin-query" id="admin-query" value="{{ request()->input('admin-query') }}" class="search-box"
                placeholder="Search Products">
                <button><i class="fa fa-search" aria-hidden="true"></i>
                </button>
            </form>
        </div>
</code>```

My Items and Links:

```<code><div class="row">
            <div class="management-products container-fluid card-deck justify-content-center">

                @foreach($items as $item)
                @include('partials.admin_product', $item)
                @endforeach
            </div>
        </div>
        <div class="row justify-content-center">
            <div class="pagination-links">
                {{ $items->links() }}
            </div>
        </div>
    </div>
</code>```

Inspect the links on page loaded

```<code><li class="page-item disabled" aria-disabled="true" aria-label="« Previous">
<span class="page-link" aria-hidden="true">‹</span>
</li>
<li class="page-item active" aria-current="page"><span class="page-link">1</span></li>
<li class="page-item"><a class="page-link" href="http://localhost:8000/admin-items/search?adim-query=volutpat&page=2">2</a></li>
 <li class="page-item"><a class="page-link" href="http://localhost:8000/admin-items/search?adim-query=volutpat&page=3">3</a></li>
<li class="page-item"><a class="page-link" href="http://localhost:8000/admin-items/search?adim-query=volutpat&page=4">4</a></li>
<li class="page-item"><a class="page-link" href="http://localhost:8000/admin-items/search?adim-query=volutpat&page=5">5</a></li>
<li class="page-item"><a class="page-link" href="http://localhost:8000/admin-items/search?adim-query=volutpat&page=6">6</a></li>
<li class="page-item"><a class="page-link" href="http://localhost:8000/admin-items/search?adim-query=volutpat&page=2" rel="next" aria-label="Next »">›</a></li>

</code>```

答:
You have to make a little change inside your view. If this doesn't work then let me know, have to give you another solution

```<code><div class="row">
        <div class="management-products container-fluid card-deck justify-content-center">

            @foreach($items as $item)
            @include('partials.admin_product', $item)
            @endforeach
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="pagination-links">
            {{ $items->appends(request()->except('page'))->links() }}
            //This is important
        </div>
    </div>
</div>
</code>```

Or you can also do it as your code is, but with little change

```<code>$items = Item::whereIn('id', $ids)->orderBy('id', 'DESC')->paginate(10);
$items = $items->appends(request()->except('page'));
</code>```

Body:
I'm currently working on a project where one page displays all items currently in the db, and I use laravel's pagination. This works perfectly fine. But the page also has a search functionality to search for specific items. This is where I encounter my problem.

At the moment the, after the search the first page is displayed fine, but when I press the buttons to go to any other page I get always the first page (the page refreshes but the url doesn't change and I get page 1 again). If I manually change the url to the href on the link it works but pressing the button doesn't change the url. page number is not appending.

Here is my controller

public function searchItems(Request $request)
  {
    if (!Auth::check() || !Auth::user()->is_admin()) return redirect('/login');

    $request->validate([

      'admin-query' => 'required|min:3',

    ]);

    $query = $request->input('admin-query');

    $items_aux = DB::select("SELECT id, ts_rank_cd(textsearch, query) AS rank FROM \"item\", to_tsquery('english','.$query')
      AS query, to_tsvector(name || ' ' || description) AS textsearch WHERE query @@ textsearch ORDER BY rank DESC");

    $ids = array();
    for ($i = 0; $i < sizeof($items_aux); $i++) {
      $ids[$i] = $items_aux[$i]->id;
    }

    $categories = Category::orderBy('id', 'DESC')->get();

    $items = Item::whereIn('id', $ids)->orderBy('id', 'DESC')->paginate(10);
    $pagination = $items->appends(array(
      'adim-query' => Input::get('admin-query')
    ));

    foreach ($items as $item) {

      $img_url = Product_Image::where('id_item', '=', $item->id)->first()['url'];
      if (Storage::disk('public')->exists($img_url)) {
        $item->img = Storage::url($img_url);
      } else {
        $item->img = null;
      }
    }

    return view('pages.adminproducts', ['items' => $items, 'categories'=>$categories]);
  }

My Routes:

Route::get('admin-items/search', 'AdminItemsController@searchItems');

My Form:

            <form action="/admin-items/search" method="GET" class="header-search-form" role="search">

            <input type="text" name="admin-query" id="admin-query" value="{{ request()->input('admin-query') }}" class="search-box"
                placeholder="Search Products">
                <button>
                </button>
            </form>

My Items and Links:

                @foreach($items as $item)
                @include('partials.admin_product', $item)
                @endforeach

                {{ $items->links() }}

Inspect the links on page loaded

‹

1

2

3

4

5

6

›

Body:
You have to make a little change inside your view. If this doesn't work then let me know, have to give you another solution

<div class="row">
        <div class="management-products container-fluid card-deck justify-content-center">

            @foreach($items as $item)
            @include('partials.admin_product', $item)
            @endforeach
        </div>
    </div>
    <div class="row justify-content-center">
        <div class="pagination-links">
            {{ $items->appends(request()->except('page'))->links() }}
            //This is important
        </div>
    </div>
</div>

Or you can also do it as your code is, but with little change

$items = Item::whereIn('id', $ids)->orderBy('id', 'DESC')->paginate(10);
$items = $items->appends(request()->except('page'));


问:
Why is not working when i try to add a to a string to my array location
I'm still learning JavaScript, and now I'm in the array chapter and I'm doing this project I have to ask the user for 5 names and stored and my array, then have to sort the names by the location in the array, so i could separed in odd and in even, then i have to add a lastname to the odds, and different last name to the even, but is that part that is not working any help ... THANKS</p>

```<code>var numberfirstNames = 5;
var userMessage = " Please enter a first Name" ;
var secondArray = [];
var odd2 = [];
var even2 = [];
for (var i = 0; i < numberfirstNames; i++) // loop 5 times  LOOL ASKING FOR "5" FIRST NAMES>> STORING IN NAMES
{
    secondArray[i] = getFirstname();
    window.alert("second " + secondArray[i] );
}
for (var i = 0; i < secondArray.length; i++) {
    if(i % 2 === 0)  // index is even
    {
        even2.push(secondArray[i]);
        for ( var i=0 ; i<even2.length; i++)
            even2[i]+=" Chavez"
    }
    else
    {
        odd2.push(secondArray[i]);
        for ( var i=0 ; i<odd2.length; i++)
            odd2[i]+=" McCain"
    }
}

document.write(" \n all the names: "+ secondArray+'<br>');
document.write(" \n even names: "+ even2+'<br>');
document.write(" \n odd names: "+ odd2+'<br>');
</code>```

答:
The problem is that you are making a second loop that is unnecessary... the code

```<code>for ( var i=0 ; i<even2.length; i++)
</code>```

and

```<code>for ( var i=0 ; i<odd2.length; i++)
</code>```

should be simply removed.

You need to add first or last name only to last element added to odd2 or even2 and this can be done with:

```<code> even2[even2.length-1]+=" Chavez"
</code>```

and

```<code> odd2[odd2.length-1]+=" McCain"
</code>```

It is important to get used adding correct indentation because this kind of error is much easier to spot in the code when it is properly indented.

Body:
I'm still learning JavaScript, and now I'm in the array chapter and I'm doing this project I have to ask the user for 5 names and stored and my array, then have to sort the names by the location in the array, so i could separed in odd and in even, then i have to add a lastname to the odds, and different last name to the even, but is that part that is not working any help ... THANKS

var numberfirstNames = 5;
var userMessage = " Please enter a first Name" ;
var secondArray = [];
var odd2 = [];
var even2 = [];
for (var i = 0; i < numberfirstNames; i++) // loop 5 times  LOOL ASKING FOR "5" FIRST NAMES>> STORING IN NAMES
{
    secondArray[i] = getFirstname();
    window.alert("second " + secondArray[i] );
}
for (var i = 0; i < secondArray.length; i++) {
    if(i % 2 === 0)  // index is even
    {
        even2.push(secondArray[i]);
        for ( var i=0 ; i<even2.length; i++)
            even2[i]+=" Chavez"
    }
    else
    {
        odd2.push(secondArray[i]);
        for ( var i=0 ; i<odd2.length; i++)
            odd2[i]+=" McCain"
    }
}

document.write(" \n all the names: "+ secondArray+'
');
document.write(" \n even names: "+ even2+'
');
document.write(" \n odd names: "+ odd2+'
');

Body:
The problem is that you are making a second loop that is unnecessary... the code

for ( var i=0 ; i<even2.length; i++)

and

for ( var i=0 ; i<odd2.length; i++)

should be simply removed.

You need to add first or last name only to last element added to odd2 or even2 and this can be done with:

 even2[even2.length-1]+=" Chavez"

and

 odd2[odd2.length-1]+=" McCain"

It is important to get used adding correct indentation because this kind of error is much easier to spot in the code when it is properly indented.


问:
Split String every 2 characters with Zip in Python 3
I need to make a function that receives a String and a number and split this String every 2 characters but if the length of the String is not even I have to add the number. Here's what I got so far.

```<code>def splitString(string,number):
  if (len(string)%2 != 0):
    return list(map(''.join, zip(*[iter(string)]*2))) # I don't know how to add the number at the end
  else:
    return list(map(''.join, zip(*[iter(string)]*2)))
</code>```

As this is for homework I was told I can't create a list and then use .append() so I have to return the list ready.

答:
This is really easily achieved using re.findall to search for substrings of 2 characters in the string with the number appended to it:

```<code>import re

def splitString(string,number):
    return re.findall(r'..', string + str(number))

print(splitString('hello', 3))
print(splitString('farewell', 3))
</code>```

Output:

```<code>['he', 'll', 'o3']
['fa', 're', 'we', 'll']
</code>```

Body:
I need to make a function that receives a String and a number and split this String every 2 characters but if the length of the String is not even I have to add the number. Here's what I got so far.

def splitString(string,number):
  if (len(string)%2 != 0):
    return list(map(''.join, zip(*[iter(string)]*2))) # I don't know how to add the number at the end
  else:
    return list(map(''.join, zip(*[iter(string)]*2)))

As this is for homework I was told I can't create a list and then use .append() so I have to return the list ready.

Body:
This is really easily achieved using re.findall to search for substrings of 2 characters in the string with the number appended to it:

import re

def splitString(string,number):
    return re.findall(r'..', string + str(number))

print(splitString('hello', 3))
print(splitString('farewell', 3))

Output:

['he', 'll', 'o3']
['fa', 're', 'we', 'll']