问:
Javascript - Math.floor does not work
I know there are more of the "Math.floor not working" questions, but I didn't found my answer there, so that's why I made this question.

I am making a simple algorithm which is looking for your number by jumping in between the range. So for example, range = 100, number = 60. It will go to 50, see it's higher, so the range is 50 - 100. then it jumps to 75 to see if it's either bigger or smaller, and so on until it found the right number.

To make this a bit more clear, I thought: "I'll round them downwards by using Math.floor." But for some reason it doesn't work.

My code:

var guessTheNumber = function() {

  var validNumber = false; // Geldig nummer = niet waar
  var userNumberHTML = document.getElementById("userNumberHTML"); // Noem HTML element met ID "userNumberHTML" "userNumberHTML"
  var guessedNumbers = document.getElementById("guessedNumbers"); // noem HTML element met ID "guessedNumbers" "guessedNumbers"
  guessedNumbers.innerHTML = "Guessed number(s): ";
  var minNumber = 0; // Minimum wat mensen kunnen invullen
  var maxNumber = 100; // Maximum wat mensen kunnen invullen
  var userNumber = prompt("Tell me a number between 0 and 100, including those (numbers with decimals will be rounded downwards)."); // Vraag gebruiker welk nummer
  userNumber = Math.floor(userNumber); // Nummer wordt naar beneden afgerond
  var counter = 1;
  var result = 0;
  var q = 1;

  if (userNumber >= minNumber && userNumber <= maxNumber) { // Als het een getal is groter of gelijk aan 1 en kleiner of gelijk aan 100
    userNumberHTML.innerHTML = "Your number: " + userNumber; // Geef "x" in HTML de waarde van "userNumber", namelijk het genoemde getal
  } else { // Anders
    while (validNumber == false) { // Zolang validNumber NIET waar is
      userNumber = prompt("This is not a number between 0 and 100. Try again."); // wordt "userNumber" de waarde van de nieuwe prompt
      if (userNumber >= 1 && userNumber <= 100) { // Als het een getal is groter of gelijk aan 1 en kleiner of gelijk aan 100
        userNumberHTML.innerHTML = "Your number: " + userNumber; // Geef "x" in HTML de waarde van "userNumber", namelijk het zojuist genoemde getal
        validNumber = true; // Zet validNumber op WEL waar
      }
    }
  }

  result = (minNumber + maxNumber) / 2;
  Math.floor(result);
  guessedNumbers.innerHTML += result + ", ";

  while (result != userNumber) {
    if (result < userNumber) {
      Math.floor(result);
      minNumber = result;
    } else {
      Math.floor(result);
      maxNumber = result;
    }
    result = (minNumber + maxNumber) / 2;
    guessedNumbers.innerHTML += result + ", ";
    q++;
  }

  guessedNumbers.innerHTML += "and there you go!";
  alert("The PC guessed your number in " + q + " times!");
  if (confirm("Try again?")) {
    guessedNumbers.innerHTML = "Guessed number(s): ";
    guessTheNumber();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>JS test</title>
</head>

<body>
  <button onclick="guessTheNumber()" style="height: 100px; width: 200px;">Let the Computer find your number!</button>
  <p id="userNumberHTML">Your number: </p>
  <p id="guessedNumbers">Guessed number(s): </p>
  <p id="TEST"></p>

  <!-- SCRIPTS -->
  <!-- <script type="text/javascript" src="guessTheNumber.js"></script> -->
  <script type="text/javascript" src="test.js"></script>
</body>

</html></code>```

I do really not know what I am doing wrong, since the user input does Math.floor like it should! Any help is appreciated :)

Thanks in advance,

Brent

答:
Math.floor(result) returns the result, so you have to use:

```<code>result = Math.floor(result);
</code>```

Title: Javascript - Math.floor does not work

Body:
I know there are more of the "Math.floor not working" questions, but I didn't found my answer there, so that's why I made this question.

I am making a simple algorithm which is looking for your number by jumping in between the range. So for example, range = 100, number = 60. It will go to 50, see it's higher, so the range is 50 - 100. then it jumps to 75 to see if it's either bigger or smaller, and so on until it found the right number.

To make this a bit more clear, I thought: "I'll round them downwards by using Math.floor." But for some reason it doesn't work.

My code:

var guessTheNumber = function() {

  var validNumber = false; // Geldig nummer = niet waar
  var userNumberHTML = document.getElementById("userNumberHTML"); // Noem HTML element met ID "userNumberHTML" "userNumberHTML"
  var guessedNumbers = document.getElementById("guessedNumbers"); // noem HTML element met ID "guessedNumbers" "guessedNumbers"
  guessedNumbers.innerHTML = "Guessed number(s): ";
  var minNumber = 0; // Minimum wat mensen kunnen invullen
  var maxNumber = 100; // Maximum wat mensen kunnen invullen
  var userNumber = prompt("Tell me a number between 0 and 100, including those (numbers with decimals will be rounded downwards)."); // Vraag gebruiker welk nummer
  userNumber = Math.floor(userNumber); // Nummer wordt naar beneden afgerond
  var counter = 1;
  var result = 0;
  var q = 1;

  if (userNumber >= minNumber && userNumber <= maxNumber) { // Als het een getal is groter of gelijk aan 1 en kleiner of gelijk aan 100
    userNumberHTML.innerHTML = "Your number: " + userNumber; // Geef "x" in HTML de waarde van "userNumber", namelijk het genoemde getal
  } else { // Anders
    while (validNumber == false) { // Zolang validNumber NIET waar is
      userNumber = prompt("This is not a number between 0 and 100. Try again."); // wordt "userNumber" de waarde van de nieuwe prompt
      if (userNumber >= 1 && userNumber <= 100) { // Als het een getal is groter of gelijk aan 1 en kleiner of gelijk aan 100
        userNumberHTML.innerHTML = "Your number: " + userNumber; // Geef "x" in HTML de waarde van "userNumber", namelijk het zojuist genoemde getal
        validNumber = true; // Zet validNumber op WEL waar
      }
    }
  }

  result = (minNumber + maxNumber) / 2;
  Math.floor(result);
  guessedNumbers.innerHTML += result + ", ";

  while (result != userNumber) {
    if (result < userNumber) {
      Math.floor(result);
      minNumber = result;
    } else {
      Math.floor(result);
      maxNumber = result;
    }
    result = (minNumber + maxNumber) / 2;
    guessedNumbers.innerHTML += result + ", ";
    q++;
  }

  guessedNumbers.innerHTML += "and there you go!";
  alert("The PC guessed your number in " + q + " times!");
  if (confirm("Try again?")) {
    guessedNumbers.innerHTML = "Guessed number(s): ";
    guessTheNumber();
  }
}

<!DOCTYPE html>

  <title>JS test</title>

  <button onclick="guessTheNumber()" style="height: 100px; width: 200px;">Let the Computer find your number!</button>

Your number:

Guessed number(s):

I do really not know what I am doing wrong, since the user input does Math.floor like it should! Any help is appreciated :)

Thanks in advance,

Brent

Body:
Math.floor(result) returns the result, so you have to use:

result = Math.floor(result);


来源: stackexchange

问:
Detecting Tap & Hold in UITableView cells
How do we detect a tap & hold on a UITableViewCell?

答: In iOS 3.2 or later you can use UILongPressGestureRecognizer

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


答:
Javascript parameters are passed by value, not by reference, so the function can't modify the parameter variable. You have to assign the result:</p>

```<code>result = Math.floor(result);
</code>```

Title: Javascript - Math.floor does not work

Body:
Javascript parameters are passed by value, not by reference, so the function can't modify the parameter variable. You have to assign the result:

result = Math.floor(result);


问:
Spring Integration: Error Channel not available in XML
Hi I am using Spring integration with JMS integration and i noticed that when i try to use error-channel in my jms-message-drive-outbound-adapter, it give below error;

As per suggestions for my previous questions , i want to retrieve exception and rollback transaction so that i dont lose message. How do i achieve that if error-channel is not possible.

```<code>cvc-complex-type.3.2.2: Attribute 'error-channel' is not allowed to appear in element 'jms:message-driven-channel-adapter'.
</code>```

My XML is below:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jms="http://www.springframework.org/schema/integration/jms"
    xmlns:integration="http://www.springframework.org/schema/integration"
    xmlns:int-kafka="http://www.springframework.org/schema/integration/kafka"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/integration/jms
    http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
    http://www.springframework.org/schema/integration/kafka
    http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd">

    <jms:message-driven-channel-adapter id="requestChannelAdapter" channel="requestChannel"
    container="requestListenerContainer" error-channel=""/>

    <int-kafka:outbound-channel-adapter
        id="kafkaOutboundChannelAdapter" kafka-template="kafkaTemplate"
        auto-startup="true" sync="true" channel="inputToKafka" topic="test">
    </int-kafka:outbound-channel-adapter>
</beans>
</code>```

Is it replaced with something else in recent releases.

My POM File is listed below for reference in case it is due to version mismatch:

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

    <groupId>com.test.dzone.activemq</groupId>
    <artifactId>jpmc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpmc</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-jms</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-kafka</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-java-dsl</artifactId>
            <version>1.1.2.RELEASE</version>
        </dependency>
        <!-- dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-zookeeper</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency-->

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-broker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.10</artifactId>
            <version>0.8.1.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
You can ignore it; it appears your IDE is using the schema from the internet - see the note at the top of it...

http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd

```<code><!--
       +++++ IMPORTANT +++++

     This schema is for the 1.0 version of Spring Integration JMS. We cannot update it to the current schema
     because that will break any applications using 1.0.3 or lower. For subsequent versions, the unversioned
     schema is resolved from the classpath and obtained from the jar.
     Please refer to github:

https://github.com/spring-projects/spring-integration/tree/master/spring-integration-jms/src/main/resources/org/springframework/integration/jms/config

     for the latest schema.
-->
</code>```

You can either ignore it, or use a Spring-Aware IDE (Spring Tool Suite - STS, IntelliJ IDEA, etc) that knows how to find the current schema on the class path via /META-INF/spring.schemas.

If you are already using STS (or eclipse with the Spring IDE plugins) then be sure to enable "Spring Nature" on the project.

Body:
Hi I am using Spring integration with JMS integration and i noticed that when i try to use error-channel in my jms-message-drive-outbound-adapter, it give below error;

As per suggestions for my previous questions , i want to retrieve exception and rollback transaction so that i dont lose message. How do i achieve that if error-channel is not possible.

cvc-complex-type.3.2.2: Attribute 'error-channel' is not allowed to appear in element 'jms:message-driven-channel-adapter'.

My XML is below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jms="http://www.springframework.org/schema/integration/jms"
    xmlns:integration="http://www.springframework.org/schema/integration"
    xmlns:int-kafka="http://www.springframework.org/schema/integration/kafka"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/integration/jms
    http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
    http://www.springframework.org/schema/integration/kafka
    http://www.springframework.org/schema/integration/kafka/spring-integration-kafka.xsd">

    <jms:message-driven-channel-adapter id="requestChannelAdapter" channel="requestChannel"
    container="requestListenerContainer" error-channel=""/>

    <int-kafka:outbound-channel-adapter
        id="kafkaOutboundChannelAdapter" kafka-template="kafkaTemplate"
        auto-startup="true" sync="true" channel="inputToKafka" topic="test">
    </int-kafka:outbound-channel-adapter>
</beans>

Is it replaced with something else in recent releases.

My POM File is listed below for reference in case it is due to version mismatch:

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

    <groupId>com.test.dzone.activemq</groupId>
    <artifactId>jpmc</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpmc</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-integration</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-jms</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-kafka</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-java-dsl</artifactId>
            <version>1.1.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-broker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka_2.10</artifactId>
            <version>0.8.1.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Body:
You can ignore it; it appears your IDE is using the schema from the internet - see the note at the top of it...

http://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd

<!--
       +++++ IMPORTANT +++++

     This schema is for the 1.0 version of Spring Integration JMS. We cannot update it to the current schema
     because that will break any applications using 1.0.3 or lower. For subsequent versions, the unversioned
     schema is resolved from the classpath and obtained from the jar.
     Please refer to github:

https://github.com/spring-projects/spring-integration/tree/master/spring-integration-jms/src/main/resources/org/springframework/integration/jms/config

     for the latest schema.
-->

You can either ignore it, or use a Spring-Aware IDE (Spring Tool Suite - STS, IntelliJ IDEA, etc) that knows how to find the current schema on the class path via /META-INF/spring.schemas.

If you are already using STS (or eclipse with the Spring IDE plugins) then be sure to enable "Spring Nature" on the project.


问:
CSS - Background images
Probably very silly question, but since I am trying to put my website online using my domaine which I have recently purchased, the background image doesn't seem to load at all.

Any idea?

body {
  margin: 0;
  background-image: url("homepage1.jpg");
  background-size: cover;
  font-family: 'Parisienne', cursive;
  background-repeat: no-repeat;
}

.navbar {
  background-color: none;
  width: 100%;
  height: 30px;
  padding-top: 0;
  text-align: center;
}

.navbar a {
  padding: 20px;
  font-size: 2.0em;
  color: black;
  text-decoration: none;
}

.navbar a:hover:not(.active) {
  color: #B22222;
}

.homepage {
  padding-top: 15px;
}

#welcome {
  color: black;
  font-size: 30px;
  text-align: center;
}

#welcome h1 {
  font-size: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="homepage">
  <div class="navbar">
    Home
    Schedule
    Accommodations
    Travel
    Activities
    Contact
  </div>
  <div id="welcome">
    <h1>Tracey & Jonathan's Wedding</h1>
    <p>16 / 08 / 2018</p>
  </div>
</div></code>```

答: Your "homepage1.jpg" should be in the same folder as in your "IDontKnowTheName.css". If it isn't, you can move it to there, or do "subfolder/subfolder/....../homepage1.jpg", or you can go a folder up by using "../".</p>

Title: CSS - Background images

Body:
Probably very silly question, but since I am trying to put my website online using my domaine which I have recently purchased, the background image doesn't seem to load at all.

Any idea?

body {
  margin: 0;
  background-image: url("homepage1.jpg");
  background-size: cover;
  font-family: 'Parisienne', cursive;
  background-repeat: no-repeat;
}

.navbar {
  background-color: none;
  width: 100%;
  height: 30px;
  padding-top: 0;
  text-align: center;
}

.navbar a {
  padding: 20px;
  font-size: 2.0em;
  color: black;
  text-decoration: none;
}

.navbar a:hover:not(.active) {
  color: #B22222;
}

.homepage {
  padding-top: 15px;
}

#welcome {
  color: black;
  font-size: 30px;
  text-align: center;
}

#welcome h1 {
  font-size: 50px;
}

    Home
    Schedule
    Accommodations
    Travel
    Activities
    Contact

Tracey & Jonathan's Wedding

16 / 08 / 2018


问:
Find unique rows in numpy.array
I need to find unique rows in a numpy.array.

For example:

```<code>>>> a # I have
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 0]])
</code>```

I know that i can create a set and loop over the array, but I am looking for an efficient pure numpy solution. I believe that there is a way to set data type to void and then I could just use numpy.unique, but I couldn't figure out how to make it work.

答:
I've compared the suggested alternative for speed and found that, surprisingly, the void view unique solution is even a bit faster than numpy's native unique with the axis argument. If you're looking for speed, you'll want

numpy.unique(
    a.view(numpy.dtype((numpy.void, a.dtype.itemsize*a.shape[1])))
).view(a.dtype).reshape(-1, a.shape[1])
```
<p>I've implemented that fastest variant in npx.unique_rows.</p>
<p>There is a bug report on GitHub for this, too.</p>
<p><img src="https://i.stack.imgur.com/mJuUK.png" alt="enter image description here" /></p>
<hr />
<p>Code to reproduce the plot:</p>
<pre class="lang-py prettyprint-override"><code>import numpy
import perfplot

