问:
Registering in Discovery Service for multiple IPs
We are using Netflix OSS in our current project which is about to go live within a few weeks. Everything was good until last week. services were getting registered in discovery, the gateway was able to route traffic to required services, the portal was working fine. But when a backup NIC card is installed in each of the servers. When I am restarting the services, the services are getting registered with 2nd nat IP address (10.1.220.125), instead of the hostname (earlier it used to be). I searched google and found many configurations, but when I applied I am not getting the successful/expected result. One such configuration is as below:

```<code>spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - p2p.*
</code>```

Here is my application.yml file of the discovery server.

```<code>spring:
  application:
    name: discovery-service
server:
  port: 8761

eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://10.1.115.8:8761/eureka/
  instance:
    registryFetchIntervalSeconds: 30
    leaseRenewalIntervalInSeconds: 10
    leaseExpirationDurationInSeconds: 30

zuul.sensitiveHeaders:

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: THREAD
          thread:
            timeoutInMilliseconds: 500000
spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - p2p.*
</code>```

When I see the log, I see that discovery-service is being registered like below:

```<code>Registered instance DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 with status UP (replication=false)
DiscoveryClient_DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 - registration status: 204
Registered instance DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 with status UP (replication=true)
</code>```

Where 10.1.220.125 is the new nat IP.

Earlier I used to get the message in log when there was only one nat IP (10.1.115.8) and no backup IP:

```<code>Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=false)
DiscoveryClient_DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 - registration status: 204
Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=true)
</code>```

Where KOLSRV1 is the server host name having IP 10.1.115.8 and 10.1.220.125.

How can I register my services with host name instead of IP?

We are using Dalston.SR1 version of spring cloud.

Edited: With verion Greenwich.RC2

```<code>server:
  port: 8761

eureka:
  environment: prod
  client:
    registerWithEureka: true
    fetchRegistry: true
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://10.1.115.8:8761/eureka/
  instance:
    registryFetchIntervalSeconds: 30
    leaseRenewalIntervalInSeconds: 10
    leaseExpirationDurationInSeconds: 30
    hostname: KOLSRV1
    ip-address: 10.1.115.8
    preferIpAddress: false
    #preferredNic: bond0
    #forceHostAddress: 10.1.115.8

zuul.sensitiveHeaders:

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: THREAD
          thread:
            timeoutInMilliseconds: 500000

spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - p2p.*
</code>```

I am getting the below error:

```<code>Request execution failed with message: A message body reader for Java class com.netflix.appinfo.InstanceInfo, and Java type class com.netflix.appinfo.InstanceInfo, and MIME media type text/html; charset=utf-8 was not found
DiscoveryClient_DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 - was unable to send heartbeat!
</code>```

For your reference, I am providing the ifconfig details of the server.

```<code>[user@KOLSRV1 ~]$ ifconfig
bond0: flags=5187<UP,BROADCAST,RUNNING,MASTER,MULTICAST>  mtu 1500
        inet 10.1.115.8  netmask 255.255.255.128  broadcast 10.1.115.127
        ether 00:0a:f7:e7:88:40  txqueuelen 1000  (Ethernet)
        RX packets 976056244  bytes 249957809358 (232.7 GiB)
        RX errors 0  dropped 0  overruns 0  frame 193559
        TX packets 937501062  bytes 243749426487 (227.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

em1: flags=6211<UP,BROADCAST,RUNNING,SLAVE,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:40  txqueuelen 1000  (Ethernet)
        RX packets 975667166  bytes 249931945975 (232.7 GiB)
        RX errors 0  dropped 0  overruns 0  frame 193559
        TX packets 937501062  bytes 243749426487 (227.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

em2: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:41  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

em3: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:3e  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 16

em4: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:3f  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 17

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 23915308  bytes 7603519514 (7.0 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 23915308  bytes 7603519514 (7.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

p2p1: flags=6211<UP,BROADCAST,RUNNING,SLAVE,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:40  txqueuelen 1000  (Ethernet)
        RX packets 389078  bytes 25863383 (24.6 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

p2p2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.1.220.125  netmask 255.255.254.0  broadcast 10.1.221.255
        ether 00:0a:f7:f3:03:01  txqueuelen 1000  (Ethernet)
        RX packets 81021  bytes 14512406 (13.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 196820  bytes 265515182 (253.2 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:ad:3c:27  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[user@KOLSRV1 ~]$
</code>```

Update 2

pom.xml

```<code><?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>
    <artifactId>discovery-service</artifactId>
    <name>discovery-service</name>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-eureka-server</artifactId>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>discovery-service</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>application.yml</exclude>
                    <exclude>*.xml</exclude>
                    <exclude>*.properties</exclude>
                </excludes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.sample.DiscoveryServiceApplication</mainClass>
                    <addResources>true</addResources>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <argLine>${argLine} -noverify</argLine>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
</project>
</code>```

bootstrap.yml

```<code>spring:
  application:
    name: discovery-service
</code>```

MainApplication

```<code>@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(DiscoveryServiceApplication.class, args);
    }
}
</code>```

答:
@spencergib, I found the solution.

In /etc/hosts file I put the entry like,

```<code>KOLSRV1   10.1.220.125
</code>```

Now the services are getting registered in discovery services using name instead of IP.

```<code>Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=false)
DiscoveryClient_DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 - registration status: 204
Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=true)
</code>```

Thanks..

Body:
We are using Netflix OSS in our current project which is about to go live within a few weeks. Everything was good until last week. services were getting registered in discovery, the gateway was able to route traffic to required services, the portal was working fine. But when a backup NIC card is installed in each of the servers. When I am restarting the services, the services are getting registered with 2nd nat IP address (10.1.220.125), instead of the hostname (earlier it used to be). I searched google and found many configurations, but when I applied I am not getting the successful/expected result. One such configuration is as below:

spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - p2p.*

Here is my application.yml file of the discovery server.

spring:
  application:
    name: discovery-service
server:
  port: 8761

eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://10.1.115.8:8761/eureka/
  instance:
    registryFetchIntervalSeconds: 30
    leaseRenewalIntervalInSeconds: 10
    leaseExpirationDurationInSeconds: 30

zuul.sensitiveHeaders:

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: THREAD
          thread:
            timeoutInMilliseconds: 500000
spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - p2p.*

When I see the log, I see that discovery-service is being registered like below:

Registered instance DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 with status UP (replication=false)
DiscoveryClient_DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 - registration status: 204
Registered instance DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 with status UP (replication=true)

Where 10.1.220.125 is the new nat IP.

Earlier I used to get the message in log when there was only one nat IP (10.1.115.8) and no backup IP:

Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=false)
DiscoveryClient_DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 - registration status: 204
Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=true)

Where KOLSRV1 is the server host name having IP 10.1.115.8 and 10.1.220.125.

How can I register my services with host name instead of IP?

We are using Dalston.SR1 version of spring cloud.

Edited: With verion Greenwich.RC2

server:
  port: 8761

eureka:
  environment: prod
  client:
    registerWithEureka: true
    fetchRegistry: true
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://10.1.115.8:8761/eureka/
  instance:
    registryFetchIntervalSeconds: 30
    leaseRenewalIntervalInSeconds: 10
    leaseExpirationDurationInSeconds: 30
    hostname: KOLSRV1
    ip-address: 10.1.115.8
    preferIpAddress: false
    #preferredNic: bond0
    #forceHostAddress: 10.1.115.8

zuul.sensitiveHeaders:

hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: THREAD
          thread:
            timeoutInMilliseconds: 500000

