问:
Dynamically updating html based on viewmodel
I'm currently trying to update some HTML based on two properties in my viewmodel which are hooked to two form groups. This is ASP.NET Core.

The two form groups:

```<code><div class="form-group">
   <label asp-for="ParticipantAmount">Antal deltagere</label>
   <input asp-for="ParticipantAmount" onchange="Group()" class="form-control" type="number" max="1000" min="1" />
</div>
<div class="form-group">
   <label asp-for="GroupAmount">Antal grupper</label>
   <input asp-for="GroupAmount" class="form-control" onchange="Group()" type="number" max="20" min="1" />
   <p id="GroupSize">0</p>
</div>
</code>```

The properties in the viewmodel:

```<code>public int ParticipantAmount { get; set; }
public int GroupAmount { get; set; }
</code>```

The javascript method in the script section:

```<code>function Group() {
    var groups = Number('@Model.GroupAmount');
    var participants = Number('@Model.ParticipantAmount');
    var size = participants / groups;
    document.getElementById('GroupSize').innerHTML = size;
}
</code>```

When I try to log stuff to the console, it seems like the properties are not being updated in the viewmodel when the form inputs change.

I think I'm missing some basic knowledge about an important aspect of what I'm trying to do, but I can't seem to google the correct keywords. Hope you can lead me in the right direction.

答:
Just to illustrate how AJAX calls work I made a minimalistic web application using jQuery which should be used for learning only, the code is not production-ready.

Razor view. I've added default values and IDs to your the input fields to identify them easier in JavaScript code.

```<code><div class="form-group">
    <label asp-for="ParticipantAmount">Antal deltagere</label>
    <input asp-for="ParticipantAmount" onchange="Group()" class="form-control" type="number" max="1000" min="1" value="@Model.ParticipantAmount" id="ParticipantAmount" />
</div>
<div class="form-group">
    <label asp-for="GroupAmount">Antal grupper</label>
    <input asp-for="GroupAmount" class="form-control" onchange="Group()" type="number" max="20" min="1" value="@Model.GroupAmount" id="GroupAmount" />
    <p id="GroupSize">0</p>`enter code here`
</div>
</code>```

JavaScript code using jQuery to get/update values and make AJAX request.

```<code><script>
function Group() {
    $.ajax({
        method: "POST",
        url: "/Home/UpdateAmounts",
        data: { ParticipantAmount: $('#ParticipantAmount').val(), GroupAmount: $('#GroupAmount').val() }
    }).done(function (response) {
        $('#GroupSize').html(response);
    });
}
</script>
</code>```

Controller and view model. Added a method for AJAX calls.

```<code>public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View(new ParticipantViewModel());
    }

    // You can call this method via AJAX to update your view model
    [HttpPost]
    public IActionResult UpdateAmounts(int participantAmount, int groupAmount)
    {
        // Validation for negative numbers, and groupAmount cannot be zero
        if (participantAmount < 0 || groupAmount <= 0)
        {
            return Ok(0);
        }

        return Ok(participantAmount / groupAmount);
    }
}

public class ParticipantViewModel
{
    public int ParticipantAmount { get; set; }

    public int GroupAmount { get; set; }
}
</code>```

To make things nicer and more modern you could look into following example of a simple web application using database to store data, and using Knockout for UI.

Body:
I'm currently trying to update some HTML based on two properties in my viewmodel which are hooked to two form groups. This is ASP.NET Core.

The two form groups:

   Antal deltagere
   <input asp-for="ParticipantAmount" onchange="Group()" class="form-control" type="number" max="1000" min="1" />

   Antal grupper
   <input asp-for="GroupAmount" class="form-control" onchange="Group()" type="number" max="20" min="1" />

0

The properties in the viewmodel:

public int ParticipantAmount { get; set; }
public int GroupAmount { get; set; }

The javascript method in the script section:

function Group() {
    var groups = Number('@Model.GroupAmount');
    var participants = Number('@Model.ParticipantAmount');
    var size = participants / groups;
    document.getElementById('GroupSize').innerHTML = size;
}

When I try to log stuff to the console, it seems like the properties are not being updated in the viewmodel when the form inputs change.

I think I'm missing some basic knowledge about an important aspect of what I'm trying to do, but I can't seem to google the correct keywords. Hope you can lead me in the right direction.

Body:
Just to illustrate how AJAX calls work I made a minimalistic web application using jQuery which should be used for learning only, the code is not production-ready.

Razor view. I've added default values and IDs to your the input fields to identify them easier in JavaScript code.

<div class="form-group">
    <label asp-for="ParticipantAmount">Antal deltagere</label>
    <input asp-for="ParticipantAmount" onchange="Group()" class="form-control" type="number" max="1000" min="1" value="@Model.ParticipantAmount" id="ParticipantAmount" />
</div>
<div class="form-group">
    <label asp-for="GroupAmount">Antal grupper</label>
    <input asp-for="GroupAmount" class="form-control" onchange="Group()" type="number" max="20" min="1" value="@Model.GroupAmount" id="GroupAmount" />
    <p id="GroupSize">0</p>`enter code here`
</div>

JavaScript code using jQuery to get/update values and make AJAX request.

<script>
function Group() {
    $.ajax({
        method: "POST",
        url: "/Home/UpdateAmounts",
        data: { ParticipantAmount: $('#ParticipantAmount').val(), GroupAmount: $('#GroupAmount').val() }
    }).done(function (response) {
        $('#GroupSize').html(response);
    });
}
</script>

Controller and view model. Added a method for AJAX calls.

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View(new ParticipantViewModel());
    }

    // You can call this method via AJAX to update your view model
    [HttpPost]
    public IActionResult UpdateAmounts(int participantAmount, int groupAmount)
    {
        // Validation for negative numbers, and groupAmount cannot be zero
        if (participantAmount < 0 || groupAmount <= 0)
        {
            return Ok(0);
        }

        return Ok(participantAmount / groupAmount);
    }
}

public class ParticipantViewModel
{
    public int ParticipantAmount { get; set; }

    public int GroupAmount { get; set; }
}

To make things nicer and more modern you could look into following example of a simple web application using database to store data, and using Knockout for UI.


来源: stackexchange

问:
Package redis.embedded does not exist
I work with a small Spring Boot project and I get the following error while using command mvn clean install