def unique_void_view(a):
    return (
        numpy.unique(a.view(numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1]))))
        .view(a.dtype)
        .reshape(-1, a.shape[1])
    )

def lexsort(a):
    ind = numpy.lexsort(a.T)
    return a[
        ind[numpy.concatenate(([True], numpy.any(a[ind[1:]] != a[ind[:-1]], axis=1)))]
    ]

def vstack(a):
    return numpy.vstack([tuple(row) for row in a])

def unique_axis(a):
    return numpy.unique(a, axis=0)

perfplot.show(
    setup=lambda n: numpy.random.randint(2, size=(n, 20)),
    kernels=[unique_void_view, lexsort, vstack, unique_axis],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
    equality_check=None,
)
</code>```

Title: Find unique rows in numpy.array

Body:
I need to find unique rows in a numpy.array.

For example:

>>> a # I have
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])
>>> new_a # I want to get to
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 1, 1, 0]])

I know that i can create a set and loop over the array, but I am looking for an efficient pure numpy solution. I believe that there is a way to set data type to void and then I could just use numpy.unique, but I couldn't figure out how to make it work.

Body:
I've compared the suggested alternative for speed and found that, surprisingly, the void view unique solution is even a bit faster than numpy's native unique with the axis argument. If you're looking for speed, you'll want

numpy.unique(
    a.view(numpy.dtype((numpy.void, a.dtype.itemsize*a.shape[1])))
).view(a.dtype).reshape(-1, a.shape[1])

I've implemented that fastest variant in npx.unique_rows.

There is a bug report on GitHub for this, too.

Code to reproduce the plot:

import numpy
import perfplot

def unique_void_view(a):
    return (
        numpy.unique(a.view(numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1]))))
        .view(a.dtype)
        .reshape(-1, a.shape[1])
    )

def lexsort(a):
    ind = numpy.lexsort(a.T)
    return a[
        ind[numpy.concatenate(([True], numpy.any(a[ind[1:]] != a[ind[:-1]], axis=1)))]
    ]

def vstack(a):
    return numpy.vstack([tuple(row) for row in a])

def unique_axis(a):
    return numpy.unique(a, axis=0)

perfplot.show(
    setup=lambda n: numpy.random.randint(2, size=(n, 20)),
    kernels=[unique_void_view, lexsort, vstack, unique_axis],
    n_range=[2 ** k for k in range(15)],
    xlabel="len(a)",
    equality_check=None,
)

ContentLicense: CC BY-SA 4.0


问:
How to know if I'm running a python script from eclipse
I have a python script which is sometimes invoked from command line and sometimes from eclipse (during SW build).

Is there a way to know from within the python script if it is invoked from eclipse (without sending the script command line arguments)?

Thanks.

答:
I don't use Eclipse anymore since PyCharm is much more efficient for Python programming, but here are some ideas you can try:

⬥ You may have (or you can set) an environment variable when the script is launched with Eclipse.

For instance, with PyCharm, we have:

```<code>import os