spring:
  cloud:
    inetutils:
      ignoredInterfaces:
        - p2p.*

I am getting the below error:

Request execution failed with message: A message body reader for Java class com.netflix.appinfo.InstanceInfo, and Java type class com.netflix.appinfo.InstanceInfo, and MIME media type text/html; charset=utf-8 was not found
DiscoveryClient_DISCOVERY-SERVICE/10.1.220.125:discovery-service:8761 - was unable to send heartbeat!

For your reference, I am providing the ifconfig details of the server.

[user@KOLSRV1 ~]$ ifconfig
bond0: flags=5187<UP,BROADCAST,RUNNING,MASTER,MULTICAST>  mtu 1500
        inet 10.1.115.8  netmask 255.255.255.128  broadcast 10.1.115.127
        ether 00:0a:f7:e7:88:40  txqueuelen 1000  (Ethernet)
        RX packets 976056244  bytes 249957809358 (232.7 GiB)
        RX errors 0  dropped 0  overruns 0  frame 193559
        TX packets 937501062  bytes 243749426487 (227.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

em1: flags=6211<UP,BROADCAST,RUNNING,SLAVE,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:40  txqueuelen 1000  (Ethernet)
        RX packets 975667166  bytes 249931945975 (232.7 GiB)
        RX errors 0  dropped 0  overruns 0  frame 193559
        TX packets 937501062  bytes 243749426487 (227.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

em2: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:41  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

em3: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:3e  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 16

em4: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:3f  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
        device interrupt 17

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 23915308  bytes 7603519514 (7.0 GiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 23915308  bytes 7603519514 (7.0 GiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

p2p1: flags=6211<UP,BROADCAST,RUNNING,SLAVE,MULTICAST>  mtu 1500
        ether 00:0a:f7:e7:88:40  txqueuelen 1000  (Ethernet)
        RX packets 389078  bytes 25863383 (24.6 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

p2p2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.1.220.125  netmask 255.255.254.0  broadcast 10.1.221.255
        ether 00:0a:f7:f3:03:01  txqueuelen 1000  (Ethernet)
        RX packets 81021  bytes 14512406 (13.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 196820  bytes 265515182 (253.2 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 192.168.122.1  netmask 255.255.255.0  broadcast 192.168.122.255
        ether 52:54:00:ad:3c:27  txqueuelen 1000  (Ethernet)
        RX packets 0  bytes 0 (0.0 B)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 0  bytes 0 (0.0 B)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

[user@KOLSRV1 ~]$

Update 2

pom.xml

<?xml version="1.0"?>
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>
    <artifactId>discovery-service</artifactId>
    <name>discovery-service</name>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-eureka-server</artifactId>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>discovery-service</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>application.yml</exclude>
                    <exclude>*.xml</exclude>
                    <exclude>*.properties</exclude>
                </excludes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.sample.DiscoveryServiceApplication</mainClass>
                    <addResources>true</addResources>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <argLine>${argLine} -noverify</argLine>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
</project>

bootstrap.yml

spring:
  application:
    name: discovery-service

MainApplication

@SpringBootApplication
@EnableEurekaServer
public class DiscoveryServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(DiscoveryServiceApplication.class, args);
    }
}

Body:
@spencergib, I found the solution.

In /etc/hosts file I put the entry like,

KOLSRV1   10.1.220.125

Now the services are getting registered in discovery services using name instead of IP.

Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=false)
DiscoveryClient_DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 - registration status: 204
Registered instance DISCOVERY-SERVICE/KOLSRV1:discovery-service:8761 with status UP (replication=true)

Thanks..


来源: stackexchange

问:
Class is giving output even when a variable is not defined globally
Define a class which will have getstring() to input a string and printstring() convert it in uppercase and another function to use __init__

```<code>class a:
    def __init__(self,b,c):
        self.b=b
        self.c=c
    def getstring(self):
        print "Please enter input"
        self.x=raw_input()
        return x
    def printstring(self):
        y=self.x.upper()
        return y
    def sum(self):
        c=self.c+self.b
        return c
d=a(23,53)
d.getstring()
d.printstring()
</code>```

The result is that the input string should be converted to uppercase. This code is working but it shouldn't as x doesn't have global scope.

Another weird thing is that if in the above code, the 'sum' function is called then the input string is not converted to upper case. It will just print the string as given in input and will give the sum.

答:
This code is working but it shouldn't as x doesn't have global scope.

x from the gettering function does not have a global scope, but self.x does, it goes with the object and you don't need to global it.

Another weird thing is that if in the above code, the 'sum' function is called then the input string is not converted to upper case. It will just print the string as given in input and will give the sum.

It still turns it into the upper case on my pc, I think it might be because you are using python 2.7 and I'm on 3.6. I suggest you switch now if you don't have a lot of projects done already because many libraries are not compatible with 2.7

ContentLicense: CC BY-SA 4.0

Body:
Define a class which will have getstring() to input a string and printstring() convert it in uppercase and another function to use __init__

class a:
    def __init__(self,b,c):
        self.b=b
        self.c=c
    def getstring(self):
        print "Please enter input"
        self.x=raw_input()
        return x
    def printstring(self):
        y=self.x.upper()
        return y
    def sum(self):
        c=self.c+self.b
        return c
d=a(23,53)
d.getstring()
d.printstring()

The result is that the input string should be converted to uppercase. This code is working but it shouldn't as x doesn't have global scope.

Another weird thing is that if in the above code, the 'sum' function is called then the input string is not converted to upper case. It will just print the string as given in input and will give the sum.


问:
how to number sequences with the same name in bed file
I have a file bed like this.

```<code>    KQ4156  0       34      Simple_repeat   .   +
    KQ4156  35      64      Simple_repeat   .   +
    KQ4156  1759    1822    Simple_repeat   .   +
    KQ4156  1901    2059    Simple_repeat   .   -
    KQ4156  2112    2258    DNA/hAT-Charlie .   +
    KQ4156  2890    2964    Simple_repeat   .   +
    KQ4156  4085    4130    DNA/hAT-Charlie .   +
    KQ4156  5587    5619    Simple_repeat   .   +
    KQ4156  5931    5995    SINE/tRNA-Deu   .   -
</code>```

for subsequent analysis I need to distinguish the same elements. es. simple_repeats_1, simple_repeats_2, etc. and DNA/hAT-Charlie_1, DNA/hAT-Charlie_2, etc.... for all of the elements.
the script used is this:

awk 'BEGIN{OFS="\t"}{if(NR>3) {if($9=="C"){strand="-"}else{strand="+"};print $5,$6-1,$7,$11,".",strand}}' file.fa.out > file.bed

how can I modify it in order to get what I'm looking for? I thought about applying paste but I don't know how to apply it for all the sequences

答:
Could you please try following.</p>

```<code>awk 'BEGIN{OFS="\t"} {$4=$4"_"++count[$4]} 1'  Input_file
</code>```

Body:
I have a file bed like this.

    KQ4156  0       34      Simple_repeat   .   +
    KQ4156  35      64      Simple_repeat   .   +
    KQ4156  1759    1822    Simple_repeat   .   +
    KQ4156  1901    2059    Simple_repeat   .   -
    KQ4156  2112    2258    DNA/hAT-Charlie .   +
    KQ4156  2890    2964    Simple_repeat   .   +
    KQ4156  4085    4130    DNA/hAT-Charlie .   +
    KQ4156  5587    5619    Simple_repeat   .   +
    KQ4156  5931    5995    SINE/tRNA-Deu   .   -

for subsequent analysis I need to distinguish the same elements. es. simple_repeats_1, simple_repeats_2, etc. and DNA/hAT-Charlie_1, DNA/hAT-Charlie_2, etc.... for all of the elements.
the script used is this:

awk 'BEGIN{OFS="\t"}{if(NR>3) {if($9=="C"){strand="-"}else{strand="+"};print $5,$6-1,$7,$11,".",strand}}' file.fa.out > file.bed

how can I modify it in order to get what I'm looking for? I thought about applying paste but I don't know how to apply it for all the sequences

Body:
Could you please try following.

awk 'BEGIN{OFS="\t"} {$4=$4"_"++count[$4]} 1'  Input_file


问:
How to capture an error from the library python litex.Regon?
I want Handling Exceptions from litex Regon (polish library with information about company). I don't know how? When i try with

When i try with this code it's ok... so i don't know why?

```<code>while True:
    try:
            x = int(input("Please enter a number: "))
            break
    except ValueError:
            print("Oops!  That was no valid number.  Try again...")
</code>```

But my code is doesn't work

## EXAMPLE
api = REGONAPI('https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc')
USER_KEY = 'my_key'
api.login(USER_KEY)
entities = api.search(nip='9222976976')
c = etree.tostring(entities[0], pretty_print=True)
c

## MY CODE
REGONAPI('https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc')
USER_KEY = 'my_key'
api.login(USER_KEY)
from litex.regon import REGONAPI
lista = []
for i in np.arange(280, 300):
        try:
            entities = api.search(nip=dane_do_przeszukwania['NIP'][i])
            c = etree.tostring(entities[0], pretty_print=True)
            lista.append(c)
        except REGONAPIError:
            None

```

<p>I have a error</p>

```EGONAPIError                             Traceback (most recent call last)
<ipython-input-7-f2653b5824bc> in <module>
      4         try:
----> 5             entities = api.search(nip=dane_do_przeszukwania['NIP'][i])
      6             c = etree.tostring(entities[0], pretty_print=True)

~\Anaconda3\lib\site-packages\litex\regon\__init__.py in search(self, nip, regon, krs, nips, regons, krss, detailed)
    210         if not result:
--> 211             raise REGONAPIError('Search failed.')
    212

REGONAPIError: Search failed.

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-7-f2653b5824bc> in <module>
      6             c = etree.tostring(entities[0], pretty_print=True)
      7             lista.append(c)
----> 8         except REGONAPIError:
      9             None
     10

NameError: name 'REGONAPIError' is not defined
```

if I do not find it number hand error and next row in iterate.

答:
REGONAPIError is not defined because you probably didn't import it.
Try adding

from litex.regon import REGONAPIError
```

in your file, this should work.

Body:
I want Handling Exceptions from litex Regon (polish library with information about company). I don't know how? When i try with

When i try with this code it's ok... so i don't know why?

while True:
    try:
            x = int(input("Please enter a number: "))
            break
    except ValueError:
            print("Oops!  That was no valid number.  Try again...")

But my code is doesn't work

## EXAMPLE
api = REGONAPI('https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc')
USER_KEY = 'my_key'
api.login(USER_KEY)
entities = api.search(nip='9222976976')
c = etree.tostring(entities[0], pretty_print=True)
c

## MY CODE
REGONAPI('https://wyszukiwarkaregon.stat.gov.pl/wsBIR/UslugaBIRzewnPubl.svc')
USER_KEY = 'my_key'
api.login(USER_KEY)
from litex.regon import REGONAPI
lista = []
for i in np.arange(280, 300):
        try:
            entities = api.search(nip=dane_do_przeszukwania['NIP'][i])
            c = etree.tostring(entities[0], pretty_print=True)
            lista.append(c)
        except REGONAPIError:
            None

I have a error

EGONAPIError                             Traceback (most recent call last)
<ipython-input-7-f2653b5824bc> in <module>
      4         try:
----> 5             entities = api.search(nip=dane_do_przeszukwania['NIP'][i])
      6             c = etree.tostring(entities[0], pretty_print=True)

~\Anaconda3\lib\site-packages\litex\regon\__init__.py in search(self, nip, regon, krs, nips, regons, krss, detailed)
    210         if not result:
--> 211             raise REGONAPIError('Search failed.')
    212

REGONAPIError: Search failed.

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-7-f2653b5824bc> in <module>
      6             c = etree.tostring(entities[0], pretty_print=True)
      7             lista.append(c)
----> 8         except REGONAPIError:
      9             None
     10

NameError: name 'REGONAPIError' is not defined

if I do not find it number hand error and next row in iterate.

Body:
REGONAPIError is not defined because you probably didn't import it.
Try adding

from litex.regon import REGONAPIError

in your file, this should work.


问:
PACT - Modify header to include oAuth2 token
I am using PACT JVM in the provider side and I need to add an oAuth2 token to the header before a request is made.
I have followed the advice in this FAQ

https://docs.pact.io/faq#how-do-i-test-oauth-or-other-security-headers

and I have created the following class:

```<code>public class TransactionPact {

    @TestTarget
    public final Target target = new HttpTarget(8332);

    private static FinanceApiToken financeApiToken;

      @BeforeClass
      public static void getAuthorisationToken() {
        HttpHeaders header = new HttpHeaders();
        header.set("Content-Type", "application/x-www-form-urlencoded");
        header.set("Authorization", "Basic ZmluLWFwaTphcGktc2VjcmV0");
        header.set("Connection", "keep-alive");
        header.set("cache-control", "no-cache");

        HttpEntity<String> request = new HttpEntity<>("username=sap&password=password2&grant_type=password", header);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<FinanceApiToken> response = restTemplate.postForEntity("http://127.0.0.1:8080/oauth/token", request, FinanceApiToken.class);

        if (response.getStatusCode() != HttpStatus.OK) {
            throw new HTTPException(response.getStatusCodeValue());
        }
        financeApiToken = response.getBody();
      }

      @State("the consumer is authorised")
      public void authorise() {

        //MODIFY HEADER HERE!
      }

    }
</code>```

However, I have no idea how to intercept a request before is made in order to modify the header and include the token.

答: Apparently @TargetRequestFilter does job. Here is the doc https://static.javadoc.io/au.com.dius/pact-jvm-provider-junit_2.11/3.2.3/au/com/dius/pact/provider/junit/TargetRequestFilter.html</p>

Body:
I am using PACT JVM in the provider side and I need to add an oAuth2 token to the header before a request is made.
I have followed the advice in this FAQ

https://docs.pact.io/faq#how-do-i-test-oauth-or-other-security-headers

and I have created the following class:

public class TransactionPact {

    @TestTarget
    public final Target target = new HttpTarget(8332);

    private static FinanceApiToken financeApiToken;

      @BeforeClass
      public static void getAuthorisationToken() {
        HttpHeaders header = new HttpHeaders();
        header.set("Content-Type", "application/x-www-form-urlencoded");
        header.set("Authorization", "Basic ZmluLWFwaTphcGktc2VjcmV0");
        header.set("Connection", "keep-alive");
        header.set("cache-control", "no-cache");

        HttpEntity<String> request = new HttpEntity<>("username=sap&password=password2&grant_type=password", header);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<FinanceApiToken> response = restTemplate.postForEntity("http://127.0.0.1:8080/oauth/token", request, FinanceApiToken.class);

        if (response.getStatusCode() != HttpStatus.OK) {
            throw new HTTPException(response.getStatusCodeValue());
        }
        financeApiToken = response.getBody();
      }

      @State("the consumer is authorised")
      public void authorise() {

        //MODIFY HEADER HERE!
      }

    }

However, I have no idea how to intercept a request before is made in order to modify the header and include the token.


问:
java.lang.IllegalStateException: Failed to load ApplicationContext ,springboot setting
The following is the error message

java.lang.IllegalStateException: Failed to load ApplicationContext

at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
  at
  org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
  at
  org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
  at
  org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
  at
  org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
  at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
  at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
  at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by:
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'wokerLogController': Unsatisfied
  dependency expressed through field 'client'; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'client' defined in class path resource
  [com/aurora/backend/config/ESConfig.class]: Bean instantiation via
  factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.elasticsearch.client.Client]: Factory method 'client'
  threw exception; nested exception is java.lang.IllegalStateException:
  availableProcessors is already set to [4], rejecting [4] at
  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
  at
  org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
  at
  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
  at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
  at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
  at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
  at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
  at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
  at
  org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)
  at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
  at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
  ... 24 more

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'client' defined in class path resource
  [com/aurora/backend/config/ESConfig.class]: Bean instantiation via
  factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.elasticsearch.client.Client]: Factory method 'client'
  threw exception; nested exception is java.lang.IllegalStateException:
  availableProcessors is already set to [4], rejecting [4] at
  org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627)
  at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
  at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1244)
  at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)
  at
  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
  ... 42 more