```<code>[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for SpringChatApp:com.messanger.chat:jar:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: commons-dbcp:commons-dbcp:jar -> duplicate declaration of version RELEASE @ line 155, column 21
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> duplicate declaration of version RELEASE @ line 160, column 21
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework.boot:spring-boot-starter-websocket:jar -> duplicate declaration of version RELEASE @ line 184, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building com.messanger.chat 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The artifact org.hibernate:hibernate-validator:jar:6.0.0.CR1 has been relocated to org.hibernate.validator:hibernate-validator:jar:6.0.0.CR1
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ com.messanger.chat ---
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ com.messanger.chat ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 576 resources
[INFO] Copying 20 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ com.messanger.chat ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 20 source files to /Users/Chaklader/IdeaProjects/SpringChatApp/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[14,22] package redis.embedded does not exist
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[35,25] cannot find symbol
  symbol:   class RedisServer
  location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[40,43] cannot find symbol
  symbol:   class RedisServer
  location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.042 s
[INFO] Finished at: 2017-07-04T19:29:34+06:00
[INFO] Final Memory: 42M/792M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project com.messanger.chat: Compilation failure: Compilation failure:
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[14,22] package redis.embedded does not exist
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[35,25] cannot find symbol
[ERROR]   symbol:   class RedisServer
[ERROR]   location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[40,43] cannot find symbol
[ERROR]   symbol:   class RedisServer
[ERROR]   location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

The pom.xml file is provided below,

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>SpringChatApp</groupId>
    <artifactId>com.messanger.chat</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
            </resource>
        </resources>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>net.glxn</groupId>
            <artifactId>qrgen</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>RELEASE</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>RELEASE</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>1.5.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-messaging -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-messaging</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.kstyrc</groupId>
            <artifactId>embedded-redis</artifactId>
            <version>0.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
            <version>3.0.7.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-net -->
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-net</artifactId>
            <version>2.0.8.RELEASE</version>
        </dependency>
    </dependencies>
</project>
</code>```

Clearly, I have used the embedded-redis dependency in the project,

```<code>        <dependency>
            <groupId>com.github.kstyrc</groupId>
            <artifactId>embedded-redis</artifactId>
            <version>0.6</version>
            <scope>test</scope>
        </dependency>
</code>```

This is the file where I get the error message,

```<code>import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import redis.clients.jedis.Protocol;
import redis.embedded.RedisServer;

/**
 * Redis is required for {@link EnableRedisHttpSession} handling.
 */
@Configuration
public class RedisConfig {

    @Bean
    public static RedisServerBean redisServer() {
        return new RedisServerBean();
    }

    /**
     * Implements BeanDefinitionRegistryPostProcessor to ensure this Bean is
     * initialized before any other Beans. Specifically, we want to ensure that
     * the Redis Server is started before RedisHttpSessionConfiguration attempts
     * to enable Keyspace notifications.
     */
    static class RedisServerBean implements InitializingBean, DisposableBean, BeanDefinitionRegistryPostProcessor {

        private RedisServer redisServer;

        @Override
        public void afterPropertiesSet() throws Exception {

            redisServer = new RedisServer(Protocol.DEFAULT_PORT);
            redisServer.start();
        }

        @Override
        public void destroy() throws Exception {
            if (redisServer != null) {
                redisServer.stop();
            }
        }

        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        }

    }
}
</code>```

How to solve the problem?

答:
The scope you put for the dependency is test. So it is not included when using clean install. Remove the scope tag and try again.

For more information on maven dependency scopes:
https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Scope

ContentLicense: CC BY-SA 3.0

Title: Package redis.embedded does not exist

Body:
I work with a small Spring Boot project and I get the following error while using command mvn clean install

[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for SpringChatApp:com.messanger.chat:jar:1.0-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: commons-dbcp:commons-dbcp:jar -> duplicate declaration of version RELEASE @ line 155, column 21
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: junit:junit:jar -> duplicate declaration of version RELEASE @ line 160, column 21
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.springframework.boot:spring-boot-starter-websocket:jar -> duplicate declaration of version RELEASE @ line 184, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building com.messanger.chat 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The artifact org.hibernate:hibernate-validator:jar:6.0.0.CR1 has been relocated to org.hibernate.validator:hibernate-validator:jar:6.0.0.CR1
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ com.messanger.chat ---
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ com.messanger.chat ---
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 576 resources
[INFO] Copying 20 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ com.messanger.chat ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 20 source files to /Users/Chaklader/IdeaProjects/SpringChatApp/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[14,22] package redis.embedded does not exist
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[35,25] cannot find symbol
  symbol:   class RedisServer
  location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[40,43] cannot find symbol
  symbol:   class RedisServer
  location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[INFO] 3 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.042 s
[INFO] Finished at: 2017-07-04T19:29:34+06:00
[INFO] Final Memory: 42M/792M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project com.messanger.chat: Compilation failure: Compilation failure:
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[14,22] package redis.embedded does not exist
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[35,25] cannot find symbol
[ERROR]   symbol:   class RedisServer
[ERROR]   location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[ERROR] /Users/Chaklader/IdeaProjects/SpringChatApp/src/main/java/com/sergialmar/wschat/config/RedisConfig.java:[40,43] cannot find symbol
[ERROR]   symbol:   class RedisServer
[ERROR]   location: class com.sergialmar.wschat.config.RedisConfig.RedisServerBean
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

The pom.xml file is provided below,

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>SpringChatApp</groupId>
    <artifactId>com.messanger.chat</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
            </resource>
        </resources>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>net.glxn</groupId>
            <artifactId>qrgen</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>RELEASE</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>RELEASE</version>
            <type>pom</type>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>1.5.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-messaging</artifactId>
            <version>4.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session</artifactId>
            <version>1.3.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.kstyrc</groupId>
            <artifactId>embedded-redis</artifactId>
            <version>0.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-core</artifactId>
            <version>3.0.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-net</artifactId>
            <version>2.0.8.RELEASE</version>
        </dependency>
    </dependencies>
</project>

Clearly, I have used the embedded-redis dependency in the project,

        <dependency>
            <groupId>com.github.kstyrc</groupId>
            <artifactId>embedded-redis</artifactId>
            <version>0.6</version>
            <scope>test</scope>
        </dependency>

This is the file where I get the error message,

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

import redis.clients.jedis.Protocol;
import redis.embedded.RedisServer;

/**
 * Redis is required for {@link EnableRedisHttpSession} handling.
 */
@Configuration
public class RedisConfig {

    @Bean
    public static RedisServerBean redisServer() {
        return new RedisServerBean();
    }

    /**
     * Implements BeanDefinitionRegistryPostProcessor to ensure this Bean is
     * initialized before any other Beans. Specifically, we want to ensure that
     * the Redis Server is started before RedisHttpSessionConfiguration attempts
     * to enable Keyspace notifications.
     */
    static class RedisServerBean implements InitializingBean, DisposableBean, BeanDefinitionRegistryPostProcessor {

        private RedisServer redisServer;

        @Override
        public void afterPropertiesSet() throws Exception {

            redisServer = new RedisServer(Protocol.DEFAULT_PORT);
            redisServer.start();
        }

        @Override
        public void destroy() throws Exception {
            if (redisServer != null) {
                redisServer.stop();
            }
        }

        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        }

    }
}

How to solve the problem?


问:
Deploying c# application issues
I have a application with one folder which i added by right clicking the project, selecting add folder. Inside this folder i have xml files which are set to build action:content, copy to output directory: copy if newer (i have tried setting to embedded resource) As well as this i have a few text files and so on.

In my bin/debug output directory i have the exe, the folder with the xml, the stand alone .txt files  and so on. My problem is, if i send the exe to my friend to try he always gets an exception thrown.

Say he puts the exe on the desktop, my programme at some point reads the filenames of the xml files in the folder. It uses the following code to do so

```<code>String[] filePaths = Directory.GetFiles(@"DataSources\");
</code>```