print("PYCHARM_HOSTED: {!r}".format(os.environ['PYCHARM_HOSTED']))
# -> PYCHARM_HOSTED: '1'
</code>```

You can have a similar environment variable with Eclipse. Check the os.environ dictionary.

⬥ You can have a different virtualenv, check the sys.executable value:

```<code>import sys

print(sys.executable)
# -> /Users/laurentlaporte/virtualenv/my_app/bin/python
</code>```

⬥ When Eclipse launch your Python application, it creates a child process. In your Python application, you can search the parent process. It is a little complex, so…

To do that, you need to use PsUtil.

Body:
I don't use Eclipse anymore since PyCharm is much more efficient for Python programming, but here are some ideas you can try:

⬥ You may have (or you can set) an environment variable when the script is launched with Eclipse.

For instance, with PyCharm, we have:

import os

print("PYCHARM_HOSTED: {!r}".format(os.environ['PYCHARM_HOSTED']))
# -> PYCHARM_HOSTED: '1'

You can have a similar environment variable with Eclipse. Check the os.environ dictionary.

⬥ You can have a different virtualenv, check the sys.executable value:

import sys

print(sys.executable)
# -> /Users/laurentlaporte/virtualenv/my_app/bin/python

⬥ When Eclipse launch your Python application, it creates a child process. In your Python application, you can search the parent process. It is a little complex, so…

To do that, you need to use PsUtil.


答:
This is because your userNumber is a string. Just use parseInt(userNumber) and it should work.
You should also add some kind of input type control!

Edit:
As others have pointed out, you also have to assign the value to the variable. I just saw the first use Math.floor() and thought that was the only problem.

To sum up, you should have:
userNumber = Math.floor(parseInt(userNumber)) at first, so you do not get a NaN, and then use result = Math.floor(result) to get the proper value.

Title: Javascript - Math.floor does not work


答:
You wrote

```<code>Math.floor(result);
</code>```

but it will not modify result and thus have no effect

Consider using

```<code>result = Math.floor(result);
</code>```

instead

Title: Javascript - Math.floor does not work

Body:
You wrote

Math.floor(result);

but it will not modify result and thus have no effect

Consider using

result = Math.floor(result);

instead


问:
Compile views at build time VS2010?

Possible Duplicate:

  ASP.Net MVC - Compiler Errors in Views

I'm using ASP.NET MVC 2 with Visual Studio 2010, and I hate runtime errors.  Compile errors that only happen when I browse that page are almost as bad.

Is there a way I can have my views compile when I hit build?

答:
Does enabling MvcBuildViews help?

To enable MvcBuildViews make the following change in your project file

```<code><MvcBuildViews>true</MvcBuildViews>
</code>```

Title: Compile views at build time VS2010?

Body:
Does enabling MvcBuildViews help?

To enable MvcBuildViews make the following change in your project file

<MvcBuildViews>true</MvcBuildViews>


问:
Python regex extra character on re.sub (Regex replacement)
I'm trying to create a simple function to replace only accented characters with normal ones:

```<code>import re

def remove_accents(r):
    r = re.sub("[àáâãäå]", 'a', r)
    r = re.sub("[èéêë]", 'e', r)
    r = re.sub("[ìíîï]", 'i', r)
    r = re.sub("[òóôõö]", 'o', r)
    r = re.sub("[ùúûü]", 'u', r)
    r = re.sub("[ýÿ]", 'y', r)

    return r
</code>```

The problem I'm having is the next one, when I try to replace the accented character with the normal one, Python is adding an extra character and I don't know why.

Example

```<code>import re

my_string = "Joaquín Noriega"
print re.sub(r"[ìíîï]", r'i', my_string)
</code>```

This is what I get on my output:

```<code>Output: 'Joaquiin Noriega'
</code>```

Note the double 'ii' on the name, it should be 'Joaquin Noriega'

Why is this happening ? Is there something wrong with my regex ?

答:
Python 2 strings are bytes, so as UTF-8, the regex really looks like this:

```<code>'[\xc3\xac\xc3\xad\xc3\xae\xc3\xaf]'
</code>```

í in "Joaquín Noriega" is encoded the same way – as two bytes – and they both match the character class, so they’re both replaced with the single-byte i.

The preferable fix to this is to switch to Python 3 (it has sane text handling), but if you can’t, Unicode strings will do:

```<code>import re

my_string = u"Joaquín Noriega"
print re.sub(u"[ìíîï]", u'i', my_string)
</code>```

Body:
I'm trying to create a simple function to replace only accented characters with normal ones:

import re

def remove_accents(r):
    r = re.sub("[àáâãäå]", 'a', r)
    r = re.sub("[èéêë]", 'e', r)
    r = re.sub("[ìíîï]", 'i', r)
    r = re.sub("[òóôõö]", 'o', r)
    r = re.sub("[ùúûü]", 'u', r)
    r = re.sub("[ýÿ]", 'y', r)

    return r

The problem I'm having is the next one, when I try to replace the accented character with the normal one, Python is adding an extra character and I don't know why.

Example

import re

my_string = "Joaquín Noriega"
print re.sub(r"[ìíîï]", r'i', my_string)

This is what I get on my output:

Output: 'Joaquiin Noriega'

Note the double 'ii' on the name, it should be 'Joaquin Noriega'

Why is this happening ? Is there something wrong with my regex ?

Body:
Python 2 strings are bytes, so as UTF-8, the regex really looks like this:

'[\xc3\xac\xc3\xad\xc3\xae\xc3\xaf]'

í in "Joaquín Noriega" is encoded the same way – as two bytes – and they both match the character class, so they’re both replaced with the single-byte i.

The preferable fix to this is to switch to Python 3 (it has sane text handling), but if you can’t, Unicode strings will do:

import re

my_string = u"Joaquín Noriega"
print re.sub(u"[ìíîï]", u'i', my_string)


问:
Use class object as parameter in function to add to array
I would like to do a simple base where I can add memebers to array. I change a "Tour of Heroes" from Angular tutorial (link). What I want to do is instead of passing name (string) to function I would like to give a whole class object (User). I use form where user is typing his name and surname (and city if he want). I have no idea how to get from input to function this whole object, instead of list of string parameters. Here is my code:
form.html:

```<code>  <div class="form-group">
    <label for="Name">Name</label>
    <input type="text" class="form-control" id="Name" required name="nameField" [(ngModel)]="ngModel"  #nameField="ngModel" >
    <div [hidden]="nameField.valid || nameField.pristine" class="alert alert-danger">Name is required</div>
  </div>

  <div class="form-group">
    <label for="surname">surname</label>
    <input type="text" class="form-control" id="surname" required name="surnameField" ngModel #surnameField="ngModel">
    <div [hidden]="surnameField.valid || surnameField.pristine" class="alert alert-danger">Surname is required</div>
  </div>

  <div class="form-group">
    <label for="city">City</label>
    <input type="text" class="form-control" id="city" name="city" ngModel #cityField="ngModel" >
  </div>

  <button type="submit" class="btn btn-success" [disabled]="!userForm.form.valid">Submit</button>