Caused by: org.springframework.beans.BeanInstantiationException:
  Failed to instantiate [org.elasticsearch.client.Client]: Factory
  method 'client' threw exception; nested exception is
  java.lang.IllegalStateException: availableProcessors is already set to
  [4], rejecting [4] at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
  at
  org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
  ... 55 more Caused by: java.lang.IllegalStateException:
  availableProcessors is already set to [4], rejecting [4] at
  io.netty.util.NettyRuntime$AvailableProcessorsHolder.setAvailableProcessors(NettyRuntime.java:51)
  at
  io.netty.util.NettyRuntime.setAvailableProcessors(NettyRuntime.java:87)
  at
  org.elasticsearch.transport.netty4.Netty4Utils.setAvailableProcessors(Netty4Utils.java:83)
  at
  org.elasticsearch.transport.netty4.Netty4Transport.(Netty4Transport.java:112)
  at
  org.elasticsearch.transport.Netty4Plugin.lambda$getTransports$0(Netty4Plugin.java:86)
  at
  org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:189)
  at
  org.elasticsearch.client.transport.TransportClient.(TransportClient.java:283)
  at
  org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:128)
  at
  org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:114)
  at
  org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:104)
  at com.aurora.backend.config.ESConfig.client(ESConfig.java:45) at
  com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.CGLIB$client$0()
  at
  com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a$$FastClassBySpringCGLIB$$93c49e6a.invoke()
  at
  org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
  at
  org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
  at
  com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.client()
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498) at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
  ... 56 more