I assume that because of this, when the exe runs from the desktop, it expect the folder of .xml files to be in the same place? I have the same type of exception when trying to read the .txt files too. What am i doing wrong here?

Thanks for your time

答:
When reading from files using relative paths you get the one relative to the applications current directory. tip: In C# you can see what directory that is using Environment.CurrentDirectory.

So if you create a shortcut on your desktop, you need to make sure you right click the shortcut and set its "Start in"-folder to the directory of your application. That way its current directory will be set when its started and relative paths will be relative to that path and not the path of the shortcut.

If you actually moved the exe file to the desktop you also need to move any resources that it needs, so if it wants a folder named "datasources" you would have to move that folder as well, or set the current directory when you start the application.

ContentLicense: CC BY-SA 2.5

Title: Deploying c# application issues

Body:
I have a application with one folder which i added by right clicking the project, selecting add folder. Inside this folder i have xml files which are set to build action:content, copy to output directory: copy if newer (i have tried setting to embedded resource) As well as this i have a few text files and so on.

In my bin/debug output directory i have the exe, the folder with the xml, the stand alone .txt files  and so on. My problem is, if i send the exe to my friend to try he always gets an exception thrown.

Say he puts the exe on the desktop, my programme at some point reads the filenames of the xml files in the folder. It uses the following code to do so

String[] filePaths = Directory.GetFiles(@"DataSources\");

I assume that because of this, when the exe runs from the desktop, it expect the folder of .xml files to be in the same place? I have the same type of exception when trying to read the .txt files too. What am i doing wrong here?

Thanks for your time


问:
Where can I find all App Maker button icons?
Is there a list of button icons that can be used in App Maker? E.g. when you set the HTML text field of a button to 'Edit' and choose 'Icon' as button style, App Maker conveniently provides me an icon with a pencil on it.

Right now I'm looking for a dropdown arrow icon, but a list of icons would be so useful to make my UIs more clean.

答:
App Maker uses material font:

https://material.io/icons/


问:
ImportError: libcblas.so.3gf: cannot open shared object file: No such file or directory
I am new to unix. I am using sklearn package for python for a multi-class and multi-label text classification. After running

```<code>from sklearn.multiclass import OneVsRestClassifier
</code>```

I get the error

ImportError: libcblas.so.3gf: cannot open shared object file: No such file or directory

I have no idea how to solve this error. I have looked at similar question on different forums, but the responses are too advanced for me. Can someone explain in the layman's words, how to resolve this issue?

答:
You need to upgrade or install again the sklearn 0.18.1 module.

the following works fine in sklearn 0.18.1 version (this is the latest).

```<code>from sklearn.multiclass import OneVsRestClassifier
</code>```

To see your version do:

```<code>import sklearn

print('The scikit-learn version is {}.'.format(sklearn.__version__))
</code>```

To install sklearn 0.18.1 use:

```<code> pip install -U scikit-learn
</code>```

Body:
I am new to unix. I am using sklearn package for python for a multi-class and multi-label text classification. After running

from sklearn.multiclass import OneVsRestClassifier

I get the error

ImportError: libcblas.so.3gf: cannot open shared object file: No such file or directory

I have no idea how to solve this error. I have looked at similar question on different forums, but the responses are too advanced for me. Can someone explain in the layman's words, how to resolve this issue?

Body:
You need to upgrade or install again the sklearn 0.18.1 module.

the following works fine in sklearn 0.18.1 version (this is the latest).

from sklearn.multiclass import OneVsRestClassifier

To see your version do:

import sklearn

print('The scikit-learn version is {}.'.format(sklearn.__version__))

To install sklearn 0.18.1 use:

 pip install -U scikit-learn


问:
How to write a file inside system/etc/wifi/wpa_supplicant.conf file using android program?
I am working on wifi related app, which takes the user giving username password and need to write(edit/append)in a file which is located in system/etc/wifi/ path.

I searched in stackoverflow and got some answers and then tried but there is no luck. This is rooted device. I did remount and su too. I can able to read the same file. I placed all the permissions in manifest too. What I missed?

```<code>try {
    String[] command = new String[]{"/system/bin/ls", "-l",
            "/system/etc/wifi/wpa_supplicant.conf" };
    Process process = Runtime.getRuntime().exec(command);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    int read;

    String output = "";
    String line;
    while ((line = reader.readLine()) != null) {
        output.concat(line + "\n");
        Log.w("myApp", "[[output]]:" + line);
    }
    reader.close();
    process.waitFor();

    String[] command2 = new String[]{"/system/etc/wifi/chmod", "777",
            "/system/etc/wifi/wpa_supplicant.conf" };

    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(new String[]{"/system/bin/sh", "-c", "echo \"12345678\" > /system/etc/wifi/wpa_supplicant.conf"});

    File path= Environment.getDataDirectory();
    FileWriter fw = new FileWriter(new File("/system/etc/wifi/wpa_supplicant"));
    fw.write('9');
    fw.close();

    Log.d(TAG, "File Saved Successfully !!!");

    //display file saved message
        /*Toast.makeText(getBaseContext(), "File saved successfully!",
        Toast.LENGTH_SHORT).show();*/

} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Here is my manifest permissions (outside application tag and some more permissions also there for some other purpose ).

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</code>```

And below error I am getting,

```<code>01-01 06:13:53.565: W/myApp(11205): [[output]]:-rw-rw-rw- root     root           58 2000-01-01 03:56 wpa_supplicant.conf
01-01 06:13:53.580: W/System.err(11205): java.io.FileNotFoundException: /system/etc/wifi/wpa_supplicant: open failed: EROFS (Read-only file system)
01-01 06:13:53.580: W/System.err(11205):    at libcore.io.IoBridge.open(IoBridge.java:452)
01-01 06:13:53.580: W/System.err(11205):    at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
01-01 06:13:53.580: W/System.err(11205):    at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
01-01 06:13:53.581: W/System.err(11205):    at java.io.FileWriter.<init>(FileWriter.java:42)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService.WriteBtn(HeadlessService.java:450)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService.setupWifiAPConfig(HeadlessService.java:386)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService$HttpServiceThread$WiFiPageHandler.handle(HeadlessService.java:1094)
01-01 06:13:53.581: W/System.err(11205):    at org.apache.http.protocol.HttpService.doService(HttpService.java:248)
01-01 06:13:53.581: W/System.err(11205):    at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:192)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService$HttpServiceThread.run(HeadlessService.java:663)
01-01 06:13:53.581: W/System.err(11205): Caused by: android.system.ErrnoException: open failed: EROFS (Read-only file system)
01-01 06:13:53.581: W/System.err(11205):    at libcore.io.Posix.open(Native Method)
01-01 06:13:53.581: W/System.err(11205):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
01-01 06:13:53.582: W/System.err(11205):    at libcore.io.IoBridge.open(IoBridge.java:438)
01-01 06:13:53.582: W/System.err(11205):    ... 9 more
</code>```

答:
Did you have root access? Without root access only the mechanism of flashing an update (via recovery or OTA) can modify /system. To be accepted, such an update archive must be signed with the same key as the ROM – which is something only the developer of the ROM can do.

There might be a way via a custom recovery which lets you edit all file systems directly (twrp). But without knowing what device it is, it cannot be said if a matching recovery exists. Apart from that, it's either rooting the device or not editing any file within /system.

If you have root access, you should execute commands as root! su command should be used

```<code>Runtime.getRuntime().exec("su");
</code>```

or a full path to su.bin in each command.

Body:
I am working on wifi related app, which takes the user giving username password and need to write(edit/append)in a file which is located in system/etc/wifi/ path.

I searched in stackoverflow and got some answers and then tried but there is no luck. This is rooted device. I did remount and su too. I can able to read the same file. I placed all the permissions in manifest too. What I missed?

try {
    String[] command = new String[]{"/system/bin/ls", "-l",
            "/system/etc/wifi/wpa_supplicant.conf" };
    Process process = Runtime.getRuntime().exec(command);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    int read;

    String output = "";
    String line;
    while ((line = reader.readLine()) != null) {
        output.concat(line + "\n");
        Log.w("myApp", "[[output]]:" + line);
    }
    reader.close();
    process.waitFor();

    String[] command2 = new String[]{"/system/etc/wifi/chmod", "777",
            "/system/etc/wifi/wpa_supplicant.conf" };

    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(new String[]{"/system/bin/sh", "-c", "echo \"12345678\" > /system/etc/wifi/wpa_supplicant.conf"});

    File path= Environment.getDataDirectory();
    FileWriter fw = new FileWriter(new File("/system/etc/wifi/wpa_supplicant"));
    fw.write('9');
    fw.close();

    Log.d(TAG, "File Saved Successfully !!!");

    //display file saved message
        /*Toast.makeText(getBaseContext(), "File saved successfully!",
        Toast.LENGTH_SHORT).show();*/

} catch (Exception e) {
    e.printStackTrace();
}

Here is my manifest permissions (outside application tag and some more permissions also there for some other purpose ).

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

And below error I am getting,

01-01 06:13:53.565: W/myApp(11205): [[output]]:-rw-rw-rw- root     root           58 2000-01-01 03:56 wpa_supplicant.conf
01-01 06:13:53.580: W/System.err(11205): java.io.FileNotFoundException: /system/etc/wifi/wpa_supplicant: open failed: EROFS (Read-only file system)
01-01 06:13:53.580: W/System.err(11205):    at libcore.io.IoBridge.open(IoBridge.java:452)
01-01 06:13:53.580: W/System.err(11205):    at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
01-01 06:13:53.580: W/System.err(11205):    at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
01-01 06:13:53.581: W/System.err(11205):    at java.io.FileWriter.<init>(FileWriter.java:42)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService.WriteBtn(HeadlessService.java:450)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService.setupWifiAPConfig(HeadlessService.java:386)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService$HttpServiceThread$WiFiPageHandler.handle(HeadlessService.java:1094)
01-01 06:13:53.581: W/System.err(11205):    at org.apache.http.protocol.HttpService.doService(HttpService.java:248)
01-01 06:13:53.581: W/System.err(11205):    at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:192)
01-01 06:13:53.581: W/System.err(11205):    at com.intel.sunnypoint.headless.HeadlessService$HttpServiceThread.run(HeadlessService.java:663)
01-01 06:13:53.581: W/System.err(11205): Caused by: android.system.ErrnoException: open failed: EROFS (Read-only file system)
01-01 06:13:53.581: W/System.err(11205):    at libcore.io.Posix.open(Native Method)
01-01 06:13:53.581: W/System.err(11205):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
01-01 06:13:53.582: W/System.err(11205):    at libcore.io.IoBridge.open(IoBridge.java:438)
01-01 06:13:53.582: W/System.err(11205):    ... 9 more