</form>
</code>```

function on submit:

```<code>onSubmit(name: string, surname: string, city: string ): void{
name = name.trim();
surname = surname.trim();
city = city.trim();

this.myservice.create(name, surname, city)
  .then(newUser => this.arrayUsers.push(newUser));
}
</code>```

And function create inside myservice:

```<code>private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/mainArray';  // URL to web api
create(name: string, surname: string, city?: string): Promise<User> {
return this.http
  .post(this.heroesUrl, JSON.stringify({name: name, surname:surname, city:city}), {headers: this.headers})
  .toPromise()
  .then(res => res.json().data as User);
}
</code>```

答:
Declare the ngModel  attribute to bind each input to the form :

For example :

```<code><input type="text" class="form-control" id="name" ngModel required name="nameField" >
<input type="text" class="form-control" id="surname" ngModel required name="surnameField" >
<input type="text" class="form-control" id="city" ngModel required name="cityField" ngModel >
</code>```

And in the form element, give a name to the form to be able to bind it in the component and add the form as parameter in the onSubmit() method :

```<code><form #f="ngForm" (ngSubmit)="onSubmit(f)" >
</code>```

Now you should be able to retrieve the user with the f.value property :

```<code>onSubmit(f: NgForm): void{

this.myservice.create(f.value)
  .then(createdUser=> this.arrayUsers.push(createdUser));
}
</code>```

More information here : https://angular.io/api/forms/NgModel

Body:
I would like to do a simple base where I can add memebers to array. I change a "Tour of Heroes" from Angular tutorial (link). What I want to do is instead of passing name (string) to function I would like to give a whole class object (User). I use form where user is typing his name and surname (and city if he want). I have no idea how to get from input to function this whole object, instead of list of string parameters. Here is my code:
form.html:

    Name
    <input type="text" class="form-control" id="Name" required name="nameField" [(ngModel)]="ngModel"  #nameField="ngModel" >

Name is required

    surname
    <input type="text" class="form-control" id="surname" required name="surnameField" ngModel #surnameField="ngModel">

Surname is required

    City
    <input type="text" class="form-control" id="city" name="city" ngModel #cityField="ngModel" >

  <button type="submit" class="btn btn-success" [disabled]="!userForm.form.valid">Submit</button>

</form>

function on submit:

onSubmit(name: string, surname: string, city: string ): void{
name = name.trim();
surname = surname.trim();
city = city.trim();

this.myservice.create(name, surname, city)
  .then(newUser => this.arrayUsers.push(newUser));
}

And function create inside myservice:

private headers = new Headers({'Content-Type': 'application/json'});
private heroesUrl = 'api/mainArray';  // URL to web api
create(name: string, surname: string, city?: string): Promise<User> {
return this.http
  .post(this.heroesUrl, JSON.stringify({name: name, surname:surname, city:city}), {headers: this.headers})
  .toPromise()
  .then(res => res.json().data as User);
}

Body:
Declare the ngModel  attribute to bind each input to the form :

For example :

<input type="text" class="form-control" id="name" ngModel required name="nameField" >
<input type="text" class="form-control" id="surname" ngModel required name="surnameField" >
<input type="text" class="form-control" id="city" ngModel required name="cityField" ngModel >

And in the form element, give a name to the form to be able to bind it in the component and add the form as parameter in the onSubmit() method :

<form #f="ngForm" (ngSubmit)="onSubmit(f)" >

Now you should be able to retrieve the user with the f.value property :

onSubmit(f: NgForm): void{

this.myservice.create(f.value)
  .then(createdUser=> this.arrayUsers.push(createdUser));
}

More information here : https://angular.io/api/forms/NgModel


答:
The image is located in a folder and you must put the trail to get to the image so example -- background-image: url(folder name/folder name/homepage1.jpg); --- the folder name would be the name of the folders your image is located in. You can also do this as well --- background-image: url(../homepage1.jpg);

Here is the result when I added your coding -- good job by the way.
Here is my coding to get this picture -- background-image: url(images/free%20images/pixabay/faucet-1684902_640.jpg);

Hope this helped and if not please let me know

Title: CSS - Background images


问:
Javascript how to filter an array using forEach() inside filter()
I have an array of objects and I'd like to filter it based on the objects property values. I'd like to filter it by different properties, so it needed to be dynamic. For this I have an input field where I type and then filter the array. So, let's say I have these 2 different arrays:

```<code>const array_one = [
  {id: 1, code: 'ABC123', name: 'John'},
  {id: 2, code: 'DEF456', name: 'Stew'},
    // ...
];

const array_two = [
  {id: 1, value: '012345', company: 'Company 01' },
  {id: 2, value: '678910', company: 'Company 02' },
    // ...
];
</code>```

I want a function where I can filter the first array based on the name, also If I want to filter the second array, I want to filter it by the value.

For this, I built this function:

```<code>filterArray(array: Array<any>, fields: Array<any>, value: string) {
    value = this.convertString(value);

    array = array.filter((item) => {
        fields.forEach(obj => {
            if ( item[obj] ) {
                const _newObj = this.convertString(item[obj]);
                if ( _newObj.indexOf(value) !== -1 ) {
                    console.log(item);
                    return item;
                }
            }
        });
    });

    return array;
}
// convertString() is just another function to replace accents, spaces, etc...
</code>```

Then I call it like this:

```<code>filterArray(originalArray, ['name'], valueFromInput);

// or...
filterArray(originalArray, ['value'], valueFromInput);

// or even...
filterArray(originalArray, ['value', 'company'], valueFromInput);
</code>```

But the array filtered is always returnin empty, even if the console inside the indexOf verification prints the correct object on the console.

What am I doing wrong here? Because it's filtering properly, I have manually checked it, but it doesn't add to the new filtered array.

答:
You can iterate the fields using Array#some, and if one of them is equal to value return the item:

const array_one = [
  {id: 1, code: 'ABC123', name: 'John'},
  {id: 2, code: 'DEF456', name: 'Stew'}
];

const array_two = [
  {id: 1, value: '012345', company: 'Company 01' },
  {id: 2, value: '678910', company: 'Company 02' }
];

const filterArray = (array, fields, value) => {
  fields = Array.isArray(fields) ? fields : [fields];

  return array.filter((item) => fields.some((field) => item[field] === value));
};

console.log(filterArray(array_one, 'name', 'Stew'));

console.log(filterArray(array_two, ['id', 'company'], 2));

console.log(filterArray(array_two, ['id', 'company'], 'Company 02'));```

Body:
I have an array of objects and I'd like to filter it based on the objects property values. I'd like to filter it by different properties, so it needed to be dynamic. For this I have an input field where I type and then filter the array. So, let's say I have these 2 different arrays:

const array_one = [
  {id: 1, code: 'ABC123', name: 'John'},
  {id: 2, code: 'DEF456', name: 'Stew'},
    // ...
];

const array_two = [
  {id: 1, value: '012345', company: 'Company 01' },
  {id: 2, value: '678910', company: 'Company 02' },
    // ...
];

I want a function where I can filter the first array based on the name, also If I want to filter the second array, I want to filter it by the value.

For this, I built this function:

filterArray(array: Array<any>, fields: Array<any>, value: string) {
    value = this.convertString(value);

    array = array.filter((item) => {
        fields.forEach(obj => {
            if ( item[obj] ) {
                const _newObj = this.convertString(item[obj]);
                if ( _newObj.indexOf(value) !== -1 ) {
                    console.log(item);
                    return item;
                }
            }
        });
    });

    return array;
}
// convertString() is just another function to replace accents, spaces, etc...

Then I call it like this:

filterArray(originalArray, ['name'], valueFromInput);

// or...
filterArray(originalArray, ['value'], valueFromInput);

// or even...
filterArray(originalArray, ['value', 'company'], valueFromInput);

But the array filtered is always returnin empty, even if the console inside the indexOf verification prints the correct object on the console.

What am I doing wrong here? Because it's filtering properly, I have manually checked it, but it doesn't add to the new filtered array.


问:
How to create std::string from output stream?
Forgive the simple question, but I've been at this for hours, with no success. Im trying to implement a function:

```<code>std::string make_date_string()
</code>```

I am using Howard Hinnant's date lib, which allows me to do stuff like this:

```<code>cout << floor<days>(system_clock::now());
</code>```

printing something like:

```<code>2017-07-09
</code>```

I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.

答:
I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.

In such case you can use a std::ostringstream:

```<code>std::ostringstream oss;
oss << floor<days>(system_clock::now());
std::string time = oss.str();
</code>```

As a side note:

As it looks like your helper function

```<code>template<typename Fmt>
floor(std::chrono::timepoint);
</code>```

is implemented as an iostream manipulator, it can be used with any std::ostream implementation.

Body:
Forgive the simple question, but I've been at this for hours, with no success. Im trying to implement a function:

std::string make_date_string()

I am using Howard Hinnant's date lib, which allows me to do stuff like this:

cout << floor<days>(system_clock::now());

printing something like:

2017-07-09

I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.

Body:
I'm trying to figure out how I can get that output to go in a std::string so I can return it from my function, but Im getting nowhere.

In such case you can use a std::ostringstream:

std::ostringstream oss;
oss << floor<days>(system_clock::now());
std::string time = oss.str();

As a side note:

As it looks like your helper function

template<typename Fmt>
floor(std::chrono::timepoint);

is implemented as an iostream manipulator, it can be used with any std::ostream implementation.


问:
Advantages of using multiple schemas?
We are currently developing In Java/Hibernate multiuser application with postgreSQL.And we are migrating our database to multiple schemas (one schema as one company);
Now i saw this drawback database size is getting more and more even though there the same data:before migrating there were 700MB; after roughly 2GB.

Because of this we are facing backuping/restoring problems it is taking much more than previous one.

Q:it can be avoided wasting time/space for making faster deliverability?
   Or, are we doing something wrong ?

答:
You have not written what you have really done.

I suppose you have some common data (f.g. dictionaries) that you have also copied. When this data will be common for each company (not customized), you should just keep it in separated schema.

Title: Advantages of using multiple schemas?


问:
Draw gradient along a curved UIBezierPath
In an app, I draw a curved UIBezierPath an an MKOverlayPathView class to show flight routes. This is the code I am using:

```<code>- (UIBezierPath *)pathForOverlayForMapRect:(MKMapRect)mapRect {

    ... bla bla bla ...

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:s];
    [path addQuadCurveToPoint:e controlPoint:cp1];
    [path addLineToPoint:e2];
    [path addQuadCurveToPoint:s2 controlPoint:cp2];
    [path closePath];

    return path;
  }
</code>```

```<code>- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context{

    self.mapRect = mapRect;

    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
    CGContextSetLineWidth(context, mapRect.size.height/700);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGContextSetLineCap(context, kCGLineCapRound);

    CGContextAddPath(context, [self pathForOverlayForMapRect:mapRect].CGPath);

    [self updateTouchablePathForMapRect:mapRect];

    CGContextDrawPath(context, kCGPathFillStroke);

}
</code>```

This is working just fine but I would like to draw a gradient along that path instead of just a fill color. And this is where it is starting to get very tricky.

I have experimented with CGContextDrawLinearGradient() but it hasn't got me anywhere useful yet.

答:
In Swift 3 this can be achieved using the code below. This example is for a straight line but the same principles should apply.</p>