A springboot project that uses elasticSearch, mysql, redis, etc.
Google has a lot, but he is just a new spingboot. The online stuff doesn't work. I don't know how to change it.

application-local.yml

```<code>server:
  port: 8000
  servlet:
    context-path: /api/v3
  error:
    whitelabel:
      enabled: false

spring:
  http:
    multipart:

    encoding:
      charset: UTF-8
      force: true
      enabled: true

  datasource:
    url: jdbc:mysql://localhost:3306/aurora?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    username: root
    password: 123456789
    driverClassName: com.mysql.jdbc.Driver
  jpa:
    database-platform: org.hibernate.dialect.MySQL57Dialect
    generate-ddl: true
    show-sql: true
  liquibase:
    change-log: classpath:db/db.master.xml
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300
      repositories:
        enabled: true
  redis:
    host: 127.0.0.1
    port: 6379
    password:
    database: 0
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
        timeout: 0
  servlet:
    multipart:
      max-file-size: 200MB # Max file size.
      max-request-size: 215MB # Max Request Size
      enabled: true

logging:
  pattern:
    file: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
    console: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
  level:
    org.springframework.web: DEBUG
    guru.springframework.controllers: DEBUG
    org.hibernate: DEBUG

app:
  wechat:
    notification: true
  design:
    root-path: /home/cloudeda/Aurora/UploadData
  jwt:
    base64-secret: NjkwNjU5ZTg0YmYxZmE0ZDJmYmFlNmMwMGNjMjJjZTc4MjFiZjkyNTk3N2IyN2M5OGQyNzg3ZTExN2M1MGYzMzNkNTg2MzMwODgzZTE3YzIwMDdhMTg1Y2M4ZWFmYmFjOGEyYWNiOTU3ZGYzNTY3NDdmMzg3ZWNjNjRmNjdjNzI=
    # Token is valid 24 hours
    token-validity-in-seconds: 86400
    token-validity-in-seconds-for-remember-me: 2592000
  id:
    data-center: 1
    machine: 1

  server:
    broker: tcp://localhost:5555
  flask:
    ibis-parser-url: http://localhost:5050/api/v3/server/parse-ibis-model
    generate-report-url: http://localhost:5050/api/v3/server/report

security:
  user:
    name: aurora
    password: aurora-monitor-password

elasticsearch:
  host: 127.0.0.1
  port: 9300
  cluster:
    name: elasticsearch
</code>```

Should be related to the configuration of the ES

ESConfig.java

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ESConfig {

    @Value("${elasticsearch.host:127.0.0.1}")
    private String host;

    @Value("${elasticsearch.port:9300}")
    private int port;

    @Value("${elasticsearch.cluster.name:elasticsearch}")
    private String clusterName;

    public String getHost() {
        return this.host;
    }

    public int getPort() {
        return this.port;
    }

    @Bean
    public Client client() {
        TransportClient client = null;

        Settings settings = Settings.builder()
            .put("cluster.name", clusterName)
            .put("client.transport.ignore_cluster_name", false)
            .build();

        try {
            client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return client;
    }
}
```

<p><strong>Controller</strong></p>

<pre class="lang-java prettyprint-override"><code>import com.aurora.backend.beans.ResultBean;
import com.aurora.backend.beans.WorkerLogBean;
import com.aurora.backend.param.SearchSimulationLogParam;
import com.aurora.backend.security.CurrentUser;
import com.aurora.backend.security.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/es")
@Slf4j
public class WokerLogController {

    @Autowired Client client;

    @PostMapping(value = "/simulation/log")
    public ResultBean getSimulationLog(
        @CurrentUser UserPrincipal user,
        @RequestBody SearchSimulationLogParam param
    ) {

        SearchResponse response = client.prepareSearch("logstash-worker")
            .setTypes("doc")
            .setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.matchQuery("logtype", 1))
            .setQuery(QueryBuilders.matchQuery("token", param.getToken()))
            .setPostFilter(
                QueryBuilders.rangeQuery("@timestamp")
                    .from(param.getStartTime()).to(param.getEndTime()))
            .get();

        SearchHit[] hits = response.getHits().getHits();
        List<WorkerLogBean> mapList = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            WorkerLogBean logBean = new WorkerLogBean();
            logBean.setId(hits[i].getId());
            logBean.setLog(hits[i].getSourceAsMap().get("log").toString());
            logBean.setMessage(hits[i].getSourceAsMap().get("message").toString());
            mapList.add(logBean);
        }
        return new ResultBean(mapList);
    }
}
</code>```

答:
This is where your exception is:

Caused by:
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'wokerLogController': Unsatisfied
  dependency expressed through field 'client'; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'client' defined in class path resource

and

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'client' defined in class path resource
  [com/aurora/backend/config/ESConfig.class]: Bean instantiation via
  factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.elasticsearch.client.Client]: Factory method 'client'
  threw exception; nested exception is java.lang.IllegalStateException:
  availableProcessors is already set to [4], rejecting [4] at