Body:
Did you have root access? Without root access only the mechanism of flashing an update (via recovery or OTA) can modify /system. To be accepted, such an update archive must be signed with the same key as the ROM – which is something only the developer of the ROM can do.

There might be a way via a custom recovery which lets you edit all file systems directly (twrp). But without knowing what device it is, it cannot be said if a matching recovery exists. Apart from that, it's either rooting the device or not editing any file within /system.

If you have root access, you should execute commands as root! su command should be used

Runtime.getRuntime().exec("su");

or a full path to su.bin in each command.


问:
sql missing from clause
```<code>  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total
</code>```

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

```<code> |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |
</code>```

This is what I'am trying to achieve, I'am doing this using the jasper report.

答:
```<code>select total.m_product_name ,total.c_bpartner_name  from(
  select count(m_product.name) as m_product_name,'NIL' as  c_bpartner_name
  from m_product
  union
  select 'NIL',count(c_bpartner.name)
  from c_bpartner
  ) as total
</code>```

Title: sql missing from clause

Body:
  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

 |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |

This is what I'am trying to achieve, I'am doing this using the jasper report.


问:
Wordpress numeric pagination without words
My work's Wordpress site needs a numeric pagination for the posts page, however as it's a multilingual site I can't have any words in it like "Previous page" or "Page 1 of 3".