```<code>    let startPoint = CGPoint(x:100, y:100)
    let endPoint = CGPoint(x: 300, y:400)

    let context = UIGraphicsGetCurrentContext()!
    context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0);
    // create a line
    context.move(to: startPoint)
    context.addLine(to: endPoint)
    context.setLineWidth(4)
    // use the line created above as a clipping mask
    context.replacePathWithStrokedPath()
    context.clip()

    // create a gradient
    let locations: [CGFloat] = [ 0.0, 0.5 ]

    let colors = [UIColor.green.cgColor,
                  UIColor.white.cgColor]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    let gradient = CGGradient(colorsSpace: colorspace,
                              colors: colors as CFArray, locations: locations)

    let gradientStartPoint = CGPoint(x: rect.midX, y: rect.minY)
    let gradientEndPoint = CGPoint(x: rect.midX, y: rect.maxY)

    context.drawLinearGradient(gradient!,
                                start: gradientStartPoint, end: gradientEndPoint,
                                options: .drawsBeforeStartLocation)
    UIGraphicsEndImageContext()
</code>```

Body:
In an app, I draw a curved UIBezierPath an an MKOverlayPathView class to show flight routes. This is the code I am using:

- (UIBezierPath *)pathForOverlayForMapRect:(MKMapRect)mapRect {

    ... bla bla bla ...

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:s];
    [path addQuadCurveToPoint:e controlPoint:cp1];
    [path addLineToPoint:e2];
    [path addQuadCurveToPoint:s2 controlPoint:cp2];
    [path closePath];

    return path;
  }

- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context{

    self.mapRect = mapRect;

    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
    CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0);
    CGContextSetLineWidth(context, mapRect.size.height/700);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    CGContextSetLineCap(context, kCGLineCapRound);

    CGContextAddPath(context, [self pathForOverlayForMapRect:mapRect].CGPath);

    [self updateTouchablePathForMapRect:mapRect];

    CGContextDrawPath(context, kCGPathFillStroke);

}

This is working just fine but I would like to draw a gradient along that path instead of just a fill color. And this is where it is starting to get very tricky.

I have experimented with CGContextDrawLinearGradient() but it hasn't got me anywhere useful yet.

Body:
In Swift 3 this can be achieved using the code below. This example is for a straight line but the same principles should apply.

    let startPoint = CGPoint(x:100, y:100)
    let endPoint = CGPoint(x: 300, y:400)

    let context = UIGraphicsGetCurrentContext()!
    context.setStrokeColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0);
    // create a line
    context.move(to: startPoint)
    context.addLine(to: endPoint)
    context.setLineWidth(4)
    // use the line created above as a clipping mask
    context.replacePathWithStrokedPath()
    context.clip()

    // create a gradient
    let locations: [CGFloat] = [ 0.0, 0.5 ]

    let colors = [UIColor.green.cgColor,
                  UIColor.white.cgColor]

    let colorspace = CGColorSpaceCreateDeviceRGB()

    let gradient = CGGradient(colorsSpace: colorspace,
                              colors: colors as CFArray, locations: locations)

    let gradientStartPoint = CGPoint(x: rect.midX, y: rect.minY)
    let gradientEndPoint = CGPoint(x: rect.midX, y: rect.maxY)

    context.drawLinearGradient(gradient!,
                                start: gradientStartPoint, end: gradientEndPoint,
                                options: .drawsBeforeStartLocation)
    UIGraphicsEndImageContext()


问:
subprocess.Popen not working in ubuntu (working fine in Windows)
I am right now in the same directory in which the file "lookup.csv" is residing.

I have tried following commands in Python 2.7:

```<code>import subprocess
subprocess.Popen("lookup.csv", shell = True)
</code>```

The above is producing the following error:

lookup.csv : not found

I have double-checked for the working directory, tried lot of available troubleshooting options given in StakExchange, tried the same in Windows (and surprisingly it was working there), what more can I do?

答: There's no reason why this should work on Windows because lookup.csv clearly is a file which you want to open with open whereas subprocess.Popen creates a new process for working with the lookup.csv binary. Maybe Windows handles process failure differently.

Body:
I am right now in the same directory in which the file "lookup.csv" is residing.

I have tried following commands in Python 2.7:

import subprocess
subprocess.Popen("lookup.csv", shell = True)

The above is producing the following error:

lookup.csv : not found

I have double-checked for the working directory, tried lot of available troubleshooting options given in StakExchange, tried the same in Windows (and surprisingly it was working there), what more can I do?


问:
How do I make an Android EditView 'Done' button and hide the keyboard when clicked?
When the user clicks on the EditView, Android opens the keyboard so that user can write in the EditView.

The problem is, when the user is done writing, there is no way to hide the keyboard. The user has to press the back button to hide the keyboard.

Is there a way to display a Done button on the keyboard that will hide the keyboard?

答:
I have to point that out as a lot of people can struggle into that without knowing the problem.

If you want the kb to hide when clicking Done, and you set android:imeOptions="actionDone" & android:maxLines="1" without setting your EditText inputType it will NOT work as the default inputType for the EditText is not "text" as a lot of people think.

so, setting only inputType will give you the results you desire whatever what you are setting it to like "text", "number", ...etc.


问:
The gap that appears on swiping UIPageViewController -- Swift
I have created a container for "modul screens" with UIPageViewController.  The main problem is a wrong size if set previous screen.

On screenshot you can see that are showed 2 screens instead 1.

For setting a new screen I use

```<code>func launchViewControllerC(vc: USBaseVaultStepViewcontroller,
                           step: UIPageViewControllerNavigationDirection,
                           animated: Bool = true) {
    vc.delegate = self

    self.pageController.setViewControllers([vc],
                                           direction: step,
                                           animated: true,
                                           completion: nil)

}
</code>```

and for the previous screen I use:

```<code>func launchPreviousScreen() {
    guard let previousStep = self.currentSetupStep.previousStep() else {
        return
    }

    guard let previousController = self.setupStepViewControllerForStep(previousStep) else {
        return
    }

    self.currentSetupStep = previousStep
    previousController.delegate = self

    self.pageController.setViewControllers([previousController],
                                           direction: UIPageViewControllerNavigationDirection.Reverse,
                                           animated: true,
                                           completion: nil)
}
</code>```

TIP: It happens when setViewControllers  has animated true.
Also I have found out that completion block doesn't work properly.

答:
On a storyboard where is located my container with PageViewController I have disabled option Autoresize Subview. And the "gap" during animation disappeared.

But the description above isn't solution just a clue.
The main problem was subHeader that showed on the screen. I was changing height constraint in runtime that is why UIPageViewController didn't know correct size of the screens.
I had to separate my screens and I've made Inner screen. I'm using  UIPageViewController in UIPageViewController. And for know animation works perfect.

Body:
I have created a container for "modul screens" with UIPageViewController.  The main problem is a wrong size if set previous screen.

On screenshot you can see that are showed 2 screens instead 1.

For setting a new screen I use

func launchViewControllerC(vc: USBaseVaultStepViewcontroller,
                           step: UIPageViewControllerNavigationDirection,
                           animated: Bool = true) {
    vc.delegate = self

    self.pageController.setViewControllers([vc],
                                           direction: step,
                                           animated: true,
                                           completion: nil)

}

and for the previous screen I use:

func launchPreviousScreen() {
    guard let previousStep = self.currentSetupStep.previousStep() else {
        return
    }

    guard let previousController = self.setupStepViewControllerForStep(previousStep) else {
        return
    }

    self.currentSetupStep = previousStep
    previousController.delegate = self

    self.pageController.setViewControllers([previousController],
                                           direction: UIPageViewControllerNavigationDirection.Reverse,
                                           animated: true,
                                           completion: nil)
}

TIP: It happens when setViewControllers  has animated true.
Also I have found out that completion block doesn't work properly.


问:
Meteor initial page load very long
With my Meteor App, I recently started to encounter a very long load time on the initial page load. Inspecting the requests to/from the page, it seems the load is hanging on a websocket request:

This issue was not present until recently and I'm not even sure how to start troubleshooting this. I'm going to start rolling back commits to see where the problem started, but any thoughts on what could cause this or where to look would be greatly appreciated.

答: I was able to resolve this issue by using Meteor DevTools to inspect the calls between the client and server. It seems I unintentionally published an entire collection of 22,000 documents (and growing) to the local collections in the browser on each reload. Quick filter in the collection publish and all is resolved.</p>

Title: Meteor initial page load very long


问:
How to Execute .cypher file using Neo4j 3.1.4 (Not Through .zip File)
I'm new to Neo4j and I have imported data from csv files using the browser console. I've downloaded Neo4j and went through the installation not using the .zip file which contains many tools such as neo4j-shell.bat and neo4j-admin.bat.

How can I execute multiple queries which I've made into .cypher file?
I can't seem to find the answer.

答:
I believe cypher-shell.bat is part of the Windows CE EXE installation. You can run cypher scripts with that.

Check https://neo4j.com/docs/operations-manual/current/tools/cypher-shell/ for more details.

Hope this helps,
Tom


问:
Bash - How to get multi line text between XML tags
I have a text file...

```<code># <?xml version="1.0" encoding="UTF-8"?>
<response>
<content>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K</content>
</response>
</code>```

and I want to extract the text between <content> up to </content>. I have tried:

```<code>grep -oP '(?<=<content> ).*?(?= </content>)' file
</code>```

But it doesn't output anything, I want the end result to be like this:

```<code>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K
</code>```

How can I do this?

答:
With GNU grep and Perl regular expression (-P):

```<code>grep -Poz '(?<=<content>)(.*\n)*.*(?=</content>)' file.xml
</code>```

Output:

```
Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K
```