and

Caused by: org.springframework.beans.BeanInstantiationException:
  Failed to instantiate [org.elasticsearch.client.Client]: Factory
  method 'client' threw exception; nested exception is
  java.lang.IllegalStateException: availableProcessors is already set to
  [4], rejecting [4] at

This problem has been reported in this link. Haven't faced this problem with elastic search. The following might solve your problem but this might be webserver dependent. Check this.

@Component
public class ElasticSearchConfiguration implements InitializingBean {
    static {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(System.getProperty("es.set.netty.runtime.available.processors"));
    }
}
```

Body:
The following is the error message

java.lang.IllegalStateException: Failed to load ApplicationContext

at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
  at
  org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
  at
  org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
  at
  org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
  at
  org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
  at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
  at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
  at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
  at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
  at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
  at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by:
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name 'wokerLogController': Unsatisfied
  dependency expressed through field 'client'; nested exception is
  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'client' defined in class path resource
  [com/aurora/backend/config/ESConfig.class]: Bean instantiation via
  factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.elasticsearch.client.Client]: Factory method 'client'
  threw exception; nested exception is java.lang.IllegalStateException:
  availableProcessors is already set to [4], rejecting [4] at
  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
  at
  org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
  at
  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
  at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
  at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
  at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
  at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
  at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
  at
  org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127)
  at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
  at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
  ... 24 more

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'client' defined in class path resource
  [com/aurora/backend/config/ESConfig.class]: Bean instantiation via
  factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [org.elasticsearch.client.Client]: Factory method 'client'
  threw exception; nested exception is java.lang.IllegalStateException:
  availableProcessors is already set to [4], rejecting [4] at
  org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627)
  at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1288)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
  at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  at
  org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
  at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1244)
  at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)
  at
  org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
  ... 42 more

Caused by: org.springframework.beans.BeanInstantiationException:
  Failed to instantiate [org.elasticsearch.client.Client]: Factory
  method 'client' threw exception; nested exception is
  java.lang.IllegalStateException: availableProcessors is already set to
  [4], rejecting [4] at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
  at
  org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
  ... 55 more Caused by: java.lang.IllegalStateException:
  availableProcessors is already set to [4], rejecting [4] at
  io.netty.util.NettyRuntime$AvailableProcessorsHolder.setAvailableProcessors(NettyRuntime.java:51)
  at
  io.netty.util.NettyRuntime.setAvailableProcessors(NettyRuntime.java:87)
  at
  org.elasticsearch.transport.netty4.Netty4Utils.setAvailableProcessors(Netty4Utils.java:83)
  at
  org.elasticsearch.transport.netty4.Netty4Transport.(Netty4Transport.java:112)
  at
  org.elasticsearch.transport.Netty4Plugin.lambda$getTransports$0(Netty4Plugin.java:86)
  at
  org.elasticsearch.client.transport.TransportClient.buildTemplate(TransportClient.java:189)
  at
  org.elasticsearch.client.transport.TransportClient.(TransportClient.java:283)
  at
  org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:128)
  at
  org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:114)
  at
  org.elasticsearch.transport.client.PreBuiltTransportClient.(PreBuiltTransportClient.java:104)
  at com.aurora.backend.config.ESConfig.client(ESConfig.java:45) at
  com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.CGLIB$client$0()
  at
  com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a$$FastClassBySpringCGLIB$$93c49e6a.invoke()
  at
  org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
  at
  org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
  at
  com.aurora.backend.config.ESConfig$$EnhancerBySpringCGLIB$$d0b29c5a.client()
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498) at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
  ... 56 more

A springboot project that uses elasticSearch, mysql, redis, etc.
Google has a lot, but he is just a new spingboot. The online stuff doesn't work. I don't know how to change it.

application-local.yml

server:
  port: 8000
  servlet:
    context-path: /api/v3
  error:
    whitelabel:
      enabled: false

spring:
  http:
    multipart:

    encoding:
      charset: UTF-8
      force: true
      enabled: true

  datasource:
    url: jdbc:mysql://localhost:3306/aurora?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
    username: root
    password: 123456789
    driverClassName: com.mysql.jdbc.Driver
  jpa:
    database-platform: org.hibernate.dialect.MySQL57Dialect
    generate-ddl: true
    show-sql: true
  liquibase:
    change-log: classpath:db/db.master.xml
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300
      repositories:
        enabled: true
  redis:
    host: 127.0.0.1
    port: 6379
    password:
    database: 0
    lettuce:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
        timeout: 0
  servlet:
    multipart:
      max-file-size: 200MB # Max file size.
      max-request-size: 215MB # Max Request Size
      enabled: true

logging:
  pattern:
    file: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
    console: "%d{yy-MM-dd HH:mm:ss.SSS} [%thread] %-5level : %X{user} %logger{36}.%M - %msg%n"
  level:
    org.springframework.web: DEBUG
    guru.springframework.controllers: DEBUG
    org.hibernate: DEBUG

app:
  wechat:
    notification: true
  design:
    root-path: /home/cloudeda/Aurora/UploadData
  jwt:
    base64-secret: NjkwNjU5ZTg0YmYxZmE0ZDJmYmFlNmMwMGNjMjJjZTc4MjFiZjkyNTk3N2IyN2M5OGQyNzg3ZTExN2M1MGYzMzNkNTg2MzMwODgzZTE3YzIwMDdhMTg1Y2M4ZWFmYmFjOGEyYWNiOTU3ZGYzNTY3NDdmMzg3ZWNjNjRmNjdjNzI=
    # Token is valid 24 hours
    token-validity-in-seconds: 86400
    token-validity-in-seconds-for-remember-me: 2592000
  id:
    data-center: 1
    machine: 1

  server:
    broker: tcp://localhost:5555
  flask:
    ibis-parser-url: http://localhost:5050/api/v3/server/parse-ibis-model
    generate-report-url: http://localhost:5050/api/v3/server/report

security:
  user:
    name: aurora
    password: aurora-monitor-password

elasticsearch:
  host: 127.0.0.1
  port: 9300
  cluster:
    name: elasticsearch

Should be related to the configuration of the ES

ESConfig.java

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Configuration
public class ESConfig {

    @Value("${elasticsearch.host:127.0.0.1}")
    private String host;

    @Value("${elasticsearch.port:9300}")
    private int port;

    @Value("${elasticsearch.cluster.name:elasticsearch}")
    private String clusterName;

    public String getHost() {
        return this.host;
    }

    public int getPort() {
        return this.port;
    }

    @Bean
    public Client client() {
        TransportClient client = null;

        Settings settings = Settings.builder()
            .put("cluster.name", clusterName)
            .put("client.transport.ignore_cluster_name", false)
            .build();

        try {
            client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        return client;
    }
}

Controller

import com.aurora.backend.beans.ResultBean;
import com.aurora.backend.beans.WorkerLogBean;
import com.aurora.backend.param.SearchSimulationLogParam;
import com.aurora.backend.security.CurrentUser;
import com.aurora.backend.security.UserPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/es")
@Slf4j
public class WokerLogController {

    @Autowired Client client;

    @PostMapping(value = "/simulation/log")
    public ResultBean getSimulationLog(
        @CurrentUser UserPrincipal user,
        @RequestBody SearchSimulationLogParam param
    ) {

        SearchResponse response = client.prepareSearch("logstash-worker")
            .setTypes("doc")
            .setSearchType(SearchType.QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.matchQuery("logtype", 1))
            .setQuery(QueryBuilders.matchQuery("token", param.getToken()))
            .setPostFilter(
                QueryBuilders.rangeQuery("@timestamp")
                    .from(param.getStartTime()).to(param.getEndTime()))
            .get();

        SearchHit[] hits = response.getHits().getHits();
        List<WorkerLogBean> mapList = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            WorkerLogBean logBean = new WorkerLogBean();
            logBean.setId(hits[i].getId());
            logBean.setLog(hits[i].getSourceAsMap().get("log").toString());
            logBean.setMessage(hits[i].getSourceAsMap().get("message").toString());
            mapList.add(logBean);
        }
        return new ResultBean(mapList);
    }
}


问:
how to get multiple column distinct value and either diffrent field has same data in reverse
I have a table with 3 column named msg, sender and receiver. Now i need to get the distinct sender and receiver. but in here if i have sender a and receiver b Or sender b and receiver a, it is showing me both. but i want only last one.

```<code>msg | sender | receiver
hi  | 1      | 5
he  | 2      | 6
jh  | 5      |1