I've tried a couple of different examples that I've found (as I'm not skilled enough to write it myself yet), but they all contain words hidden within queries and I can't figure out how to change them. Eg:

```<code>function pagination($pages = '', $range = 4)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
         echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages."</span>";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>« First</a>";
         if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹ Previous</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">Next ›</a>";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Last »</a>";
         echo "</div>\n";
     }
}
</code>```

This code shows "Page 1 of 2". If I could just change that to 1/2 for example, that would be perfect. Is anyone able to explain how I could do this, or any alternative methods? Many thanks!

答:
Check out below code for Wordpress numeric pagination custom code:</p>

```<code><?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($paged == "1") {
    $args = array(
        'post_type' => 'uk-blog',
        'post_status' => 'publish',
        'offset' => 0,
        'posts_per_page' => 10
    );
} else {
    $offset = $paged * 5;
    $offset = $offset - 5;
    $args = array(
        'post_type' => 'uk-blog',
        'post_status' => 'publish',
        'offset' => $offset
    );
}

$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
    /*Your Code */

endwhile;
?>
<div class="pagination-grp">
    <?php
    $big = 999999999; // need an unlikely integer
    //$i=1;

    echo paginate_links(array(
        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'prev_text' => __('<'),
        'next_text' => __('>'),
        'total' => $loop->max_num_pages

    ));
    wp_reset_postdata();
    endif;
    ?>
</div>
</code>```

Body:
My work's Wordpress site needs a numeric pagination for the posts page, however as it's a multilingual site I can't have any words in it like "Previous page" or "Page 1 of 3".

I've tried a couple of different examples that I've found (as I'm not skilled enough to write it myself yet), but they all contain words hidden within queries and I can't figure out how to change them. Eg:

function pagination($pages = '', $range = 4)
{
     $showitems = ($range * 2)+1;

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }

     if(1 != $pages)
     {
         echo "
Page ".$paged." of ".$pages."";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "« First";
         if($paged > 1 && $showitems < $pages) echo "‹ Previous";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "".$i."":"".$i."";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "Next ›";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "Last »";
         echo "
\n";
     }
}

This code shows "Page 1 of 2". If I could just change that to 1/2 for example, that would be perfect. Is anyone able to explain how I could do this, or any alternative methods? Many thanks!

Body:
Check out below code for Wordpress numeric pagination custom code:

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($paged == "1") {
    $args = array(
        'post_type' => 'uk-blog',
        'post_status' => 'publish',
        'offset' => 0,
        'posts_per_page' => 10
    );
} else {
    $offset = $paged * 5;
    $offset = $offset - 5;
    $args = array(
        'post_type' => 'uk-blog',
        'post_status' => 'publish',
        'offset' => $offset
    );
}

$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
    /*Your Code */

endwhile;
?>
<div class="pagination-grp">
    <?php
    $big = 999999999; // need an unlikely integer
    //$i=1;

    echo paginate_links(array(
        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'prev_text' => __('<'),
        'next_text' => __('>'),
        'total' => $loop->max_num_pages

    ));
    wp_reset_postdata();
    endif;
    ?>
</div>


问:
How do I create a custom asp.net sql membership provider to save hashed passwords in SHA256?
I'm building a web application using the ASP.net Membership Provider to manage, Authentication/Authorisation. I've done this a bunch of times, but this time I need to store the hashed password in SHA256, instead of the standard password hash which is SHA1.

Looking at the overridable methods on the SQLMembershipProvider there is at least one that I think I'm going to have to override in order to get this puppy to work:

```<code>byte[] EncryptPassword(byte[] password)
</code>```

I'll also have to change the aspnet_Membership.Password field cope with the newly hashed password, currently it's only nvarchar(128).

I was hoping that someone with a little more experience on extending the SqlMembershipProvider might be able to give me some pointers.

Thanks.

note: Although I'm using the .net 2.0 membership provider, I'm actually running .net 3.5

答:
I would try following the solutions listed in this answer first before creating my own membership provider:

What is default hash algorithm that ASP.NET membership uses?

As far as I can tell, SHA256 outputs a 64 character string, so you should be safe with the varchar(128) field.

Body:
I'm building a web application using the ASP.net Membership Provider to manage, Authentication/Authorisation. I've done this a bunch of times, but this time I need to store the hashed password in SHA256, instead of the standard password hash which is SHA1.

Looking at the overridable methods on the SQLMembershipProvider there is at least one that I think I'm going to have to override in order to get this puppy to work:

byte[] EncryptPassword(byte[] password)

I'll also have to change the aspnet_Membership.Password field cope with the newly hashed password, currently it's only nvarchar(128).

I was hoping that someone with a little more experience on extending the SqlMembershipProvider might be able to give me some pointers.

Thanks.

note: Although I'm using the .net 2.0 membership provider, I'm actually running .net 3.5


问:
Detect and Fill any Webpage form with Selenium-Python
I'm kind of new to Selenium testing. I want to use Selenium to detect forms in any webpage and also fill them. I don't want to be restricted to a single webpage like having to inspect the page or view page source to get an id or name or Xpath.

I just want to be able to input any webpage URL, selenium should detect a form, fill it and submit. For example, a registration or login form in any webpage. Thanks.

NB: I'm working with python please.

答:
There are no out of the box solutions, as far as I know, for your stated problem. Mainly because your problem is too broad.

Selenium can't detect "forms" unless you tell it what forms are. To do that you need to find an identifiable CSS or XPATH selector for all the elements on any webpage that could qualify as a form input field.

Furthermore, filling every possible input field in a form with acceptable input is something you can only do if you know how a webpage classifies "good" and "bad" input. Selenium can't make that choice for you.

Submitting a form can be done in multiple ways, most webpages use a "Submit" or similar button. Selenium can't automatically detect that button is and press it for you, you need to tell it where that button is on the page via a selector.

I would suggest reading a bit more on what Selenium is and what it can do. There are multiple python/selenium tutorials available. I would first start reading about the bindings available in the python implementation for Selenium if you chose python to be your scripting language of choice for your work. http://selenium-python.readthedocs.io/index.html


问:
How to set Jmeter home in pom.xml?
The following is my pom.xml

```<code>  <build>
    <plugins>
      <plugin>
        <groupId>com.lazerycode.jmeter</groupId>
        <artifactId>jmeter-maven-plugin</artifactId>
        <version>2.2.0</version>
        <executions>
          <execution>
            <id>jmeter-tests</id>
            <goals>
              <goal>jmeter</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <propertiesJMeter>

          </propertiesJMeter>
        </configuration>
      </plugin>
    </plugins>
  </build>
</code>```

When I run the .jmx, I get the following message:

Error: Could not find or load main class org.apache.jmeter.NewDriver

I notice that the classpath for org.apache.jmeter.NewDriver is wrong. How do I set it to Jmeter's home in the pom.xml, or in the .jmx file?

答:
There is no such concept as JMeter home when it comes to executing tests via Maven plugin, all you need to do is to:

Set up your pom.xml file to look like:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.blazemeter</groupId>
  <artifactId>mvn-jmeter</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>maven-jmeter-demo</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <groupId>com.lazerycode.jmeter</groupId>
        <artifactId>jmeter-maven-plugin</artifactId>
        <version>2.2.0</version>
        <executions>
          <execution>
            <id>jmeter-tests</id>
            <phase>verify</phase>
            <goals>
              <goal>jmeter</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

Set up your project to look like:

src

test

jmeter

test.jmx

here you can put another jmx if needed

pom.xml

Run your test like mvn clean verify

JMeter Maven plugin will download JMeter along with dependencies (you will be able to find in under target/jmeter folder along with JMeter logs (logs folder) and test results (results folder)

More information:

JMeter Maven Plugin - official documentation

JMeter Maven Plugin - JMeter Wiki

Five Ways To Launch a JMeter Test without Using the JMeter GUI - aggregate information on different approaches to running a headless JMeter inlcuding (but not limited to) Maven Plugin

Title: How to set Jmeter home in pom.xml?

Body:
The following is my pom.xml

  <build>
    <plugins>
      <plugin>
        <groupId>com.lazerycode.jmeter</groupId>
        <artifactId>jmeter-maven-plugin</artifactId>
        <version>2.2.0</version>
        <executions>
          <execution>
            <id>jmeter-tests</id>
            <goals>
              <goal>jmeter</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <propertiesJMeter>

          </propertiesJMeter>
        </configuration>
      </plugin>
    </plugins>
  </build>

When I run the .jmx, I get the following message:

Error: Could not find or load main class org.apache.jmeter.NewDriver

I notice that the classpath for org.apache.jmeter.NewDriver is wrong. How do I set it to Jmeter's home in the pom.xml, or in the .jmx file?

Body:
There is no such concept as JMeter home when it comes to executing tests via Maven plugin, all you need to do is to:

Set up your pom.xml file to look like:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.blazemeter</groupId>
  <artifactId>mvn-jmeter</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>maven-jmeter-demo</name>
  <url>http://maven.apache.org</url>
  <build>
    <plugins>
      <plugin>
        <groupId>com.lazerycode.jmeter</groupId>
        <artifactId>jmeter-maven-plugin</artifactId>
        <version>2.2.0</version>
        <executions>
          <execution>
            <id>jmeter-tests</id>
            <phase>verify</phase>
            <goals>
              <goal>jmeter</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Set up your project to look like:

src

test

jmeter

test.jmx

here you can put another jmx if needed

pom.xml

Run your test like mvn clean verify

JMeter Maven plugin will download JMeter along with dependencies (you will be able to find in under target/jmeter folder along with JMeter logs (logs folder) and test results (results folder)

More information:

JMeter Maven Plugin - official documentation

JMeter Maven Plugin - JMeter Wiki

Five Ways To Launch a JMeter Test without Using the JMeter GUI - aggregate information on different approaches to running a headless JMeter inlcuding (but not limited to) Maven Plugin


答:
Have a look at the documentation here

You probably want to do something like:

```<code>all_inputs = driver.find_elements_by_tag_name("input")
for input in all_inputs:
   input.sendKeys("my password")
</code>```

Title: Detect and Fill any Webpage form with Selenium-Python

Body:
I'm kind of new to Selenium testing. I want to use Selenium to detect forms in any webpage and also fill them. I don't want to be restricted to a single webpage like having to inspect the page or view page source to get an id or name or Xpath.

I just want to be able to input any webpage URL, selenium should detect a form, fill it and submit. For example, a registration or login form in any webpage. Thanks.

NB: I'm working with python please.

Body:
Have a look at the documentation here

You probably want to do something like:

all_inputs = driver.find_elements_by_tag_name("input")
for input in all_inputs:
   input.sendKeys("my password")


答:
With

```<code>for i in l
</code>```

i will takes the values inside l and not its index. (i.e. i=1995, then i=1996...) Obviously the list l does not have that many elements

What you want is:

```<code>for i, li in enumerate(l):
    print(i,li)
#(0, 1995)
#(1, 1996)
#(2, 1997)
#...
</code>```

Title: Python3 print, IndexError: list index out of range

Body:
My code

for i in l:
    print (("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);") %(l[i]))

My list

l=[1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016]

What I got in Jupyter
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-11-6f78605f79c5> in <module>()
      1 for i in l:
----> 2     print (("ALTER TABLE jul ADD COLUMN %i VARCHAR(256);") %(l[i]))

IndexError: list index out of range

Body:
With

for i in l

i will takes the values inside l and not its index. (i.e. i=1995, then i=1996...) Obviously the list l does not have that many elements

What you want is:

for i, li in enumerate(l):
    print(i,li)
#(0, 1995)
#(1, 1996)
#(2, 1997)
#...


问:
unable to validate email and number
I need help because I have added the following javascript(mentioned below in code) to my form and I am passing ID to js, but unable to validate it.

Javascript Code

```<code>function validateForm() {
    var x = document.getElementById('emailid').value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    var txt = document.getElementById('mobNo');
    var filter = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;
    var test_bool = filter.test(txt.value);
    if (test_bool == false) {
        alert('Please enter valid Mobile Number ');
        txt.focus();
        return false;
    }
}
</code>```

HTML

```<code><div class="form-group">
    <input type="email" class="form-control" value="" placeholder="Email ID" id="emailid" name="Email" required="required" maxlength="70" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>
<div class="form-group">
    <input type="text" class="form-control" value="" placeholder="Mobile Number" id="mobNo" name="number" required="required" maxlength="14" />
    <label class="input-field-icon icon-email" for="login-email"></label>
</div>
</code>```

答:
You can validate user inputs easily with regular expressions. Make sure to call your JavaScript when the form is submitted.

HTML

```<code><form onSubmit="myFunction()">
Email Address: <input type="email" id="userEmail" name="email" placeholder="Enter a valid email address" required>
</form>
</code>```

JavaScript

```<code>function myFunction(){
 var email = document.getElementById('userEmail').value;
 if(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)){
    alert('Valid');
 }else{
    alert('Invalid');
 }
}
</code>```

Result

```<code>Input: 'email@email.com' Result: 'Valid"
Input: 'email@email'     Result: 'Invalid'
</code>```

Title: unable to validate email and number

Body:
I need help because I have added the following javascript(mentioned below in code) to my form and I am passing ID to js, but unable to validate it.

Javascript Code

function validateForm() {
    var x = document.getElementById('emailid').value;
    var atpos = x.indexOf("@");
    var dotpos = x.lastIndexOf(".");
    if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
        alert("Not a valid e-mail address");
        return false;
    }
    var txt = document.getElementById('mobNo');
    var filter = /^([0]|\+91|\+91-|\+91\s)?\d{10}/;
    var test_bool = filter.test(txt.value);
    if (test_bool == false) {
        alert('Please enter valid Mobile Number ');
        txt.focus();
        return false;
    }
}

HTML

    <input type="email" class="form-control" value="" placeholder="Email ID" id="emailid" name="Email" required="required" maxlength="70" />

    <input type="text" class="form-control" value="" placeholder="Mobile Number" id="mobNo" name="number" required="required" maxlength="14" />

Body:
You can validate user inputs easily with regular expressions. Make sure to call your JavaScript when the form is submitted.

HTML

<form onSubmit="myFunction()">
Email Address: <input type="email" id="userEmail" name="email" placeholder="Enter a valid email address" required>
</form>

JavaScript

function myFunction(){
 var email = document.getElementById('userEmail').value;
 if(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email)){
    alert('Valid');
 }else{
    alert('Invalid');
 }
}

Result

Input: 'email@email.com' Result: 'Valid"
Input: 'email@email'     Result: 'Invalid'


问:
Detect overlapping date ranges from the same table
I have a table with the following data

```<code>PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010  31/01/2010  S
03    05/01/2010  06/01/2010  A
</code>```

And want to get the following results

```<code>PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
03    05/01/2010  06/01/2010  A
</code>```

Any ideas on where to start? A lot of the reading I've done suggests I need to create entries and for each day and join on matching days, is this the only way?

答:
Perhaps:</p>

```<code>SELECT A.PKey, A.Start, A.End, A.Type
FROM calendar AS A, calendar AS B
WHERE (p.pkey<>a.pkey
AND b.start>=a.start
AND b.end<=a.end)
OR (b.pkey<>a.pkey
AND b.start<=a.start
AND b.end>=a.end)
</code>```

Body:
I have a table with the following data

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
02    15/01/2010  31/01/2010  S
03    05/01/2010  06/01/2010  A

And want to get the following results

PKey  Start       End         Type
====  =====       ===         ====
01    01/01/2010  14/01/2010  S
03    05/01/2010  06/01/2010  A

Any ideas on where to start? A lot of the reading I've done suggests I need to create entries and for each day and join on matching days, is this the only way?

Body:
Perhaps:

SELECT A.PKey, A.Start, A.End, A.Type
FROM calendar AS A, calendar AS B
WHERE (p.pkey<>a.pkey
AND b.start>=a.start
AND b.end<=a.end)
OR (b.pkey<>a.pkey
AND b.start<=a.start
AND b.end>=a.end)


问:
RabbitMQ REST HTTP JSON payload
I am trying to use RabbitMQ HTTP REST client to publish messages into the queue. I am using the following url and request

http://xxxx/api/exchanges/xxxx/exc.notif/publish

```<code>{
 "routing_key":"routing.key",
  "payload":{

  },
 "payload_encoding":"string",
 "properties":{
   "headers":{
     "notif_d":"TEST",
     "notif_k": ["example1", "example2"],
     "userModTime":"timestamp"
   }
 }
}
</code>```

And getting back from the rabbit the following response:

```<code>{"error":"bad_request","reason":"payload_not_string"}
</code>```

I have just one header set:

```<code>Content-Type:application/json
</code>```

I was trying to set the

```<code>"payload_encoding":"base64",
</code>```

but it didn't help. I am new to rabbit any response is welcome.

答:
Try with </p>

```<code>{
"properties": {
"content-type": "application/json"
},
"routing_key": "testKey",
"payload": "1234",
"payload_encoding": "string"
}
</code>```

Title: RabbitMQ REST HTTP JSON payload

Body:
I am trying to use RabbitMQ HTTP REST client to publish messages into the queue. I am using the following url and request

http://xxxx/api/exchanges/xxxx/exc.notif/publish

{
 "routing_key":"routing.key",
  "payload":{

  },
 "payload_encoding":"string",
 "properties":{
   "headers":{
     "notif_d":"TEST",
     "notif_k": ["example1", "example2"],
     "userModTime":"timestamp"
   }
 }
}

And getting back from the rabbit the following response:

{"error":"bad_request","reason":"payload_not_string"}

I have just one header set:

Content-Type:application/json

I was trying to set the

"payload_encoding":"base64",

but it didn't help. I am new to rabbit any response is welcome.

Body:
Try with

{
"properties": {
"content-type": "application/json"
},
"routing_key": "testKey",
"payload": "1234",
"payload_encoding": "string"
}


问:
Changing ListBox's ItemsPanelTemplate At Runtime
I would like to have ListBox's ItemsPanelTemplate change during runtime.

I have the following XAML which allows me to change the ItemsPanelTemplate; however has the unwanted side effect of breaking the ScrollViewer.

```<code>xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ie="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"

...

<UserControl.Resources>
    <ItemsPanelTemplate x:Key="StackPanelTemplate">
        <VirtualizingStackPanel/>
    </ItemsPanelTemplate>

    <ItemsPanelTemplate x:Key="WrapPanelTemplate">
        <telerik:RadWrapPanel/>
    </ItemsPanelTemplate>
</UserControl.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <StackPanel>
        <Button Content="StackPanel">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ie:ChangePropertyAction TargetName="TargetListBox" PropertyName="ItemsPanel" Value="{StaticResource StackPanelTemplate}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
        <Button Content="WrapPanel">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ie:ChangePropertyAction TargetName="TargetListBox" PropertyName="ItemsPanel" Value="{StaticResource WrapPanelTemplate}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
    </StackPanel>

    <ListBox x:Name="TargetListBox" Grid.Column="1" ItemsSource="{Binding SomeCollection}"/>
</Grid>
</code>```

When you change the ItemsPanelTemplate this way. The ScrollViewer seems to stay in whatever state it was in before you changed it and using the scroll bar does not effect any change on the ListBox.

Can anyone provide any insight on this issue or perhaps provide a workaround?

Thank you.

* EDIT *

So, I've narrowed the problem down to it being related to virtualization. If you change the VirtualizingStackPanel for just a regular StackPanel the ScrollViewer does not break. This isn't really a solution for me though as this ListBox will hold many hundreds of search results.

答:
well I was facing the same problem I wanted to create a ListBox that have products and make user free to change the layout from WrapPanel to List box and from ListBox to WrapPanel. so to do this you should use styles. (I recommend you to use ListView not ListBox because of scrolling issues in ListBox. anyway both will work).
at first add your 2 styles inside  in your app.xaml

WrapPanelTemplateLV

```<code><Style x:Key="WrapPanelTemplateLV" TargetType="ListView">
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <WrapPanel />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

and StackPanelTemplateLV

```<code><Style x:Key="StackPanelLV" TargetType="ListBox">
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <StackPanel />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

now inside your button just do this

```<code>// StackPanelLV is on my App.xaml
            MyListView.Style = (Style)Application.Current.Resources["StackPanelLV"];
</code>```

and now you got the idea. make some logic to switch between the 2 styles.
I recommend you to go to this question for more.
Changing the styles at runtime in WPF

Body:
I would like to have ListBox's ItemsPanelTemplate change during runtime.

I have the following XAML which allows me to change the ItemsPanelTemplate; however has the unwanted side effect of breaking the ScrollViewer.

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ie="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"

...

<UserControl.Resources>
    <ItemsPanelTemplate x:Key="StackPanelTemplate">
        <VirtualizingStackPanel/>
    </ItemsPanelTemplate>

    <ItemsPanelTemplate x:Key="WrapPanelTemplate">
        <telerik:RadWrapPanel/>
    </ItemsPanelTemplate>
</UserControl.Resources>

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <StackPanel>
        <Button Content="StackPanel">

                    <ie:ChangePropertyAction TargetName="TargetListBox" PropertyName="ItemsPanel" Value="{StaticResource StackPanelTemplate}"/>

        </Button>
        <Button Content="WrapPanel">

                    <ie:ChangePropertyAction TargetName="TargetListBox" PropertyName="ItemsPanel" Value="{StaticResource WrapPanelTemplate}"/>

        </Button>
    </StackPanel>

    <ListBox x:Name="TargetListBox" Grid.Column="1" ItemsSource="{Binding SomeCollection}"/>
</Grid>

When you change the ItemsPanelTemplate this way. The ScrollViewer seems to stay in whatever state it was in before you changed it and using the scroll bar does not effect any change on the ListBox.

Can anyone provide any insight on this issue or perhaps provide a workaround?

Thank you.

* EDIT *

So, I've narrowed the problem down to it being related to virtualization. If you change the VirtualizingStackPanel for just a regular StackPanel the ScrollViewer does not break. This isn't really a solution for me though as this ListBox will hold many hundreds of search results.

Body:
well I was facing the same problem I wanted to create a ListBox that have products and make user free to change the layout from WrapPanel to List box and from ListBox to WrapPanel. so to do this you should use styles. (I recommend you to use ListView not ListBox because of scrolling issues in ListBox. anyway both will work).
at first add your 2 styles inside  in your app.xaml

WrapPanelTemplateLV

<Style x:Key="WrapPanelTemplateLV" TargetType="ListView">
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <WrapPanel />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>

and StackPanelTemplateLV

<Style x:Key="StackPanelLV" TargetType="ListBox">
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <StackPanel />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>

now inside your button just do this

// StackPanelLV is on my App.xaml
            MyListView.Style = (Style)Application.Current.Resources["StackPanelLV"];

and now you got the idea. make some logic to switch between the 2 styles.
I recommend you to go to this question for more.
Changing the styles at runtime in WPF


问:
How to concatenate multiple pandas.DataFrames without running into MemoryError
I have three DataFrames that I'm trying to concatenate.

```<code>concat_df = pd.concat([df1, df2, df3])
</code>```

This results in a MemoryError. How can I resolve this?

Note that most of the existing similar questions are on MemoryErrors occuring when reading large files. I don't have that problem. I have read my files in into DataFrames. I just can't concatenate that data.

答:
I've had a similar performance issues while trying to concatenate a large number of DataFrames to a 'growing' DataFrame.

My workaround was appending all sub DataFrames to a list, and then concatenating the list of DataFrames once processing of the sub DataFrames has been completed. This will bring the runtime to almost half.

Body:
I have three DataFrames that I'm trying to concatenate.

concat_df = pd.concat([df1, df2, df3])

This results in a MemoryError. How can I resolve this?

Note that most of the existing similar questions are on MemoryErrors occuring when reading large files. I don't have that problem. I have read my files in into DataFrames. I just can't concatenate that data.


问:
Make jackson serialize apache commons Pair
How can I make jackson, if even possible without making my own complex serializer of org.apache.commons.lang3.tuple.Pair, to serialize both my left and right object in a proper way. So for example I have to following code:

```<code> public class MyPairTest {

    public static void main(String[] args) {
        Address address1 = new Address("Axel Street 1", "London");
        Address address2 = new Address("Axel Street 2", "Copenhagen");

        Map<String, Pair> map = new HashMap<>();
        map.put("Address", Pair.of(address1, address2));

        Pair p = Pair.of(address1, address2);

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        try {
            String serializeMapWithPair = mapper.writeValueAsString(map);
            String serializePair = mapper.writeValueAsString(p);
            System.out.println(serializeMapWithPair);
            System.out.println(serializePair);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();
        System.out.println(gson.toJson(p));
    }
}
</code>```

And the resulting output is:

```<code>{
  "Address" : {
    "com.example.api.beans.Address@224edc67" : {
      "street" : "Axel Street 2",
      "city" : "Copenhagen"
    }
  }
}
{
  "com.example.api.beans.Address@224edc67" : {
    "street" : "Axel Street 2",
    "city" : "Copenhagen"
  }
}
{"left":{"street":"Axel Street 1","city":"London"},"right":{"street":"Axel Street 2","city":"Copenhagen"}}
</code>```

So the first two outputs are serializing Pair with jackson ObjectMapper where as the last is with Gson, I want to achieve the result as in the Gson example, but with jackson and without the left and right part. The Gson example I got from this jira improvement suggestion and I know that they state the following "Commons-lang has no dependencies, so Jackson or anything similar can not be used." But was wondering if Jackson them self have made a serializer or the kind for this, cannot find anything like it out there so maybe there is no simple solution to this with jackson? Or should I just drop it and use Gson, and then just manually manipulate and remove the left and right parts?

答:
Anyhow I think that I will just go with implementing my own generic class with a before and after field and then serialize that, works even how I want it to be in the end, so I end up with something like the following class:

```<code>public class MyPair<T> {
    private T before;
    private T after;

    private MyPair(T before, T after) {
        this.before = before;
        this.after = after;
    }

    public static <T> MyPair<T> of(final T before, final T after) {
        return new MyPair<>(before, after);
    }

    public T getBefore() {
        return this.before;
    }

    public T getAfter() {
        return this.after;
    }

    public void setBefore(T before) {
        this.before = before;
    }

    public void setAfter(T after) {
        this.after = after;
    }
}
</code>```

and then I can just call MyPair.of(address1, address2) and get that serialized as

```<code>{
  "Address" : {
    "before" : {
      "street" : "Axel Street 1",
      "city" : "London"
    },
    "after" : {
      "street" : "Axel Street 2",
      "city" : "Copenhagen"
    }
  }
}
</code>```

Which is what I was expecting :). Just need to make sure that it is called with the same object type, else throw compile-time error, seems that does not work because right now of() can be called with two different types.