Body:
I have a text file...

# <?xml version="1.0" encoding="UTF-8"?>
<response>
<content>Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K</content>
</response>

and I want to extract the text between <content> up to </content>. I have tried:

grep -oP '(?<=<content> ).*?(?= </content>)' file

But it doesn't output anything, I want the end result to be like this:

Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K

How can I do this?

Body:
With GNU grep and Perl regular expression (-P):

grep -Poz '(?<=<content>)(.*\n)*.*(?=</content>)' file.xml

Output:

Pulsa:Rp200,Bonus:0 s/d 12-JUL-17. 1GB Rp10rb.Mau?
1. Mau
2. Info
3. Internet
4. RAMADHAN HOTSALE
5. Nelpon
6. SMS
7. BB
8. NEW:UNLIMITED INTERNET
9. Roaming
10. 100MB2K


问:
Should defined numbers be stored in a table within the database?
Imagine you have a table - lets contrive an example where this is Orders - which has a field named type, which may be only one of a few fixed values (lets say 0 or 1, for Quotation and Order).

Should all the possible values of type be represented by another table in the database (with just typeID and typeName columns?), and Orders made to reference the new table?

Or is it normal to leave these numbers as-is and have them documented outside the database?

If this is a "it depends" situation: What are the important implications of both options?

I have used the first option in a recent University assignement, but without really thinking about why - and looking back at the design now I'm wondering whether this is important.

I never once queried the reference table as part of my application - because I didn't "need" to - does this indicate the reference table is unneeded, or is this a flaw in my application because it should be checking the ref table (what for?)?

答:
Typically a second table with typeID and typeName, with typeID as primary key, and a foreign key in the Orders table.

These can be used later for filtering from the client side.

And also, later there might be more information pertinent to the actual type, that can then be stored in the same table.


问:
Dictionary without generics
I'm learning C# and I have an exercise with these three classes:

```<code>public abstract BaseClass<T> Where T : BaseClass<T>

public class Class1

public class Class2 : BaseClass<Class2>
</code>```

On the exercise there is this:

```<code>var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };
</code>```

I think that here, Dictionary is a shortcut for Dictionary<object, object>
; so I have added this class to the project:

```<code>public class Dictionary : Dictionary<object, object>
</code>```

My problem here is that I'm not sure if I have declared correctly Dictionary. Now the exercise works perfectly but maybe there is another option to declare Dictionary. By the way, I have used dynamic instead of object and it also works.

My question is:

In the exercise, is Dictionary a custom class or is another class from .NET Framework or whatever that I don't know?

答:
The syntax from the exercise is invalid:

```<code>var dictionary = new Dictionary {
    [class1] = class1
,   [class2] = class2
};
</code>```

This looks like a C# 6 dictionary initializer, which expects type parameters of the dictionary to be specified explicitly:

```<code>var dictionary = new Dictionary<object,object> {
    [class1] = class1
,   [class2] = class2
};
</code>```

You do not need to create your own class derived from Dictionary<TKey,TVal>, or use dynamic.

Note: Using object for both key and value type is required because your dictionary example uses classes Class1 and Class2 as both keys and values, while the classes have no common ancestor other than object.

Edit:

I can't modify the exercise. So, I need to do something to make it compile

Your solution that derives Dictionary from Dictionary<object,object> is fine then. You can also write your own Dictionary class that takes a dictionary-like initializer, but that would be a much harder exercise.

Title: Dictionary without generics

Body:
I'm learning C# and I have an exercise with these three classes:

public abstract BaseClass<T> Where T : BaseClass<T>

public class Class1

public class Class2 : BaseClass<Class2>

On the exercise there is this:

var dictionary = new Dictionary { [class1] = class1, [class2] = class2 };

I think that here, Dictionary is a shortcut for Dictionary<object, object>
; so I have added this class to the project:

public class Dictionary : Dictionary<object, object>

My problem here is that I'm not sure if I have declared correctly Dictionary. Now the exercise works perfectly but maybe there is another option to declare Dictionary. By the way, I have used dynamic instead of object and it also works.

My question is:

In the exercise, is Dictionary a custom class or is another class from .NET Framework or whatever that I don't know?

Body:
The syntax from the exercise is invalid:

var dictionary = new Dictionary {
    [class1] = class1
,   [class2] = class2
};

This looks like a C# 6 dictionary initializer, which expects type parameters of the dictionary to be specified explicitly:

var dictionary = new Dictionary<object,object> {
    [class1] = class1
,   [class2] = class2
};

You do not need to create your own class derived from Dictionary<TKey,TVal>, or use dynamic.

Note: Using object for both key and value type is required because your dictionary example uses classes Class1 and Class2 as both keys and values, while the classes have no common ancestor other than object.

Edit:

I can't modify the exercise. So, I need to do something to make it compile

Your solution that derives Dictionary from Dictionary<object,object> is fine then. You can also write your own Dictionary class that takes a dictionary-like initializer, but that would be a much harder exercise.


问:
Optimized strcmp implementation
This function was found here. It's an implementation of strcmp:

```<code>int strcmp(const char* s1, const char* s2)
{
    while (*s1 && (*s1 == *s2))
        s1++, s2++;
    return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
</code>```

I understand all but the last line, in short what is going on in the last line?

答:
This implementation can be further optimized, shaving off some comparisons:

```<code>int strcmp(const char *s1, const char *s2) {
    unsigned char c1, c2;
    while ((c1 = *s1++) == (c2 = *s2++)) {
        if (c1 == '\0')
            return 0;
    }
    return c1 - c2;
}
</code>```

The return value is 0 if the string are identical up to and including the terminating null byte.  The sign of the return value is that of the difference between the first differing characters, converted to unsigned char as per the C Standard.

If char is smaller than int, which is true on all but some rare embedded systems, this difference can be computed with a simple subtraction, both c1 and c2 being promoted to int and this difference is guaranteed to fit in the range of type int.

On systems where sizeof(int) == 1, the return value should be computed this way:

```<code>return (c1 < c2) ? -1 : 1;
</code>```

Title: Optimized strcmp implementation

Body:
This function was found here. It's an implementation of strcmp:

int strcmp(const char* s1, const char* s2)
{
    while (*s1 && (*s1 == *s2))
        s1++, s2++;
    return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}

I understand all but the last line, in short what is going on in the last line?

Body:
This implementation can be further optimized, shaving off some comparisons:

int strcmp(const char *s1, const char *s2) {
    unsigned char c1, c2;
    while ((c1 = *s1++) == (c2 = *s2++)) {
        if (c1 == '\0')
            return 0;
    }
    return c1 - c2;
}

The return value is 0 if the string are identical up to and including the terminating null byte.  The sign of the return value is that of the difference between the first differing characters, converted to unsigned char as per the C Standard.

If char is smaller than int, which is true on all but some rare embedded systems, this difference can be computed with a simple subtraction, both c1 and c2 being promoted to int and this difference is guaranteed to fit in the range of type int.

On systems where sizeof(int) == 1, the return value should be computed this way:

return (c1 < c2) ? -1 : 1;


问:
Batch update returned unexpected row count from update [0];
I use this entity in order to record into database.

```<code>@Entity
@Table(name = "SYSTEM_USERS")
public class SystemUsersModel implements Serializable
{
    private static final long serialVersionUID = 8432414340180447723L;

    @Id
    @GeneratedValue
    private Integer id;

    @Column
    private String username;

    @Column
    private String email;

    @Column
    @Type(type = "date")
    @Temporal(TemporalType.DATE)
    private Date lastlogin;

    @Column
    private String password;

    @Column
    private String salt;

    @Column
    @Type(type = "date")
    @Temporal(TemporalType.DATE)
    private Date added;
</code>```

Delete query:

```<code>SessionFactory factory = HibernateUtils.getSessionFactory();
        Session session = factory.getCurrentSession();

        try
        {
            session.getTransaction().begin();

            SystemUsersModel obj = new SystemUsersModel();
            obj.setId(userlist.getId());

            session.delete(obj);

            session.getTransaction().commit();

            blacklists.remove(selectedBlackListEntry);
            selectedBlackListEntry = null;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
</code>```

Then I run the code I get this error:

```<code>Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
</code>```

I had inserted several rows using script before I start the application.
How I can solve this issue?

答:
When you manage instances of objects with hibernate, they have to be "attached" to the session.

If you create an object with new you need first to attach it to the session before you can manage it with hibernate.

When an object (with generated id) has an id value, hibernate expects that the object exist in his session (because the id value can only exist if hibernate had generated it or hibernate has brought it from the database via a query), otherwise it throws the Stale Exception.