SELECT DSTINCT `sender`, `receiver` from `table`
</code>```

it is giving me this result

```<code>1-5
2-6
5-1
</code>```

but i need

```<code>5-1
2-6
</code>```

is there any sql query that can solve this?

答:
You can also do this using  least() and greatest() functions

```<code>select distinct least(sender , receiver), greatest(sender , receiver)
from t
</code>```

Body:
I have a table with 3 column named msg, sender and receiver. Now i need to get the distinct sender and receiver. but in here if i have sender a and receiver b Or sender b and receiver a, it is showing me both. but i want only last one.

msg | sender | receiver
hi  | 1      | 5
he  | 2      | 6
jh  | 5      |1

SELECT DSTINCT `sender`, `receiver` from `table`

it is giving me this result

1-5
2-6
5-1

but i need

5-1
2-6

is there any sql query that can solve this?

Body:
You can also do this using  least() and greatest() functions

select distinct least(sender , receiver), greatest(sender , receiver)
from t


问:
How to get string and two integers as an input in the same line
I want my input in this format    string N M

where N, M are integer value . I want this input in same line.

I have tried input().split() but it doesn't work.

```<code>alphabets  = input().split()   # what to do next
</code>```

My input format is (str, int, int).

答:
You can take strings and numbers in single line by following the below code.

Try this,

```<code>>>> alphabets = [int(v) if v.isnumeric() else v for v in input().split()]
hello 1 3
>>> alphabets
['hello', 1, 3]
</code>```

Body:
I want my input in this format    string N M

where N, M are integer value . I want this input in same line.

I have tried input().split() but it doesn't work.

alphabets  = input().split()   # what to do next

My input format is (str, int, int).

Body:
You can take strings and numbers in single line by following the below code.

Try this,

>>> alphabets = [int(v) if v.isnumeric() else v for v in input().split()]
hello 1 3
>>> alphabets
['hello', 1, 3]


问:
react-select don't show keyboard on mobile devices and prevent zoom
I'm using React-Select version 2.4.2. Testing on iOS Chrome, Firefox, Safari.

I have gone through the documentation but cannot find the correct prop to pass for this to just happen.

I want the menu to show on mobile, but not the keyboard, or any iOS native footer.
Toggling the isDisabled doesn't work, of course, since it disables the entire input and select menu.

Flipping the "searchable" prop to false DOES in fact disable the keyboard, BUT shows a footer with "Done" on Safari and Firefox, and an "X" on Chrome.

Ideally, I could just disable the input but still allow for the touch selection of the options.

Example code:

```<code>    <Select
        value={selectedOption}
        options={selectOptions}
        onChange={handleOptionSelect}
        placeholder={placeholderText}
        isDisabled={false} {/* bool toggles affect entire plugin */}
        blurInputOnSelect={true} {/* don't want any input/keyboard on mobile */}
        readonly={true} {/* tried, didn't work */}
        searchable={false} {/* disables keyboard, but still shows iOS footer with "Done" button in Safari and Firefox, and an "X" in Chrome, and zooms in when touching select element */}
    />
</code>```

答: Craig, have you tried setting the font-size of the input to 16px? This prevents zooming on iOS when focusing an input field</p>

Body:
I'm using React-Select version 2.4.2. Testing on iOS Chrome, Firefox, Safari.

I have gone through the documentation but cannot find the correct prop to pass for this to just happen.

I want the menu to show on mobile, but not the keyboard, or any iOS native footer.
Toggling the isDisabled doesn't work, of course, since it disables the entire input and select menu.

Flipping the "searchable" prop to false DOES in fact disable the keyboard, BUT shows a footer with "Done" on Safari and Firefox, and an "X" on Chrome.

Ideally, I could just disable the input but still allow for the touch selection of the options.

Example code:

    <Select
        value={selectedOption}
        options={selectOptions}
        onChange={handleOptionSelect}
        placeholder={placeholderText}
        isDisabled={false} {/* bool toggles affect entire plugin */}
        blurInputOnSelect={true} {/* don't want any input/keyboard on mobile */}
        readonly={true} {/* tried, didn't work */}
        searchable={false} {/* disables keyboard, but still shows iOS footer with "Done" button in Safari and Firefox, and an "X" in Chrome, and zooms in when touching select element */}
    />


问:
Manifest for native messaging host not found
I'm currently trying to establish a connection between a chrome-extension and a NativeMessagingHost. Everything works fine on Windows, but it won't do on Linux (either arch, kali or ubuntu).
How it fails:

Can't find manifest for native messaging host my_host.json

My current state:

have my host manifest under ~/.config/google-chrome-beta/NativeMessagingHosts/my_host.json

in there: "name":"my_host.json" and the path to my python script which handles the messages, also the unique chrome-extension code unter allowed_origins

in manifest.json of my extension given the permission for nativeMessaging

furthermore in popup.js: var port = chrome.runtime.connectNative("my_host.json"); and the same name used in sendNativeMessage

What I tried so far:

tried with google-chrome-beta and -stable

deleted file endings e.g. my_host.json to my_host, or removing the python ending

easier paths where my python script lays

also tried to put my_host into /Library/Google/Chrome/NativeMessagingHosts which typically should be the Mac path - but hey, may it worked (not..)

I get no error starting the application, copied the message from terminal whilst starting chrome with logging.
I pretty much went through the example google gave, adjusting paths etc.

Also went through differnt posts, but it seems no one has the same problem, or no one tries to do something similar.

答:
So I figured out where the problem was:
I changed the name of my host from my_host.json to com.my.host.json and set "name" to com.my.host (where I firstly had the ending .json as well, which probably caused the problem too). Furthermore I changed var port = chrome.runtime.connectNative("my_host.json") in my js-file to [...]("com.my.host") where the ending .json was not right too. Everything works now. Thank you for your suggestions!


问:
Get span Id's of selected text using getSelected()
I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a span with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.

So a simple example of a paragraph is below.

```<code><span id="p-58" class="softWord" onClick="setTranscriptPosition(-58);return false"> that </span>
<span id="p177" class="softWord" onClick="setTranscriptPosition(177);return false"> quake </span>
<span id="p857" class="softWord" onClick="setTranscriptPosition(857);return false"> briefly </span>
<span id="p1697" class="softWord" onClick="setTranscriptPosition(1697);return false"> triggering </span>
<span id="p2267" class="softWord" onClick="setTranscriptPosition(2267);return false"> another </span>
<span id="p2697" class="softWord" onClick="setTranscriptPosition(2697);return false"> tsunami </span>
</code>```

I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)

```<code>function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }
</code>```

How would i get the id's of those spans though?

答:
I think that your over complicating it, just use mouseup()

jquery

```<code>$('span').mouseup(function(){
    alert($(this).attr('id'));
});
</code>```

Check it out here - http://jsfiddle.net/ajthomascouk/Qdv4T/

ContentLicense: CC BY-SA 3.0

Body:
I have a weird problem. I don’t quite know how to approach it. We have an application that spits out paragraphs of text with each and every word wrapped in a span with an ID. I am being asked to make a JavaScript to capture the ID's of all the words that a user highlights.

So a simple example of a paragraph is below.

 that
 quake
 briefly
 triggering
 another
 tsunami

I know there is a way to capture the selected text using something like this:(found this at site http://motyar.blogspot.com/2010/02/get-user-selected-text-with-jquery-and.html)

function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }

How would i get the id's of those spans though?

Body:
I think that your over complicating it, just use mouseup()

jquery

$('span').mouseup(function(){
    alert($(this).attr('id'));
});

Check it out here - http://jsfiddle.net/ajthomascouk/Qdv4T/


问:
What is wrong with my code in Python Jupyter Notebook?
When I run the code and input "1" or "2" it gives me the response

Sorry, we didn't understand your selection.

How do I fix this so that it gives me the correct answer?

I've Tried making "1" and "2" a string.

```<code>def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if response == "1":
        return new_customer()
    elif response == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()