Body:
How can I make jackson, if even possible without making my own complex serializer of org.apache.commons.lang3.tuple.Pair, to serialize both my left and right object in a proper way. So for example I have to following code:

 public class MyPairTest {

    public static void main(String[] args) {
        Address address1 = new Address("Axel Street 1", "London");
        Address address2 = new Address("Axel Street 2", "Copenhagen");

        Map<String, Pair> map = new HashMap<>();
        map.put("Address", Pair.of(address1, address2));

        Pair p = Pair.of(address1, address2);

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        try {
            String serializeMapWithPair = mapper.writeValueAsString(map);
            String serializePair = mapper.writeValueAsString(p);
            System.out.println(serializeMapWithPair);
            System.out.println(serializePair);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();
        System.out.println(gson.toJson(p));
    }
}

And the resulting output is:

{
  "Address" : {
    "com.example.api.beans.Address@224edc67" : {
      "street" : "Axel Street 2",
      "city" : "Copenhagen"
    }
  }
}
{
  "com.example.api.beans.Address@224edc67" : {
    "street" : "Axel Street 2",
    "city" : "Copenhagen"
  }
}
{"left":{"street":"Axel Street 1","city":"London"},"right":{"street":"Axel Street 2","city":"Copenhagen"}}

So the first two outputs are serializing Pair with jackson ObjectMapper where as the last is with Gson, I want to achieve the result as in the Gson example, but with jackson and without the left and right part. The Gson example I got from this jira improvement suggestion and I know that they state the following "Commons-lang has no dependencies, so Jackson or anything similar can not be used." But was wondering if Jackson them self have made a serializer or the kind for this, cannot find anything like it out there so maybe there is no simple solution to this with jackson? Or should I just drop it and use Gson, and then just manually manipulate and remove the left and right parts?

Body:
Anyhow I think that I will just go with implementing my own generic class with a before and after field and then serialize that, works even how I want it to be in the end, so I end up with something like the following class:

public class MyPair<T> {
    private T before;
    private T after;

    private MyPair(T before, T after) {
        this.before = before;
        this.after = after;
    }

    public static <T> MyPair<T> of(final T before, final T after) {
        return new MyPair<>(before, after);
    }

    public T getBefore() {
        return this.before;
    }

    public T getAfter() {
        return this.after;
    }

    public void setBefore(T before) {
        this.before = before;
    }

    public void setAfter(T after) {
        this.after = after;
    }
}

and then I can just call MyPair.of(address1, address2) and get that serialized as

{
  "Address" : {
    "before" : {
      "street" : "Axel Street 1",
      "city" : "London"
    },
    "after" : {
      "street" : "Axel Street 2",
      "city" : "Copenhagen"
    }
  }
}

Which is what I was expecting :). Just need to make sure that it is called with the same object type, else throw compile-time error, seems that does not work because right now of() can be called with two different types.


问:
What is "epoch" in keras.models.Model.fit?
What is "epoch" in keras.models.Model.fit? Is it one gradient update? If it is more than one gradient update, then what is defining an epoch?

Suppose I am feeding my own batches to fit. I would regard "epoch" as finishing to process entire training set (is this correct)? Then how to control keras for this way? Can I set batch_size equal to x and y size and epochs to 1?

答:
Here is how Keras documentation defines an epoch:

Epoch: an arbitrary cutoff, generally defined as "one pass over the entire dataset", used to separate training into distinct phases, which is useful for logging and periodic evaluation.

So, in other words, a number of epochs means how many times you go through your training set.

The model is updated each time a batch is processed, which means that it can be updated multiple times during one epoch. If batch_size is set equal to the length of x, then the model will be updated once per epoch.