You have to either call saveOrUpdate on it for hibernate to create its Id and attach the instance to the session (in case it doesn't exist in the database), or call load with the id for hibernate to bring the instance from the database (in case it exists in the database).

In this case you know the id,  so you have to query hibernate to obtain an attached instance. So, try this instead:

```<code>SystemUsersModel obj = session.load(SystemUsersModel.class, userlist.getId());
session.delete(obj);
</code>```

Here is the explanation of the different states of an instance respect of the hibernate session: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html

Edit: Thanks to @vanoekel

Or better, instead of load you can just use getReference as it will be less expensive in terms of resources, if you just want to delete it afterwords.

Body:
I use this entity in order to record into database.

@Entity
@Table(name = "SYSTEM_USERS")
public class SystemUsersModel implements Serializable
{
    private static final long serialVersionUID = 8432414340180447723L;

    @Id
    @GeneratedValue
    private Integer id;

    @Column
    private String username;

    @Column
    private String email;

    @Column
    @Type(type = "date")
    @Temporal(TemporalType.DATE)
    private Date lastlogin;

    @Column
    private String password;

    @Column
    private String salt;

    @Column
    @Type(type = "date")
    @Temporal(TemporalType.DATE)
    private Date added;

Delete query:

SessionFactory factory = HibernateUtils.getSessionFactory();
        Session session = factory.getCurrentSession();

        try
        {
            session.getTransaction().begin();

            SystemUsersModel obj = new SystemUsersModel();
            obj.setId(userlist.getId());

            session.delete(obj);

            session.getTransaction().commit();

            blacklists.remove(selectedBlackListEntry);
            selectedBlackListEntry = null;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            session.getTransaction().rollback();
        }

Then I run the code I get this error:

Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

I had inserted several rows using script before I start the application.
How I can solve this issue?

Body:
When you manage instances of objects with hibernate, they have to be "attached" to the session.

If you create an object with new you need first to attach it to the session before you can manage it with hibernate.

When an object (with generated id) has an id value, hibernate expects that the object exist in his session (because the id value can only exist if hibernate had generated it or hibernate has brought it from the database via a query), otherwise it throws the Stale Exception.

You have to either call saveOrUpdate on it for hibernate to create its Id and attach the instance to the session (in case it doesn't exist in the database), or call load with the id for hibernate to bring the instance from the database (in case it exists in the database).

In this case you know the id,  so you have to query hibernate to obtain an attached instance. So, try this instead:

SystemUsersModel obj = session.load(SystemUsersModel.class, userlist.getId());
session.delete(obj);

Here is the explanation of the different states of an instance respect of the hibernate session: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html

Edit: Thanks to @vanoekel

Or better, instead of load you can just use getReference as it will be less expensive in terms of resources, if you just want to delete it afterwords.


问:
Starting previous activity with Intent, without creating a new one
I want to have my MainActivity which shows a list of different TextViews.
The second Activity contains an EditText field. When I hit 'Submit' in the second Activity, I want to add the String from EditText to the list of TextViews in MainActivity.

The problem I have is that there is a new MainActivity started each time, so that only the latest Text is shown. I want to go back to my MainActivity and kind of "collect" the texts in there. Here is some code:

The MainActivity:

```<code>public class FullTimeline extends AppCompatActivity {

    private LinearLayout linLayout;
    private FloatingActionButton addEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_timeline);
        linLayout = (LinearLayout) findViewById(R.id.entriesLinear);
        addEntry = (FloatingActionButton) findViewById(R.id.floatingActionButton); //starts the second Activity with the EditText

        //Here I want to get the text from my second Activity
        Intent intent = getIntent();
        String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
        linLayout.addView(createNewTextView(entry), 0);
    }

    public void openEntryActivity(View view){
        Intent intent = new Intent(this, EntryTextActivity.class);
        startActivity(intent);

    }

    private TextView createNewTextView(String text) {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        final TextView textView = new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText(text);
        return textView;
    }
}
</code>```

This is the second Activity with the EditText:

```<code>public class EntryTextActivity extends AppCompatActivity {

public static final String EXTRA_ENTRY = "com.xyz.ENTRY";
    private Button submitButton;
    private EditText editTextEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry_text);
        submitButton = (Button) findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EntryTextActivity.this, FullTimeline.class);
                editTextEntry = (EditText) findViewById(R.id.editTextEntry);
                String entryText = editTextEntry.getText().toString();
                intent.putExtra(EXTRA_ENTRY, entryText);
                startActivity(intent);//this starts a new instance of the MainActivity ?
            }
        });
    }
}
</code>```

I hope that helps understanding my problem. I could not find any working solutions on here.

答:
You need to use startActivityForResult()

Here's a Nishant's simple explanation on how to work with it:
- https://stackoverflow.com/a/10407371/5648172

Basically, you want to start your EntryTextActivity with startActivityForResult() instead of startActivity().

Body:
I want to have my MainActivity which shows a list of different TextViews.
The second Activity contains an EditText field. When I hit 'Submit' in the second Activity, I want to add the String from EditText to the list of TextViews in MainActivity.

The problem I have is that there is a new MainActivity started each time, so that only the latest Text is shown. I want to go back to my MainActivity and kind of "collect" the texts in there. Here is some code:

The MainActivity:

public class FullTimeline extends AppCompatActivity {

    private LinearLayout linLayout;
    private FloatingActionButton addEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_timeline);
        linLayout = (LinearLayout) findViewById(R.id.entriesLinear);
        addEntry = (FloatingActionButton) findViewById(R.id.floatingActionButton); //starts the second Activity with the EditText

        //Here I want to get the text from my second Activity
        Intent intent = getIntent();
        String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
        linLayout.addView(createNewTextView(entry), 0);
    }

    public void openEntryActivity(View view){
        Intent intent = new Intent(this, EntryTextActivity.class);
        startActivity(intent);

    }

    private TextView createNewTextView(String text) {
        final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        final TextView textView = new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText(text);
        return textView;
    }
}

This is the second Activity with the EditText:

public class EntryTextActivity extends AppCompatActivity {

public static final String EXTRA_ENTRY = "com.xyz.ENTRY";
    private Button submitButton;
    private EditText editTextEntry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_entry_text);
        submitButton = (Button) findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EntryTextActivity.this, FullTimeline.class);
                editTextEntry = (EditText) findViewById(R.id.editTextEntry);
                String entryText = editTextEntry.getText().toString();
                intent.putExtra(EXTRA_ENTRY, entryText);
                startActivity(intent);//this starts a new instance of the MainActivity ?
            }
        });
    }
}

I hope that helps understanding my problem. I could not find any working solutions on here.


问:
How to crawl multiple keywords with python icrawler
I have an array with a lot of keywords:

```<code>array = ['table', 'chair', 'pen']
</code>```

I want to crawl 5 images from Google Image Search for each item in my array with python icrawler

Here is the initialization:

```<code>from icrawler.builtin import GoogleImageCrawler

google_crawler = GoogleImageCrawler(
  parser_threads=2,
  downloader_threads=4,
  storage={ 'root_dir': 'images' }
)
</code>```

I use a loop to crawl each item:

```<code>for item in array:
  google_crawler.crawl(
    keyword=item,
    offset=0,
    max_num=5,
    min_size=(500, 500)
  )
</code>```

However, I get the error log:

```<code>  File "crawler.py", line 20, in <module>
    min_size=(500, 500)
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/site-packages/icrawler/builtin/google.py", line 83, in crawl
    feeder_kwargs=feeder_kwargs, downloader_kwargs=downloader_kwargs)
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/site-packages/icrawler/crawler.py", line 166, in crawl
    self.feeder.start(**feeder_kwargs)
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/site-packages/icrawler/utils/thread_pool.py", line 66, in start
    worker.start()
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/threading.py", line 842, in start
    raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
</code>```

which seems that I cannot use google_crawler.crawl more than once. How can I fix that?

答:
In the latest version, you can use it like this.

```<code>from icrawler.builtin import GoogleImageCrawler

google_crawler = GoogleImageCrawler(
    parser_threads=2,
    downloader_threads=4,
    storage={'root_dir': 'images'}
)

for keyword in ['cat', 'dog']:
    google_crawler.crawl(
        keyword=keyword, max_num=5, min_size=(500, 500), file_idx_offset='auto')
    # set `file_idx_offset` to 'auto' will prevent naming the 5 images
    # of dog from 000001.jpg to 000005.jpg, but naming it from 000006.jpg.
</code>```

or if you want to download these images to different folders, you can simply create two GoogleImageCrawler instances.

```<code>from icrawler.builtin import GoogleImageCrawler

for keyword in ['cat', 'dog']:
    google_crawler = GoogleImageCrawler(
        parser_threads=2,
        downloader_threads=4,
        storage={'root_dir': 'images/{}'.format(keword)}
    )
    google_crawler.crawl(
        keyword=keyword, max_num=5, min_size=(500, 500))
</code>```

Body:
I have an array with a lot of keywords:

array = ['table', 'chair', 'pen']

I want to crawl 5 images from Google Image Search for each item in my array with python icrawler

Here is the initialization:

from icrawler.builtin import GoogleImageCrawler

google_crawler = GoogleImageCrawler(
  parser_threads=2,
  downloader_threads=4,
  storage={ 'root_dir': 'images' }
)

I use a loop to crawl each item:

for item in array:
  google_crawler.crawl(
    keyword=item,
    offset=0,
    max_num=5,
    min_size=(500, 500)
  )

However, I get the error log:

  File "crawler.py", line 20, in <module>
    min_size=(500, 500)
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/site-packages/icrawler/builtin/google.py", line 83, in crawl
    feeder_kwargs=feeder_kwargs, downloader_kwargs=downloader_kwargs)
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/site-packages/icrawler/crawler.py", line 166, in crawl
    self.feeder.start(**feeder_kwargs)
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/site-packages/icrawler/utils/thread_pool.py", line 66, in start
    worker.start()
  File "/home/user/opt/miniconda3/envs/pak/lib/python3.6/threading.py", line 842, in start
    raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once

which seems that I cannot use google_crawler.crawl more than once. How can I fix that?

Body:
In the latest version, you can use it like this.

from icrawler.builtin import GoogleImageCrawler