</code>```

No error messages, It won't give me the answer I am looking for which is either one of these functions: new_customer() or existing_customer()

答:
If you are using python2 ,input is returning integer,
so you need do to:

```<code>response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
if response == 1:
    return new_customer()
</code>```

or:

```<code>response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
if str(response) == "1":
    return new_customer()
</code>```

Examples:

```<code>Python 2.x
s1 = raw_input("Enter raw_input to test raw_input() function: ")
>> 3
print (type(s1))  <type 'str'>
s11 = raw_input("Enter raw_input to test raw_input() function: ")
>> a
print (type(s11))  <type 'str'>

s2 = input("Enter input to test input() function: ")
>> 3
print (type(s2))  <type 'int'>
s22 = input("Enter input to test input() function: ")
>> a
print (type(s22))  <type 'str'>

Python 3.x
s3 = input("Enter input to test input() function: ")
>> 1
print (type(s3))  <type 'str'>
s33 = input("Enter input to test input() function: ")
>> a
print (type(s33))  <type 'str'>
</code>```

EDIT:

```<code>def new_customer():
    print ("new_customer")

def existing_customer():
    print ("existing_customer")

def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if response == "1":
        return new_customer()
    elif response == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()
</code>```

output:

```<code>Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer?
 [1] New Customer
 [2] Existing Customer
 Please enter the number corresponding to your choice:1
new_customer
</code>```

Body:
When I run the code and input "1" or "2" it gives me the response

Sorry, we didn't understand your selection.

How do I fix this so that it gives me the correct answer?

I've Tried making "1" and "2" a string.

def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if response == "1":
        return new_customer()
    elif response == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()

No error messages, It won't give me the answer I am looking for which is either one of these functions: new_customer() or existing_customer()

Body:
If you are using python2 ,input is returning integer,
so you need do to:

response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
if response == 1:
    return new_customer()

or:

response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
if str(response) == "1":
    return new_customer()

Examples:

Python 2.x
s1 = raw_input("Enter raw_input to test raw_input() function: ")
>> 3
print (type(s1))  <type 'str'>
s11 = raw_input("Enter raw_input to test raw_input() function: ")
>> a
print (type(s11))  <type 'str'>

s2 = input("Enter input to test input() function: ")
>> 3
print (type(s2))  <type 'int'>
s22 = input("Enter input to test input() function: ")
>> a
print (type(s22))  <type 'str'>

Python 3.x
s3 = input("Enter input to test input() function: ")
>> 1
print (type(s3))  <type 'str'>
s33 = input("Enter input to test input() function: ")
>> a
print (type(s33))  <type 'str'>

EDIT:

def new_customer():
    print ("new_customer")

def existing_customer():
    print ("existing_customer")

def cs_service_bot():
    # Replace `pass` with your code
    response = input("Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer? \n [1] New Customer \n [2] Existing Customer \n Please enter the number corresponding to your choice:")
    if response == "1":
        return new_customer()
    elif response == "2":
        return existing_customer()
    else:
        print("Sorry, we didn't understand your selection.")
        return cs_service_bot()

cs_service_bot()

output:

Hello! Welcome to the DNS Cable Company's Service Portal. Are you a new or existing customer?
 [1] New Customer
 [2] Existing Customer
 Please enter the number corresponding to your choice:1
new_customer


问:
First newbie question: SSRS Tablix visibility parameter
SSRS: I have two tablix.  One dataset.

Tablix 1 = Summary

Tablix 2 = Details

I would like to set a parameter for the user to choose.  I do not have a field in the data to use as a parameter to differentiate.  I have to use the tablix itself.  By name in report code or by visibility in the tablix?

I've tried everything I could find on Stack overflow.  But I have used a method in the past with a code in the report properties.  But I can't find the code.

I would like the user to choose summary or details or both.  Then see the corresponding tablix

答:
I tried to replicate your scenario on my local report project.
I create a mutlivalue parameter.

Then I have available values as below

Then I added below expression on visibilty of Summary Tablix.

```<code>=IIF(Parameters!ChooseTablix.Count>1,false,
IIF(Parameters!ChooseTablix.Value(0)<>1,true,false))
</code>```

Below expression for Details Tablix

```<code> =IIF(Parameters!ChooseTablix.Count>1,false,
    IIF(Parameters!ChooseTablix.Value(0)<>2,true,false))
</code>```

Body:
I tried to replicate your scenario on my local report project.
I create a mutlivalue parameter.

Then I have available values as below

Then I added below expression on visibilty of Summary Tablix.

=IIF(Parameters!ChooseTablix.Count>1,false,
IIF(Parameters!ChooseTablix.Value(0)<>1,true,false))

Below expression for Details Tablix

 =IIF(Parameters!ChooseTablix.Count>1,false,
    IIF(Parameters!ChooseTablix.Value(0)<>2,true,false))


问:
Different between in operator and for loop?
i was wondering if the "in" operator work as a for loop and if the time complexity are equivalent?

for n in range(10):
    if n == 5:
        return True
return False

5 in range(10)
```

答:
```<code>~ $ python -m timeit "def func():
>   for x in range(10):
>     if x == 5:
>       return True
>     return False
> func()"
1000000 loops, best of 3: 0.352 usec per loop

~ $ python -m timeit "5 in range(10)"
1000000 loops, best of 3: 0.263 usec per loop
</code>```

This is easy to test, and i think results aren't big suprise :)

Body:
~ $ python -m timeit "def func():
>   for x in range(10):
>     if x == 5:
>       return True
>     return False
> func()"
1000000 loops, best of 3: 0.352 usec per loop

~ $ python -m timeit "5 in range(10)"
1000000 loops, best of 3: 0.263 usec per loop

This is easy to test, and i think results aren't big suprise :)


问:
Why is this regex expression returning 'true'?
I am using this exact regex in a RegularExpressionValidator and it works fine. However this code in c# is returning true. Can you please let me know what I am doing wrong?

I am checking for numbers only regex

```<code>var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();
</code>```

答:
Because you trying to match one or more digit from 0 to 9. Explaininh:

```<code>[0-9] //Match digit 0-9 you can also use /d-(Match any digit char)
+ //Match one or more of the preceding token
</code>```

If you have some digit in you string, this code:

```<code>var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();
</code>```

will always return True.
For exaple if you try this one:

```<code>var x = Regex.IsMatch("asdf", @"[0-9]+").ToString();
</code>```

will return False

Body:
I am using this exact regex in a RegularExpressionValidator and it works fine. However this code in c# is returning true. Can you please let me know what I am doing wrong?

I am checking for numbers only regex

var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();

Body:
Because you trying to match one or more digit from 0 to 9. Explaininh:

[0-9] //Match digit 0-9 you can also use /d-(Match any digit char)
+ //Match one or more of the preceding token

If you have some digit in you string, this code:

var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();

will always return True.
For exaple if you try this one:

var x = Regex.IsMatch("asdf", @"[0-9]+").ToString();

will return False


问:
Can i access more than 1 scope when requesting for token?
I am creating API, which has multiple access levels and I have 16 routes groups (for example users, users-basic, payments, etc.) and each of them has a separate scope.

Question is - can I pass multiple scopes in authorize request? I want to manage permissions for every client oauth2 individually, that's why I am making APP scopes.

I have tried passing multiple scopes with commas, an array, etc. Nothing worked.

```<code>response: [
   error: invalid_scope,
   message: The requested scope is invalid, unknown, or malformed
   hint: Check the `users,payments` scope
]
</code>```

答: Just found out that you can pass scopes with spaces.. https://laravel.com/docs/5.8/passport#token-scopes Assigning Scopes To Tokens </p>

Body:
I am creating API, which has multiple access levels and I have 16 routes groups (for example users, users-basic, payments, etc.) and each of them has a separate scope.

Question is - can I pass multiple scopes in authorize request? I want to manage permissions for every client oauth2 individually, that's why I am making APP scopes.

I have tried passing multiple scopes with commas, an array, etc. Nothing worked.

response: [
   error: invalid_scope,
   message: The requested scope is invalid, unknown, or malformed
   hint: Check the `users,payments` scope
]


问:
How to make grouped ListView headers floating (not sticky) correctly in iOS?
I have a grouped ListView (Xamarin Forms). I need to make group headers floating (not sticky). On Android everything works the way I want, but on iOS there is a problem.

I tried to use this:
https://forums.xamarin.com/discussion/34696/listview-grouped-style-on-ios

In this case headers are floating, but it looks like it creates new control and the previous one doesn't disappear. I mean that I see one list which overlaps another one.

I can set the background of the top list to some color. Then the list that is behind will be not visible, but it is not the solution for this problem. Can somebody explain me how to fix this?

答:
A simple solution to this problem is to use an iOS platform-specific feature for Xamarin.Forms that allows you to easily set the ListView Group Header Style in XAML (or code behind) in one line as follows:

```<code><ContentPage ...
             xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core">
    <StackLayout Margin="20">
        <ListView ios:ListView.GroupHeaderStyle="Grouped">
            ...
        </ListView>
    </StackLayout>
</ContentPage>
</code>```

The 'Grouped' enumeration indicates that header cells do not float when the ListView is scrolled. See https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/ios/listview-group-header-style for further details.

Body:
A simple solution to this problem is to use an iOS platform-specific feature for Xamarin.Forms that allows you to easily set the ListView Group Header Style in XAML (or code behind) in one line as follows:

<ContentPage ...
             xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core">
    <StackLayout Margin="20">
        <ListView ios:ListView.GroupHeaderStyle="Grouped">
            ...
        </ListView>
    </StackLayout>
</ContentPage>

The 'Grouped' enumeration indicates that header cells do not float when the ListView is scrolled. See https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/ios/listview-group-header-style for further details.


问:
Is it possible to do bytecode manipulation when using OSGi?
I'm making an application server and in it I need to use some bytecode manipulation (e.g. inserting custom equals and hashCode methods to classes annotated with @Entity). Now I give the JVM a Java Agent (the -javaagent option) which does bytecode transformations using ASM.

I've been considering using OSGi, but I don't know whether it allows me to do the necessary bytecode manipulation.

Is it possible to do bytecode manipulation when using OSGi? How?

Is it possible for a bundle to declare itself, that it requires some bytecode manipulation for it to work? For example the application server requires that some of its own core classes are manipulated.

Is it possible to specify that some other bundle requires some bytecode manipulation, without that bundle knowing about it? For example all applications which run on the server  must be manipulated, but the applications don't need to know about it.

Is it possible for a bundle to declare itself, that all bundles which depend on it must be bytecode manipulated? This would make it easy for me to declare that all who depend on the API bundle which contains the @Entity annotation, must be manipulated.

答:
1) Yes, it is possible to do bytecode manipulation in OSGi. The how is a bit different than with standard java, you need to use the extender pattern describe here http://www.osgi.org/blog/2007/02/osgi-extender-model.html.
I believe Eclipse is using that in their equinox aspect project: http://www.eclipse.org/equinox/incubator/aspects/. Spring DM is definitely using this pattern to autoconfigure osgi dm module.

2) that would be up to the extender pattern you use. tha's how the spring extender is working, looking for configuration files in  the META-INF/spring folder of bundle before they are started by the platform.

3) Again, this would be up to the extender you define.

4) I believe this would be possible since before a bundle can be started, it has to resolved and dependencies started, your extender could then analyze bundle dependencies and start the byte code manipulation.

OwnerDisplayName: Esko Luontola

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Patrick Roumanoff


问:
How do I convert "fraction of day" to Java time?
I'm working with the Excel format where

0.6549

Means that we are 65.49% through the day.  How would I convert this to a nice looking time such as

15:30:42 PM

in Java?

答:
Try this:

```<code>public static void main(String[] args) throws Exception {
    DateFormat format = new SimpleDateFormat("HH:mm:ss a");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    for(String fracStr : args) {
        double frac = Double.parseDouble(fracStr);
        long day = (long) Math.floor(frac);
        frac = frac - day;
        Date time = new Date((long) ( 86400000l * frac));
        System.out.println(fracStr+" -> "+format.format(time));
    }
}
</code>```

A little note here - the GMT time zone may not get you the results you expect, but UTC will. This is because Java considers GMT as a valid abbreviation for Europe/London and between 1968 and 1972 London was on permanent daylight saving. So midnight 1st January 1970 GMT (the Java epoch) is also 1am 1st January 1970 (GMT).

Body:
Try this:

public static void main(String[] args) throws Exception {
    DateFormat format = new SimpleDateFormat("HH:mm:ss a");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    for(String fracStr : args) {
        double frac = Double.parseDouble(fracStr);
        long day = (long) Math.floor(frac);
        frac = frac - day;
        Date time = new Date((long) ( 86400000l * frac));
        System.out.println(fracStr+" -> "+format.format(time));
    }
}

A little note here - the GMT time zone may not get you the results you expect, but UTC will. This is because Java considers GMT as a valid abbreviation for Europe/London and between 1968 and 1972 London was on permanent daylight saving. So midnight 1st January 1970 GMT (the Java epoch) is also 1am 1st January 1970 (GMT).