google_crawler = GoogleImageCrawler(
    parser_threads=2,
    downloader_threads=4,
    storage={'root_dir': 'images'}
)

for keyword in ['cat', 'dog']:
    google_crawler.crawl(
        keyword=keyword, max_num=5, min_size=(500, 500), file_idx_offset='auto')
    # set `file_idx_offset` to 'auto' will prevent naming the 5 images
    # of dog from 000001.jpg to 000005.jpg, but naming it from 000006.jpg.

or if you want to download these images to different folders, you can simply create two GoogleImageCrawler instances.

from icrawler.builtin import GoogleImageCrawler

for keyword in ['cat', 'dog']:
    google_crawler = GoogleImageCrawler(
        parser_threads=2,
        downloader_threads=4,
        storage={'root_dir': 'images/{}'.format(keword)}
    )
    google_crawler.crawl(
        keyword=keyword, max_num=5, min_size=(500, 500))


问:
Node Express APP 1 to N (with MongoDB)
we are developing a big node app with express and MongoDB. We are trying to get the best performance, because we will have multiple clients (maybe 100+) running on the same server.

We were thinking in a one-to-n APP, one instance, one database and multiple clients accessing their domains.

I want to know what is the best settings for this scenario (one server, multiple clients) to performance and development

One instance, one database (clients data would be identified by a company ObjectId on the entry and clients would access a domain or subroute)

One instance, multiple tables (or databases, what is the best?)

Multiple instances, multiple tables

Any other ideas?

On the first setting, the developers will always worry about the current company and this can bring limitations to the app

On the second setting, the concern will continue but the company will not  interfere on the database entries (more clean model)

On the third setting (maybe the best for development) only one company will be treated and brings a lot of possibilities, but may bring performance issues (all instances will run on a single server)

Other settings I have not thought of can be better.

Notes:

We are using the mongoose library

I have some experience with WordPress and i like the way themes and plugins are created for it. We are trying to achieve a level of performance similar to Wordpress with PHP (several Wordpress running on a server efficiently)

sorry about bad english

答:
You don't need to manage multiple instance as you can create a company collection and in that collection you can store every single company and then you just need to create a reference of all these values in users.Please make sure that you have made unique index on company collection.It is really easy handle such scenarios in RDBMS(mysql).

And one more thing you can also run multiple mongod client on same instance by just changing the port and if you are looking for that sort of solution then you can do that as well.

Please note following things before using mongo:-

Please use mongo only if you have over TB's of data because that doesn't make any sense to use mongodb for some mb's or gb's of data.

Use of indexes is must in mongo if you want maximum performance.

Mongo stores all the indexes in main memory and if the indexes size is more then memory that it start swapping of indexes which is really costly and hence please make sure that you have different servers for your application and your db.

I still says it would be better to use RDBMS if you don't have TB's of data to deal with.
Why this approach:-

Let me give you a scenario.
You have 100 companies and with in 100 companies you have 1000 users for each of the company. i.e. you have 1L records in your user collection.Now i want to delete a single user  or i want to update a user or i want to fetch a user from a single company then i don't need to traverse my complete database as i can make a index on my user collection using user-id and company id(compound index)  or even i can make a simple filter query on company id.

For index please read this
https://docs.mongodb.com/manual/core/index-compound/

And btw we are not saving company id as an object instead i am saving only the value of _id from company collection.

Title: Node Express APP 1 to N (with MongoDB)


问:
How can I add Java Template Project in Xcode 4?
I wanna know how can I add Java Template Project in Xcode 4.
I'm working with Eclipse and it's really fine but i want to write Java program in Xcode.
Thanks for helping. ;)</p>

答: I realise this question is 6 years old, but I have a similar problem and found what seems an easy solution. I have an old Java project (2008-9) which I maintain but has been dormant. As I prefer to keep it into Xcode I transferred the whole project (sources, project files and all paraphernalia) to a new development machine running el Capitan with Xcode 7.3.1. I opened the project (which was still in 3.1 version) with it, and tried to build it. It failed as Ant was missing. So I downloaded Ant (version 1.10.1) and copied its bin and lib directories under /usr/local/ant, then I changed the project external build tool configuration (under project, go to Info, and you'll see that parameter) which was set to /usr/bin/ant and set it to /usr/local/ant/bin/ant or wherever you put it. Build again and this time it worked.</p>


问:
How to disconnect discord.py (self)bot?
I am creating a Discord self-bot that will run for multiple users, thus needing to disconnect each time one user is finished with the bot. Is there any way I can programmatically disconnect the selfbot from the user's account without stopping the entire application?

Thanks in advance,

ICT :)

答: Client.logout() or Client.close()

Title: How to disconnect discord.py (self)bot?

Body: Client.logout() or Client.close()


问:
Python - TypeError: module.__init__() takes at most 2 arguments (3 given)
Trying my hand at Python inheritance. I need your help on how to fix an error.

I have 2 classes: Person (super class )& Contact (sub class).

I get the following error when trying to run Contact:

```<code>        "Contact.py", line 3, in <module>
            class Contact(Person):
        TypeError: module.__init__() takes at most 2 arguments (3 given)
</code>```

Thanks in advance

Below is my code:

```<code>class Person:
      __name=""
      __age=0

      def __init__(self, name, age):
          self.__name = name
          self.__age = age

      def set_name(self, name):
          self.__name = name

      def set_age(selfself, age):
          self.__age = age

      def get_name(self):
          return self.__name

      def get_age(selfself):
          return self.__age

      def  getInfo(self):
        return "Name is: {} - Age is: {}".format(self.__name, self.__age)

        # ----------------------------------------------------

    import Person
            class Contact(Person):
        __method=""

        def __init__(self, name, age, method):
            super().__init__(name, age)
            self.__method = method

        def set_method(self, method):
            self.__method = method

        def get__method(self):
            return self.__method

        def getInfo(self):
            return "Name is: {} - Age is: {} - Contact Info: {}".format(self.__name, self.__age, self.__method)

    person2 = Contact("Adam Smith", 19, "Email: adam.smith@abcde.net")
    print(person2.getInfo())
</code>```

答:
First of all, the indentation is messed up!

If Person is in a separate file, import the file name without extension, like this:

```<code>class Person:

  def __init__(self, name, age):
      self.__name = name
      self.__age = age

  def set_name(self, name):
      self.__name = name

  def set_age(self, age):
      self.__age = age

  def get_name(self):
      return self.__name

  def get_age(self):
      return self.__age

  def getInfo(self):
      return "Name is: {} - Age is: {}".format(self.__name, self.__age)

    # ----------------------------------------------------

from person import Person # assumed your Person class is in person.py

class Contact(Person):
    __method=""

    def __init__(self, name, age, method):
        super().__init__(name, age)
        self.__method = method

    def set_method(self, method):
        self.__method = method

    def get__method(self):
        return self.__method

    def getInfo(self):
        return "Name is: {} - Age is: {} - Contact Info: {}".format(self.get_name(), self.get_age(), self.__method)

person2 = Contact("Adam Smith", 19, "Email: adam.smith@abcde.net")
print(person2.getInfo())
</code>```

Access the parent class's private fields through its methods.

Body:
Trying my hand at Python inheritance. I need your help on how to fix an error.

I have 2 classes: Person (super class )& Contact (sub class).

I get the following error when trying to run Contact:

        "Contact.py", line 3, in <module>
            class Contact(Person):
        TypeError: module.__init__() takes at most 2 arguments (3 given)

Thanks in advance

Below is my code:

class Person:
      __name=""
      __age=0

      def __init__(self, name, age):
          self.__name = name
          self.__age = age

      def set_name(self, name):
          self.__name = name

      def set_age(selfself, age):
          self.__age = age

      def get_name(self):
          return self.__name

      def get_age(selfself):
          return self.__age

      def  getInfo(self):
        return "Name is: {} - Age is: {}".format(self.__name, self.__age)

        # ----------------------------------------------------

    import Person
            class Contact(Person):
        __method=""

        def __init__(self, name, age, method):
            super().__init__(name, age)
            self.__method = method

        def set_method(self, method):
            self.__method = method

        def get__method(self):
            return self.__method

        def getInfo(self):
            return "Name is: {} - Age is: {} - Contact Info: {}".format(self.__name, self.__age, self.__method)

    person2 = Contact("Adam Smith", 19, "Email: adam.smith@abcde.net")
    print(person2.getInfo())

Body:
First of all, the indentation is messed up!

If Person is in a separate file, import the file name without extension, like this:

class Person:

  def __init__(self, name, age):
      self.__name = name
      self.__age = age

  def set_name(self, name):
      self.__name = name

  def set_age(self, age):
      self.__age = age

  def get_name(self):
      return self.__name

  def get_age(self):
      return self.__age

  def getInfo(self):
      return "Name is: {} - Age is: {}".format(self.__name, self.__age)

    # ----------------------------------------------------

from person import Person # assumed your Person class is in person.py

class Contact(Person):
    __method=""

    def __init__(self, name, age, method):
        super().__init__(name, age)
        self.__method = method

    def set_method(self, method):
        self.__method = method

    def get__method(self):
        return self.__method

    def getInfo(self):
        return "Name is: {} - Age is: {} - Contact Info: {}".format(self.get_name(), self.get_age(), self.__method)

person2 = Contact("Adam Smith", 19, "Email: adam.smith@abcde.net")
print(person2.getInfo())

Access the parent class's private fields through its methods.