问:
Find all unique xml first nodes under a parent node using xslt
I'm an xsl n00b and trying to find all unique xml nodes under the
 node

Here's my code:

```<code><section>
   <books>
     <book>
       <title>Child 44</title>
       <author>Thomas Rob Smith</author>
       <price>5.00</price>
     </book>
     <book>
       <title>Atlas Shrugged</title>
       <author>Ayn Rand</author>
       <price>7.00</price>
     </book>
   </books>
   <cds>
     <cd>
       <title>A Passage in time</title>
       <band>Authority Zero</band>
       <price>10.00</price>
      </cd>
   </cds>
</section>
</code>```

Here is my desired output:

```<code>books
cds
</code>```

Thanks in advance!

答:
This transformation:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:strip-space elements="*"/>
 <xsl:output method="text"/>

 <xsl:key name="kElByName" match="/*/*" use="name()" />

 <xsl:template match=
  "/*/*[generate-id()=generate-id(key('kElByName',name())[1])]">
  <xsl:value-of select="concat(name(),'\n')"/>
 </xsl:template>
</xsl:stylesheet>
</code>```

when applied on the provided XML document:

```<code><section>
    <books>
        <book>
            <title>Child 44</title>
            <author>Thomas Rob Smith</author>
            <price>5.00</price>
        </book>
        <book>
            <title>Atlas Shrugged</title>
            <author>Ayn Rand</author>
            <price>7.00</price>
        </book>
    </books>
    <cds>
        <cd>
            <title>A Passage in time</title>
            <band>Authority Zero</band>
            <price>10.00</price>
        </cd>
    </cds>
</section>
</code>```

produces the wanted, correct result:

```<code>books
cds
</code>```

Do note: The Munchian method for grouping is used. This is probably the most efficient grouping method for XSLT 1.0.

Body:
I'm an xsl n00b and trying to find all unique xml nodes under the
 node

Here's my code:

   <books>
     <book>
       <title>Child 44</title>
       <author>Thomas Rob Smith</author>
       <price>5.00</price>
     </book>
     <book>
       <title>Atlas Shrugged</title>
       <author>Ayn Rand</author>
       <price>7.00</price>
     </book>
   </books>
   <cds>
     <cd>
       <title>A Passage in time</title>
       <band>Authority Zero</band>
       <price>10.00</price>
      </cd>
   </cds>

Here is my desired output:

books
cds

Thanks in advance!

Body:
This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:strip-space elements="*"/>
 <xsl:output method="text"/>

 <xsl:key name="kElByName" match="/*/*" use="name()" />

 <xsl:template match=
  "/*/*[generate-id()=generate-id(key('kElByName',name())[1])]">
  <xsl:value-of select="concat(name(),'&#xA;')"/>
 </xsl:template>
</xsl:stylesheet>

when applied on the provided XML document:

<section>
    <books>
        <book>
            <title>Child 44</title>
            <author>Thomas Rob Smith</author>
            <price>5.00</price>
        </book>
        <book>
            <title>Atlas Shrugged</title>
            <author>Ayn Rand</author>
            <price>7.00</price>
        </book>
    </books>
    <cds>
        <cd>
            <title>A Passage in time</title>
            <band>Authority Zero</band>
            <price>10.00</price>
        </cd>
    </cds>
</section>

produces the wanted, correct result:

books
cds

Do note: The Munchian method for grouping is used. This is probably the most efficient grouping method for XSLT 1.0.


来源: stackexchange

问:
Qt Qml Javascript - Where to use which?
I'm new to Qt and Qml and I'm trying to figure out how they work together.

I'm confused about where to use C++ and where to use JavaScript. Let's say I have a couple of QML objects (like forms, inputs, dropdowns, etc.). Now obviously these components have some logic code. Should I write this logic code in JavaScript or in C++? Let's say my input has a group of properties and signals. Where and how should these be coded? If I should write it in JavaScript, then how C++ is used. How C++ and JavaScript are connected?  I'm pretty confused! and the docs doesn't help me either. Thanks

答:
The QML language was invented to be used to describe interfaces. It is meant to be simple to understand for designers.

This mean that in a program you will generally have all the logic implemented in C++ and the UI implemented in QML. To make the link between C++ and QML it is necessary to have some C++ code exposed to QML. There a many way to do that.
For instance you could make a C++ class available in QML (see http://doc.qt.io/qt-5/qtqml-cppintegration-topic.html), just make the instance of a singleton available in QML or inject a QObject pointer into the QML environment.  All of this heavily use the Qt meta object system (http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html).

```<code>// in C++
class MyClass
{
    Q_OBJECT
public slots:
    int doSomething();
   ...
};

int main()
{
...
   engine->rootContext()->setContextProperty("foo", new MyClass());
...
}

// in QML

function foobar() {
    var anInt = foo.doSomething();
}
</code>```

QML allowing you to write javascript you can also write a complete program without ever using C++, implementing everything in javascript.
But this is generally a bad idea, especially if you need performances.

Unlike some say, C++ is not here for extending QML. But QML is here to offer a simple interface to C++ objects, allowing developers and designers to create fancy UI without typing/learning C++.

My personal rule when writing QML is to go to C++ as soon as possible. Sure you can write simple functions in QML, but you have to keep them short and simple to leverage the full power of the optimizations of the underlying QML and JS engines. Keeping QML fast is so hard there is a full page in Qt documentation of what to think about when using QML (http://doc.qt.io/qt-5/qtquick-performance.html).

ContentLicense: CC BY-SA 3.0

Title: Qt Qml Javascript - Where to use which?

Body:
The QML language was invented to be used to describe interfaces. It is meant to be simple to understand for designers.

This mean that in a program you will generally have all the logic implemented in C++ and the UI implemented in QML. To make the link between C++ and QML it is necessary to have some C++ code exposed to QML. There a many way to do that.
For instance you could make a C++ class available in QML (see http://doc.qt.io/qt-5/qtqml-cppintegration-topic.html), just make the instance of a singleton available in QML or inject a QObject pointer into the QML environment.  All of this heavily use the Qt meta object system (http://doc.qt.io/qt-5/qtqml-cppintegration-exposecppattributes.html).

// in C++
class MyClass
{
    Q_OBJECT
public slots:
    int doSomething();
   ...
};

int main()
{
...
   engine->rootContext()->setContextProperty("foo", new MyClass());
...
}

// in QML

function foobar() {
    var anInt = foo.doSomething();
}

QML allowing you to write javascript you can also write a complete program without ever using C++, implementing everything in javascript.
But this is generally a bad idea, especially if you need performances.

Unlike some say, C++ is not here for extending QML. But QML is here to offer a simple interface to C++ objects, allowing developers and designers to create fancy UI without typing/learning C++.

My personal rule when writing QML is to go to C++ as soon as possible. Sure you can write simple functions in QML, but you have to keep them short and simple to leverage the full power of the optimizations of the underlying QML and JS engines. Keeping QML fast is so hard there is a full page in Qt documentation of what to think about when using QML (http://doc.qt.io/qt-5/qtquick-performance.html).


问:
Subsetting columns by another column and column index in Pandas
I want to get a certain subset of columns (defined by index range) of rows filtered by another column value. My data frame:

```<code>   A   B   C   D
0  11  b1  c1  d1
1  33  b2  c2  d2
2  22  b3  c3  d3
</code>```

Here I can get all columns of rows by a column criteria:

```<code>df[df['A'] == 33]
</code>```

Also, I can get certain columns of all rows by index:

```<code>df.iloc[:,0:2]
</code>```

Now I want to combine the two along this logic (this doesn't work):

```<code>df[df['A'] == 33, 0:2]
</code>```

Body:
I want to get a certain subset of columns (defined by index range) of rows filtered by another column value. My data frame:

   A   B   C   D
0  11  b1  c1  d1
1  33  b2  c2  d2
2  22  b3  c3  d3

Here I can get all columns of rows by a column criteria:

df[df['A'] == 33]

Also, I can get certain columns of all rows by index:

df.iloc[:,0:2]

Now I want to combine the two along this logic (this doesn't work):

df[df['A'] == 33, 0:2]

Body:
We can combine them together :-)

df.loc[df['A'] == 33].iloc[:,0:2]
Out[464]:
    A   B
1  33  b2

Or

df.iloc[(df['A'] == 33).nonzero()[0],0:2]
Out[471]:
    A   B
1  33  b2


问:
How to connect Spring MVC to a remote MongoDB, to use the MongoOperations interface?
I have setup MongoDB on a local and a remote server, IP: 10.11.12.13.
Connecting using the command-line works when I do the following:

```<code>mongo 10.11.12.13:27017 -u "root" -p "123456" --authenticationDatabase "admin"
</code>```

Furthermore, connecting to localhost using the Spring MVC, works too, and below is my configuration XML:

```<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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->
    <!-- For the autowired Classes -->
    <context:component-scan base-package="com.example">
        <!-- Exclude the Web controllers from the Spring root configuration file -->
        <context:exclude-filter type="regex"
            expression="com.example.controller" />
    </context:component-scan>

    <tx:annotation-driven />

    <!-- Enable @Aspect, @Before, @After -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <mongo:mongo id="mongo" host="localhost" port="27017" />
    <mongo:db-factory dbname="MockDB" mongo-ref="mongo" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>

</beans>
</code>```

This is the pom.xml

```<code>    <properties>
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- Spring -->
        <org.springframework-version>3.2.6.RELEASE</org.springframework-version>
        <org.springsecurity-version>3.2.0.RELEASE</org.springsecurity-version>
        <!-- Hibernate / JPA -->
        <hibernate.version>4.1.8.Final</hibernate.version>
        <mysql.version>5.1.27</mysql.version>
        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>
        <!-- Test -->
        <junit.version>4.11</junit.version>
        <apache-dbcp.version>1.4</apache-dbcp.version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <mockito-version>1.10.19</mockito-version>
        <assertj-version>1.5.0</assertj-version>
        <!-- MongoDB -->
        <jackson.version>1.9.10</jackson.version>
        <mongo.version>1.3.3.RELEASE</mongo.version>
    </properties>

    <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.12.0</version>
    <scope>test</scope>
</dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <!-- Spring Aspect Oriented support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${apache-dbcp.version}</version>
        </dependency>

        <!-- Test Artifacts -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${assertj-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>${mongo.version}</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <scope>runtime</scope>
        </dependency>
        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.2</version>
</dependency>
</code>```

As mentioned, I am using MongoOperations Java interface to manage MongoDB.

I would like to be able to connect to a remote MongoDB just the way I am connecting using a command-line, so I can manage it with MongoOperations.
However, whatever I tried did not work, and I am stuck.  What am I supposed to do/change/add so I can connect to a remote MongoDB ?

答:
If you want you can use a java class to configure mongoDB rather than an XML file.

The code below uses spring-boot and spring-data-mongo in order to access a remote MongoDB > 3.X instance.

```<code>@Configuration
@EnableMongoRepositories()
public class MongoConfig extends AbstractMongoConfiguration {
    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Value("${spring.data.mongodb.host}")
    private String ip;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.authenticationDatabase}")
    private String authDb;

    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Bean(name = "mongoClient")
    public MongoClient mongo() throws UnknownHostException {
        String connection = String.format("mongodb://%s:%s@%s/%s", username, password, ip, authDb);
        return new MongoClient(new MongoClientURI(connection));
    }
}
</code>```

Then inside your view or service you can simply inject the bean mongoClient

Body:
I have setup MongoDB on a local and a remote server, IP: 10.11.12.13.
Connecting using the command-line works when I do the following:

mongo 10.11.12.13:27017 -u "root" -p "123456" --authenticationDatabase "admin"

Furthermore, connecting to localhost using the Spring MVC, works too, and below is my configuration XML:

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.example">

        <context:exclude-filter type="regex"
            expression="com.example.controller" />
    </context:component-scan>

    <tx:annotation-driven />

    <aop:aspectj-autoproxy proxy-target-class="true" />

    <mongo:mongo id="mongo" host="localhost" port="27017" />
    <mongo:db-factory dbname="MockDB" mongo-ref="mongo" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>

</beans>

This is the pom.xml

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

        <org.springframework-version>3.2.6.RELEASE</org.springframework-version>
        <org.springsecurity-version>3.2.0.RELEASE</org.springsecurity-version>

        <hibernate.version>4.1.8.Final</hibernate.version>
        <mysql.version>5.1.27</mysql.version>

        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

        <junit.version>4.11</junit.version>
        <apache-dbcp.version>1.4</apache-dbcp.version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <mockito-version>1.10.19</mockito-version>
        <assertj-version>1.5.0</assertj-version>

        <jackson.version>1.9.10</jackson.version>
        <mongo.version>1.3.3.RELEASE</mongo.version>
    </properties>

    <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.12.0</version>
    <scope>test</scope>
</dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${apache-dbcp.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${assertj-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>${mongo.version}</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.2</version>
</dependency>

As mentioned, I am using MongoOperations Java interface to manage MongoDB.

I would like to be able to connect to a remote MongoDB just the way I am connecting using a command-line, so I can manage it with MongoOperations.
However, whatever I tried did not work, and I am stuck.  What am I supposed to do/change/add so I can connect to a remote MongoDB ?

Body:
If you want you can use a java class to configure mongoDB rather than an XML file.

The code below uses spring-boot and spring-data-mongo in order to access a remote MongoDB > 3.X instance.

@Configuration
@EnableMongoRepositories()
public class MongoConfig extends AbstractMongoConfiguration {
    @Value("${spring.data.mongodb.port}")
    private Integer port;

    @Value("${spring.data.mongodb.host}")
    private String ip;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.authenticationDatabase}")
    private String authDb;

    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Bean(name = "mongoClient")
    public MongoClient mongo() throws UnknownHostException {
        String connection = String.format("mongodb://%s:%s@%s/%s", username, password, ip, authDb);
        return new MongoClient(new MongoClientURI(connection));
    }
}

Then inside your view or service you can simply inject the bean mongoClient


问:
Match first date in line with regex
I'm trying to write a regex search string for Notepad++ that will match the first date on every line.

My text looks something like this:

Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017,  Martin Lægland 31.12.2017 Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

I only want the first date on each line, so excluding 31.12.2017 on the second line.

I've tried \K(([0-9]{2}).([0-9]{2}).([0-9]{4})), but that only gives me the second date, not the first.

答:
Full credit to ctwheels. With a different flavour of it to have boundaries defined

```<code>^.*?\K[0-9]{2}+\.[0-9]{2}+\.[0-9]{4}+
</code>```

Explanation:

```<code>^ asserts position at start of the string
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\K resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match
Match a single character present in the list below [0-9]{2}+
{2}+ Quantifier — Matches exactly 2 times
0-9 a single character in the range between 0 - 9
\. matches the character . literally (case sensitive)
Match a single character present in the list below [0-9]{2}+
{2}+ Quantifier — Matches exactly 2 times
0-9 a single character in the range between 0 - 9
\. matches the character . literally (case sensitive)
Match a single character present in the list below [0-9]{4}+
{4}+ Quantifier — Matches exactly 4 times
0-9 a single character in the range between 0 - 9
Global pattern flags
g modifier: global. All matches (don't return after first match)
</code>```

Title: Match first date in line with regex

Body:
Full credit to ctwheels. With a different flavour of it to have boundaries defined

^.*?\K[0-9]{2}+\.[0-9]{2}+\.[0-9]{4}+

Explanation:

^ asserts position at start of the string
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\K resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match
Match a single character present in the list below [0-9]{2}+
{2}+ Quantifier — Matches exactly 2 times
0-9 a single character in the range between 0 - 9
\. matches the character . literally (case sensitive)
Match a single character present in the list below [0-9]{2}+
{2}+ Quantifier — Matches exactly 2 times
0-9 a single character in the range between 0 - 9
\. matches the character . literally (case sensitive)
Match a single character present in the list below [0-9]{4}+
{4}+ Quantifier — Matches exactly 4 times
0-9 a single character in the range between 0 - 9
Global pattern flags
g modifier: global. All matches (don't return after first match)


问:
Building a generic interactive map from coordinates on Android and iOS
I am working on an app for Android and iOS that needs to display a generic map of the United States (not a Google map, just state borderlines, no more detail needed or wanted). Each state needs to be tappable/highlight-able and the map needs to be easy to resize across the different screen sizes available to Android/iOS.

I've found that my best bet for rendering the map on Android is to use Canvas and on iOS is to use CoreGraphics and CoreAnimations.

I've found state borderline coordinate data on a site called Global Administrative Areas . The sites offer files that can be edited with Gqis.

This brings me to my questions:

Can you use Gqis to produce code that is usable by Canvas on Android and CoreGraphics on iOS?

Does anyone have a better idea on how to approach rendering the interactive generic map?

(edit) Am I on the right track with Canvas and CoreGraphics?

答:
After doing more research, I've found that Gqis, or Qgis as it's called now, does not provide an SDK to interact with geopackage data. I've found two solutions:

a paid solution - use ArcGIS's Spatial Database, Android SDK, and iOS SDK to handle the data from the geopackage.

a free solution - use Qgis to create a Spatial Database that can then be used with the free GeoPackage SDKs provided by the National Geospatial-Intelligence Agency (Android SDK) (iOS SDK) to handle the data from the geopackage.

Lastly, Canvas and CoreGraphics seem to be a good way to handle the actual rendering of the map.


问:
problem in an update form
when i was trying to work on update form I found that there is something wrong in it . the form works well but the new data don't insert to the database but show in the URL

code :

```<code>include"connection.php";

$gid = intval($_GET['id']);
$id = $_POST['product_id'];
$content = $_POST['content'];
$link = $_POST['link'];

if(isset($_POST['saveedit']) && $_POST['saveedit']=='products'){
    $update = mysql_query(" UPDATE products SET
                            content='$content',
                            link='$link'
                            WHERE product_id='$id' ") or die (mysql_error());

    if(isset($update)){
        echo "<b>update is done</b>";
    }
}

$query = mysql_query(" SELECT * FROM products WHERE product_id='".$gid."' ") or die (mysql_error());
$re = mysql_fetch_assoc($query);

if($_REQUEST['do'] == 'edit'){

echo"
<form action='".$_SERVER['PHP_SELF']."' metho='post'>
    <table>
    <tr>
    <td>Link : </td>
    <td><input type='text' name='link' value='".$re['link']."'/></td
    </tr>
    <tr>
    <td>Content :</td>
    <td><textarea name='content'>".$re['content']."</textarea></td>
    </tr>
    <tr>
    <td colspan='2'>
    <input type='submit' name='saveedit' value='save'/>
    <input type='hidden' name='id' value='".$gid."'/>
    <input type='hidden' name='productedit' value='products'/>
    </td>
    </tr>
    </table>
</form>
";
}

$data = mysql_query("SELECT * FROM products ORDER BY product_id");

echo"
    <table width='500' border='1'>
    <tr>
        <td>Link</td>
        <td>Content</td>
        <td>Option</td>
    </tr>
";

while($row = mysql_fetch_assoc($data)){
    echo"
        <tr>
        <td>".$row['link']."</td>
        <td>".$row['content']."</td>
        <td>
            <a href='edit.php?do=edit&id=".$row['product_id']."'> Edit </a>
        </td>
        </tr>
    ";
}
echo"</table>";
</code>```

?>

答:
@Hannan: Try -- </p>

```<code><?php
include "connection.php";

$gid = intval($_GET['id']);

if(isset($_POST['saveedit']) && $_POST['productedit'] == 'products')
{
    $content = $_POST['content'];
    $link    = $_POST['link'];

    $update = mysql_query("UPDATE products SET
                           content='$content',
                           link='$link'
                           WHERE product_id='$gid'") or die (mysql_error());

    if(mysql_affected_rows() > 0)
    {
        echo "<b>update is done</b>";
    }
}

if($_GET['do'] == 'edit')
{
    $query = mysql_query("SELECT * FROM products WHERE product_id='".$gid."' ") or die (mysql_error());
    $re = mysql_fetch_assoc($query);

    echo "
    <form action='".$_SERVER['PHP_SELF']."?id=" . $gid . "' method='post'>
        <table>
        <tr>
        <td>Link : </td>
        <td><input type='text' name='link' value='".$re['link']."'/></td
        </tr>
        <tr>
        <td>Content :</td>
        <td><textarea name='content'>".$re['content']."</textarea></td>
        </tr>
        <tr>
        <td colspan='2'>
        <input type='submit' name='saveedit' value='save'/>
        <input type='hidden' name='productedit' value='products'/>
        </td>
        </tr>
        </table>
    </form>
    ";
}

$data = mysql_query("SELECT * FROM products ORDER BY product_id");

echo "
    <table width='500' border='1'>
    <tr>
        <td>Link</td>
        <td>Content</td>
        <td>Option</td>
    </tr>
";

while($row = mysql_fetch_assoc($data))
{
    echo "
        <tr>
        <td>".$row['link']."</td>
        <td>".$row['content']."</td>
        <td>
            <a href='edit.php?do=edit&id=".$row['product_id']."'> Edit </a>
        </td>
        </tr>
    ";
}
echo "</table>";
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: problem in an update form

Body:
when i was trying to work on update form I found that there is something wrong in it . the form works well but the new data don't insert to the database but show in the URL

code :

include"connection.php";

$gid = intval($_GET['id']);
$id = $_POST['product_id'];
$content = $_POST['content'];
$link = $_POST['link'];

if(isset($_POST['saveedit']) && $_POST['saveedit']=='products'){
    $update = mysql_query(" UPDATE products SET
                            content='$content',
                            link='$link'
                            WHERE product_id='$id' ") or die (mysql_error());

    if(isset($update)){
        echo "update is done";
    }
}

$query = mysql_query(" SELECT * FROM products WHERE product_id='".$gid."' ") or die (mysql_error());
$re = mysql_fetch_assoc($query);

if($_REQUEST['do'] == 'edit'){

echo"
<form action='".$_SERVER['PHP_SELF']."' metho='post'>

    Link :
    <input type='text' name='link' value='".$re['link']."'/></td

    Content :
    <textarea name='content'>".$re['content']."</textarea>

    <input type='submit' name='saveedit' value='save'/>
    <input type='hidden' name='id' value='".$gid."'/>
    <input type='hidden' name='productedit' value='products'/>

</form>
";
}

$data = mysql_query("SELECT * FROM products ORDER BY product_id");

echo"

        Link
        Content
        Option

";

while($row = mysql_fetch_assoc($data)){
    echo"

        ".$row['link']."
        ".$row['content']."

             Edit

    ";
}
echo"
";

?>

Body:
@Hannan: Try --

<?php
include "connection.php";

$gid = intval($_GET['id']);

if(isset($_POST['saveedit']) && $_POST['productedit'] == 'products')
{
    $content = $_POST['content'];
    $link    = $_POST['link'];

    $update = mysql_query("UPDATE products SET
                           content='$content',
                           link='$link'
                           WHERE product_id='$gid'") or die (mysql_error());

    if(mysql_affected_rows() > 0)
    {
        echo "<b>update is done</b>";
    }
}

if($_GET['do'] == 'edit')
{
    $query = mysql_query("SELECT * FROM products WHERE product_id='".$gid."' ") or die (mysql_error());
    $re = mysql_fetch_assoc($query);

    echo "
    <form action='".$_SERVER['PHP_SELF']."?id=" . $gid . "' method='post'>
        <table>
        <tr>
        <td>Link : </td>
        <td><input type='text' name='link' value='".$re['link']."'/></td
        </tr>
        <tr>
        <td>Content :</td>
        <td><textarea name='content'>".$re['content']."</textarea></td>
        </tr>
        <tr>
        <td colspan='2'>
        <input type='submit' name='saveedit' value='save'/>
        <input type='hidden' name='productedit' value='products'/>
        </td>
        </tr>
        </table>
    </form>
    ";
}

$data = mysql_query("SELECT * FROM products ORDER BY product_id");

echo "
    <table width='500' border='1'>
    <tr>
        <td>Link</td>
        <td>Content</td>
        <td>Option</td>
    </tr>
";

while($row = mysql_fetch_assoc($data))
{
    echo "
        <tr>
        <td>".$row['link']."</td>
        <td>".$row['content']."</td>
        <td>
            <a href='edit.php?do=edit&id=".$row['product_id']."'> Edit </a>
        </td>
        </tr>
    ";
}
echo "</table>";
?>


问:
PHP dividing decimal/integer values gives round up output
When I'm dividing,

```<code>echo 50.3228679581385 / 100;
Output:0.50322867958139
</code>```

It should be 0.503228679581385 . Is there any way to avoid default round up?

答:
Yes, there's an INI setting for that, where 14 is the default value:

; The number of significant digits displayed in floating point numbers.

  ; http://php.net/precision

  precision = 14

Increase to 15 or more, as necessary. Also works at runtime like this:

```<code>ini_set('precision', 15);
</code>```

Body:
When I'm dividing,

echo 50.3228679581385 / 100;
Output:0.50322867958139

It should be 0.503228679581385 . Is there any way to avoid default round up?

Body:
Yes, there's an INI setting for that, where 14 is the default value:

; The number of significant digits displayed in floating point numbers.

  ; http://php.net/precision

  precision = 14

Increase to 15 or more, as necessary. Also works at runtime like this:

ini_set('precision', 15);


问:
Is this actually mutating the state?
I've just put together a really basic bit of React functionality to show someone and my console tab is accusing me of mutating the state directly.  I thought that as long as you're using this.setState() that you're basically fine.

This little bit of code just spits out the first person from the person object stored in the state and then when you click the button it increments the age (this actually all works, incidentally).

Am I actually directly mutating the state by doing this?  And if I am, what is the correct way of doing this?

```<code>import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: 'Max', age: 28 },
      { name: 'Stephanie', age: 26 },
      { name: 'Manu', age: 29 },
    ],
  }

  increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }

  render() {
    return (
      <div className="App">
        <h1>This is an app</h1>
        <button onClick={this.increaseAgeHandler}>Add to age</button>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age} />
      </div>
    );
  }
}

export default App;
</code>```

答:
So doing:

```<code>this.state.persons[0].age += 1
</code>```

Is acutally a mutation you want to create a new pointer for the age variable so you're actually going to do:

```<code>this.state.persons[0].age + 1
</code>```

This doesn't mutate previous value and adds a new pointer to your state, if you have any questions about this, just shoot! Hope it's understandable.

Title: Is this actually mutating the state?

Body:
I've just put together a really basic bit of React functionality to show someone and my console tab is accusing me of mutating the state directly.  I thought that as long as you're using this.setState() that you're basically fine.

This little bit of code just spits out the first person from the person object stored in the state and then when you click the button it increments the age (this actually all works, incidentally).

Am I actually directly mutating the state by doing this?  And if I am, what is the correct way of doing this?

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: 'Max', age: 28 },
      { name: 'Stephanie', age: 26 },
      { name: 'Manu', age: 29 },
    ],
  }

  increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }

  render() {
    return (

This is an app

        <button onClick={this.increaseAgeHandler}>Add to age</button>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age} />

    );
  }
}

export default App;

Body:
So doing:

this.state.persons[0].age += 1

Is acutally a mutation you want to create a new pointer for the age variable so you're actually going to do:

this.state.persons[0].age + 1

This doesn't mutate previous value and adds a new pointer to your state, if you have any questions about this, just shoot! Hope it's understandable.


问:
Update state from OnPress if action is true
Im trying to update a constant to be true if user press Yes on an AlertIOS window.

But can't get it working currently its built as

```<code>deleteDeck = () => {
    const {id} = this.props
    const executeRemoval = false
    if (Platform.OS === 'ios') {
      AlertIOS.alert(
        'Remove Deck',
        'Are you sure you want to delete this deck?',
        [
          {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
          {text: 'Yes', onPress: () =>  executeRemoval = true},
        ],
      )
    }
</code>```

And if the user press Yes const executeRemoval should now be true and by that entering

```<code>{executeRemoval &&
      removeDeck(id)
      .then(() =>  this.props.deleteDeck(id))
      .then(() =>  this.props.navigation.dispatch(NavigationActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({ routeName: 'Home'})
          ]
        })))
      }
</code>```

Anyone have any thoughts on how to get this behvior working ?

答:
You need to use a stateful component and save the current state of executeRemoval in it. </p>

```<code>class yourClass extends Component {
    constructor(props){
        super(props);
        this.state = {
            executeRemoval = false
        }
    }
}
</code>```

<p>in your onPress event you do the following: </p>

```<code>onPress={() => this.setState({ executeRemoval: true })}
</code>```

Body:
Im trying to update a constant to be true if user press Yes on an AlertIOS window.

But can't get it working currently its built as

deleteDeck = () => {
    const {id} = this.props
    const executeRemoval = false
    if (Platform.OS === 'ios') {
      AlertIOS.alert(
        'Remove Deck',
        'Are you sure you want to delete this deck?',
        [
          {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
          {text: 'Yes', onPress: () =>  executeRemoval = true},
        ],
      )
    }

And if the user press Yes const executeRemoval should now be true and by that entering

{executeRemoval &&
      removeDeck(id)
      .then(() =>  this.props.deleteDeck(id))
      .then(() =>  this.props.navigation.dispatch(NavigationActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({ routeName: 'Home'})
          ]
        })))
      }

Anyone have any thoughts on how to get this behvior working ?

Body:
You need to use a stateful component and save the current state of executeRemoval in it.

class yourClass extends Component {
    constructor(props){
        super(props);
        this.state = {
            executeRemoval = false
        }
    }
}

in your onPress event you do the following:

onPress={() => this.setState({ executeRemoval: true })}


问:
If clause optimization
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

```<code>if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}
</code>```

Is there a cleaner way to write this condition?

Thanks.

答:
You can reorganize and simplify your conditions using Boolean algebra:</p>

```<code>if (group != G1
    || privilege == P1
    || role == R1
            && (level <= 2 && class == C1
                || level == 1 && (class == C2 || class == C3))
) {
    perform_action_and_exit();
}
</code>```

Title: If clause optimization

Body:
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

Is there a cleaner way to write this condition?

Thanks.

Body:
You can reorganize and simplify your conditions using Boolean algebra:

if (group != G1
    || privilege == P1
    || role == R1
            && (level <= 2 && class == C1
                || level == 1 && (class == C2 || class == C3))
) {
    perform_action_and_exit();
}


问:
Does Google crawl content inside HTML5 template tags?
HTML5 template tags are meant to be completely inert as if the content doesn't exist in the source but is that the case when Google crawls and then indexes a webpage?

Does anyone have any data that can prove one way or another that Google indexes or doesn't index content within template tags? Template tags are great but I don't want to use them if they adversely affect SEO

答:
I experienced something today that would confirm it does affect SEO.

I just received a warning from the Google Search Console about increasing 404 errors, and almost all URL in error are in that form: /some-path/some-page/$%7Bconsent.infoURL%7D.

Once URL decoded, we can see that ${consent.infoURL} is a variable I use in a template tag, on a href attribute:

```<code><template data-template="cookie-notice">
    `<div data-cookie-notice class="cookie-notice" role="dialog">
    <span class="cookie-notice-caption">${consent.captionText}</span>
    <a class="cookie-notice-link" href="${consent.infoURL}">${consent.linkText}</a>
    <button data-button-consent type="button" class="cookie-notice-button">${consent.buttonText}</a>
    </div>`
</template>
</code>```

So Google Bot indeed follows links in template tags.

Body:
I experienced something today that would confirm it does affect SEO.

I just received a warning from the Google Search Console about increasing 404 errors, and almost all URL in error are in that form: /some-path/some-page/$%7Bconsent.infoURL%7D.

Once URL decoded, we can see that ${consent.infoURL} is a variable I use in a template tag, on a href attribute:

<template data-template="cookie-notice">
    `<div data-cookie-notice class="cookie-notice" role="dialog">
    <span class="cookie-notice-caption">${consent.captionText}</span>
    <a class="cookie-notice-link" href="${consent.infoURL}">${consent.linkText}</a>
    <button data-button-consent type="button" class="cookie-notice-button">${consent.buttonText}</a>
    </div>`
</template>

So Google Bot indeed follows links in template tags.


答:
Code

See regex in use here

```<code>^.*?\K\d+\.\d+\.\d+
</code>```

Results

Input

```<code>Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017, Martin Lægland 31.12.2017 Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.
</code>```

Output

```<code>09.09.2017
09.09.2017
09.09.2017
</code>```

Explanation

^ Assert position at the start of the line

.*? Match any character any number of times, but as few as possible

\K Reset the starting point of the reported match. Any previously consumed characters are no longer included in the final match

\d+\.\d+\.\d+ Match any digit one or more times, followed by a dot . literally, followed by the same thing (any digit one or more times, followed by a dot . literally), followed by any digit one or more times

Title: Match first date in line with regex

Body:
I'm trying to write a regex search string for Notepad++ that will match the first date on every line.

My text looks something like this:

Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017,  Martin Lægland 31.12.2017 Publisert på nett.

  Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

I only want the first date on each line, so excluding 31.12.2017 on the second line.

I've tried \K(([0-9]{2}).([0-9]{2}).([0-9]{4})), but that only gives me the second date, not the first.

Body:
Code

See regex in use here

^.*?\K\d+\.\d+\.\d+

Results

Input

Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017, Martin Lægland 31.12.2017 Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

Output

09.09.2017
09.09.2017
09.09.2017

Explanation

^ Assert position at the start of the line

.*? Match any character any number of times, but as few as possible

\K Reset the starting point of the reported match. Any previously consumed characters are no longer included in the final match

\d+\.\d+\.\d+ Match any digit one or more times, followed by a dot . literally, followed by the same thing (any digit one or more times, followed by a dot . literally), followed by any digit one or more times


问:
jQuery fadeIn fadeOut Text looks bad in Internet Explorer IE: getting the fix to work
I have tried the solutions previously posted here (and elsewhere) for text looking pixelated and bad during the jQuery fadeIn and fadeOut in Internet Explorer IE.

Two solutions seem common: add a background color or remove the 'filter' attribute.

With this design I cannot use the background color fix (which helps but does not totally remove the issue anyway).

So I have been trying the "remove the filter attribute after the fadeIn" fix.
But it does not fix the text and the "removeAttribute" version the stops the script.
How are you guys getting it to work?

My jQ code is below.

thanks for considering the question!

====================================

// this loop is based on another Stackoverflow answer by Pointy

```<code>    var divs = $('.myDiv'), i = 0;
    function reveal() {
        if (i == divs.length) divs.fadeIn(inTime, function(){
            $('.mainPadding').css("height", "4000px");
            });
        divs.eq(i).fadeIn(inTime, function(){
               //$(this).style.removeAttribute('filter');
               $(this).removeAttr("filter");
            }).delay(waitTime).fadeOut(outTime, function() {
                i++;
                setTimeout(reveal, 0);
          });
    }
    setTimeout(reveal, 0);
</code>```

答:
Here's what I found on that...
<code>```<br>
 // When fading a html node with the .fadeIn() and .fadeOut()
 // functions in jQuery, IE drops the windows Cleartype rendering;
 // which results in very ugly text. This override corrects that problem  </p>

```<code>    jQuery.fn.fadeTo = function(speed, to, callback) {
        return this.animate({ opacity: to }, speed, function() {
            if (to == 1 && jQuery.browser.msie)
                this.style.removeAttribute('filter');

            if (jQuery.isFunction(callback))
                callback();
        });
    };
</code>```

<p>```</code></p>

Body:
I have tried the solutions previously posted here (and elsewhere) for text looking pixelated and bad during the jQuery fadeIn and fadeOut in Internet Explorer IE.

Two solutions seem common: add a background color or remove the 'filter' attribute.

With this design I cannot use the background color fix (which helps but does not totally remove the issue anyway).

So I have been trying the "remove the filter attribute after the fadeIn" fix.
But it does not fix the text and the "removeAttribute" version the stops the script.
How are you guys getting it to work?

My jQ code is below.

thanks for considering the question!

====================================

// this loop is based on another Stackoverflow answer by Pointy

    var divs = $('.myDiv'), i = 0;
    function reveal() {
        if (i == divs.length) divs.fadeIn(inTime, function(){
            $('.mainPadding').css("height", "4000px");
            });
        divs.eq(i).fadeIn(inTime, function(){
               //$(this).style.removeAttribute('filter');
               $(this).removeAttr("filter");
            }).delay(waitTime).fadeOut(outTime, function() {
                i++;
                setTimeout(reveal, 0);
          });
    }
    setTimeout(reveal, 0);

Body:
Here's what I found on that...

 // When fading a html node with the .fadeIn() and .fadeOut()
 // functions in jQuery, IE drops the windows Cleartype rendering;
 // which results in very ugly text. This override corrects that problem

    jQuery.fn.fadeTo = function(speed, to, callback) {
        return this.animate({ opacity: to }, speed, function() {
            if (to == 1 && jQuery.browser.msie)
                this.style.removeAttribute('filter');

            if (jQuery.isFunction(callback))
                callback();
        });
    };


问:
Bootstrap Button - No Hand Cursor
I am developing an MVC6 project in Visual Studio 2015. I have just added Bootstrap 3.3.6 using Bower. On a very simple html page I have referenced the CSS in the header and Bootstrap at the bottom of the body as follows:

```<code><link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<script type="text/javascript" src="~/lib/bootstrap/dist/js/bootstrap.min.js"></script>
</code>```

I defined a button as follows:

```<code><button class="btn btn-primary">Hello</button>
</code>```

When I debug the project (IIS, IE11) the button appears and is clearly styled by Bootstrap but there is no hand cursor.

If I use the browser to navigate to an example of a Bootstrap styled button, for example here: http://www.w3schools.com/bootstrap/bootstrap_buttons.asp, the hand cursor appears as I would expect. So it's not my browser at fault.

Can anyone suggest why I am not getting a hand cursor from a simple Bootstrap styled button please?

答:
Try adding an href such as href="#" to the button.

```<code><button class="btn btn-primary" href="#">Hello</button>
</code>```

When you start changing native element types and roles there are other side effects, including how those elements interact with accessibility for users. See this MDN link for details on that: Button Role

Title: Bootstrap Button - No Hand Cursor

Body:
I am developing an MVC6 project in Visual Studio 2015. I have just added Bootstrap 3.3.6 using Bower. On a very simple html page I have referenced the CSS in the header and Bootstrap at the bottom of the body as follows:

<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />

I defined a button as follows:

<button class="btn btn-primary">Hello</button>

When I debug the project (IIS, IE11) the button appears and is clearly styled by Bootstrap but there is no hand cursor.

If I use the browser to navigate to an example of a Bootstrap styled button, for example here: http://www.w3schools.com/bootstrap/bootstrap_buttons.asp, the hand cursor appears as I would expect. So it's not my browser at fault.

Can anyone suggest why I am not getting a hand cursor from a simple Bootstrap styled button please?

Body:
Try adding an href such as href="#" to the button.

<button class="btn btn-primary" href="#">Hello</button>

When you start changing native element types and roles there are other side effects, including how those elements interact with accessibility for users. See this MDN link for details on that: Button Role


问:
error while create paypal sandbox , status is "error"
i create  lot of sandbox  but  in status it shows me  "error" what is reason ? .

答: Typically this is caused by some issues with the sandbox system.  For this issue, you would need to file a technical support ticket with PayPal at www.paypal.com/mts </p>


问:
How to add 50 for every number over 4 until 31 in a loop?
Ted is hired for a job, and his employer pays him based on number of days he works in a month.  His employer agrees that Ted’s salary is 3 dollars the first day, 9 dollars the second, 27 dollars the third day and 81 for the fourth day. If he works more than 4 days, his employer agrees to pay 50 dollars per day for each additional day of employment. Create an application that allows the user to select/enter into a textbox the number of days that Ted will work and display his regular pay for the month. </p>

答:
The first thing that you'll need to do validate that the user entered a valid whole number over 0. To do this, you'll need to attempt to convert the value entered into an Integer using Integer.TryParse.

Once the number has been validated, you'll need to keep a running total of the pay. To do this, simply declare an Integer variable since the pay will never contain a decimal.

After you declare the variable, you'll need to check if the days entered is greater than or equal to 1, 2, 3, and/or 4 and then increase the running total respectively by 3, 9, 27, and 81.

Finally, the last step would be to use a For/Next loop to iterate from 5 to the days entered and increment the running total by 50. If the days entered is less than 5 then it will not execute the code inside of the loop.

Here is a quick example demonstrating these instructions:

```<code>'Prompt for the number of days to work
Dim days As Integer = 0
Console.Write("Days to Work: ")

'Loop until the user enters a valid number over 0
Do Until Integer.TryParse(Console.ReadLine(), days) AndAlso days > 0
    'Display the error and re-prompt
    Console.WriteLine("Please enter a valid whole number over 0.")
    Console.Write("Days to Work: ")
Loop

'Keep a running total
Dim total As Integer = 0

'Use a conditional statement to increment the total by 3, 9, 27, and 81 if the days to work are respectively >= 1, 2, 3, 4
If days >= 1 Then
    total += 3
End If
If days >= 2 Then
    total += 9
End If
If days >= 3 Then
    total += 27
End If
If days >= 4 Then
    total += 81
End If

'Now loop from 5 to the number of days to work, if the upper-bounds is less than 5 then the loop won't execute
For counter As Integer = 5 To days
    'Increment the running total by 50
    total += 50
Next

'Display the running total as a currency
Console.WriteLine("Total: {0}", total.ToString("C"))
</code>```

Fiddle: Live Demo

Body:
The first thing that you'll need to do validate that the user entered a valid whole number over 0. To do this, you'll need to attempt to convert the value entered into an Integer using Integer.TryParse.

Once the number has been validated, you'll need to keep a running total of the pay. To do this, simply declare an Integer variable since the pay will never contain a decimal.

After you declare the variable, you'll need to check if the days entered is greater than or equal to 1, 2, 3, and/or 4 and then increase the running total respectively by 3, 9, 27, and 81.

Finally, the last step would be to use a For/Next loop to iterate from 5 to the days entered and increment the running total by 50. If the days entered is less than 5 then it will not execute the code inside of the loop.

Here is a quick example demonstrating these instructions:

'Prompt for the number of days to work
Dim days As Integer = 0
Console.Write("Days to Work: ")

'Loop until the user enters a valid number over 0
Do Until Integer.TryParse(Console.ReadLine(), days) AndAlso days > 0
    'Display the error and re-prompt
    Console.WriteLine("Please enter a valid whole number over 0.")
    Console.Write("Days to Work: ")
Loop

'Keep a running total
Dim total As Integer = 0

'Use a conditional statement to increment the total by 3, 9, 27, and 81 if the days to work are respectively >= 1, 2, 3, 4
If days >= 1 Then
    total += 3
End If
If days >= 2 Then
    total += 9
End If
If days >= 3 Then
    total += 27
End If
If days >= 4 Then
    total += 81
End If

'Now loop from 5 to the number of days to work, if the upper-bounds is less than 5 then the loop won't execute
For counter As Integer = 5 To days
    'Increment the running total by 50
    total += 50
Next

'Display the running total as a currency
Console.WriteLine("Total: {0}", total.ToString("C"))

Fiddle: Live Demo


问:
Java 8 example for if else with Optional
I have a method which returns Optional. Basically, it gets value from DB and if the value from DB is present and if the value is before 20 years, it returns currentDate-20 years or else return as it is.

```<code>Optional<Instant> getJoinDate(final Instant instant) {

        final Optional<Employee> joinTime = empService.retrieveById(1);

        if (joinTime.isPresent()) {

            final Instant joinDate = joinTime.get().getJoinTime().toInstant();

            if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
                return Optional.of(instant.minus(20, ChronoUnit.YEARS));
            }
            else {
                return Optional.of(joinDate);
            }
        }

        return Optional.empty();
    }
</code>```

Is there any simple way to do this with Java 8 without if else?

Thanks

答:
If I understand your code correctly, this is it:

Optional<Instant> getJoinDate(Instant instant) {
    Instant cap = instant.minus(20,ChronoUnit.YEARS)
    return empService.retrieveById(1)
        .map(employee -> employee.getJoinTime().getInstant())
        .map(joinInstant -> joinInstant.before(cap)?cap:joinInstant);
}
```

Body:
I have a method which returns Optional. Basically, it gets value from DB and if the value from DB is present and if the value is before 20 years, it returns currentDate-20 years or else return as it is.

Optional<Instant> getJoinDate(final Instant instant) {

        final Optional<Employee> joinTime = empService.retrieveById(1);

        if (joinTime.isPresent()) {

            final Instant joinDate = joinTime.get().getJoinTime().toInstant();

            if (joinDate.isBefore(instant.minus(20,ChronoUnit.YEARS))) {
                return Optional.of(instant.minus(20, ChronoUnit.YEARS));
            }
            else {
                return Optional.of(joinDate);
            }
        }

        return Optional.empty();
    }

Is there any simple way to do this with Java 8 without if else?

Thanks


答:
```<code>this.state.persons[0].age += 1
</code>```

This changes the age directly because += is an assignment operator. Instead, just add 1 to the age without assigning:

```<code>this.state.persons[0].age + 1
</code>```

Title: Is this actually mutating the state?

Body:
this.state.persons[0].age += 1

This changes the age directly because += is an assignment operator. Instead, just add 1 to the age without assigning:

this.state.persons[0].age + 1


答:
Create a simple function that is going to handle the action you want to run.

Example

```<code>executeRemoval = () => {
  const { id } = this.props;
  removeDeck(id)
  .then(() =>  this.props.deleteDeck(id))
  .then(() =>  this.props.navigation.dispatch(NavigationActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({ routeName: 'Home'})
    ]
  })))
}

deleteDeck = () => {
  if (Platform.OS === 'ios') {
    AlertIOS.alert(
      'Remove Deck',
      'Are you sure you want to delete this deck?',
      [
        {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
        {text: 'Yes', onPress: this.executeRemoval },
      ],
    )
  }
}
</code>```

Title: Update state from OnPress if action is true

Body:
Create a simple function that is going to handle the action you want to run.

Example

executeRemoval = () => {
  const { id } = this.props;
  removeDeck(id)
  .then(() =>  this.props.deleteDeck(id))
  .then(() =>  this.props.navigation.dispatch(NavigationActions.reset({
    index: 0,
    actions: [
      NavigationActions.navigate({ routeName: 'Home'})
    ]
  })))
}

deleteDeck = () => {
  if (Platform.OS === 'ios') {
    AlertIOS.alert(
      'Remove Deck',
      'Are you sure you want to delete this deck?',
      [
        {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
        {text: 'Yes', onPress: this.executeRemoval },
      ],
    )
  }
}


问:
Kendo UI Costom Copy/ Paste Grid like Excel and data source update
I'm trying to add in Kendo UI Grid Copy/ Paste functionality, which will allow to multiply some cells in many other selected cells or to multiply selected rows or to copy several columns and to multiply them somewhere in the same grid - pretty much Excel functionality. What I've done so far is in this JS Bin - http://jsbin.com/xokabumuka/1/edit?html,output
- prepopulate one copied cell value in the same column multiple times, but only in the front end. The same for the rows and of course only for plain text.

I have two problems actually:
First problem - Currently for some reason, I don't know why, I'm loosing "el2" rowIdx on the second iteration. If for example I copy from productName column value "Tea" and select all the cells below in order to prepopulate "Tea" and there after the first iteration my rowIdx is -1
Second problem - How to copy and the nested widget if the selected copied cell has some - for example if column productName contains dropdownlist and I want to copy and paste it along with his data source etc.

答:
Actually I found solutions on my both problems and will share them for all the others who want to make something freaking strange :D

First problem solution - extracted grid.dataSource.data()[e.rowIdx].set(e.colName, e.value) between both foreach cycles - for some reason it breaks current row index

```<code>$.each(copiedData, function(i, el) {
    var IdxNamesValues = []
    $.each(grid.select(), function(i2, el2) {
        var row = $(el2).closest("tr");
        var rowIdx = $("tr", grid.tbody).index(row);
        var colIdx = $("td", row).index(el2);
        if (el.cellIndex === el2.cellIndex) {
            var colName = $('#grid').find('th').eq(el.cellIndex).text();
            var value = el.innerText;
            IdxNamesValues.push({rowIdx, colName, value});
            el2.innerText = el.innerText;
        }
    });

    $.each(IdxNamesValues, function(i, e) {
        grid.dataSource.data()[e.rowIdx].set(e.colName, e.value);
    })
})
</code>```

Second problem solution - I found out that I can get kendo widget by it's HTML representation. For example if I select a column with nested kendoDropDownList widget in there and click Copy I'm getting the below HTML. After that on it I can say copiedData.find('.k-widget input').data("kendoDropDownList") to get that kendoDropDownList as an object with it's all options, dataSource etc...

```<code>    <td class="k-state-selected" role="gridcell" aria-selected="true">
   <span title="" class="k-widget k-dropdown k-header" unselectable="on" role="listbox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-owns="" aria-disabled="false" aria-busy="false" aria-activedescendant="f9fc2fa4-2c3d-4d9c-beef-7d924706fa72" style=""><span unselectable="on" class="k-dropdown-wrap k-state-default"><span unselectable="on" class="k-input">Jane Doe</span><span unselectable="on" class="k-select" aria-label="select"><span class="k-icon k-i-arrow-60-down"></span></span></span><input data-role="dropdownlist" data-text-field="text" data-value-field="id" data-bind="value: name, source: items" style="display: none;"></span>
</td><td class="" role="gridcell">29</td><td class="" role="gridcell">testt</td>
</code>```

I hope will save a lot of time on someone else : )

Body:
Actually I found solutions on my both problems and will share them for all the others who want to make something freaking strange :D

First problem solution - extracted grid.dataSource.data()[e.rowIdx].set(e.colName, e.value) between both foreach cycles - for some reason it breaks current row index

$.each(copiedData, function(i, el) {
    var IdxNamesValues = []
    $.each(grid.select(), function(i2, el2) {
        var row = $(el2).closest("tr");
        var rowIdx = $("tr", grid.tbody).index(row);
        var colIdx = $("td", row).index(el2);
        if (el.cellIndex === el2.cellIndex) {
            var colName = $('#grid').find('th').eq(el.cellIndex).text();
            var value = el.innerText;
            IdxNamesValues.push({rowIdx, colName, value});
            el2.innerText = el.innerText;
        }
    });

    $.each(IdxNamesValues, function(i, e) {
        grid.dataSource.data()[e.rowIdx].set(e.colName, e.value);
    })
})

Second problem solution - I found out that I can get kendo widget by it's HTML representation. For example if I select a column with nested kendoDropDownList widget in there and click Copy I'm getting the below HTML. After that on it I can say copiedData.find('.k-widget input').data("kendoDropDownList") to get that kendoDropDownList as an object with it's all options, dataSource etc...

    <td class="k-state-selected" role="gridcell" aria-selected="true">
   <span title="" class="k-widget k-dropdown k-header" unselectable="on" role="listbox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-owns="" aria-disabled="false" aria-busy="false" aria-activedescendant="f9fc2fa4-2c3d-4d9c-beef-7d924706fa72" style=""><span unselectable="on" class="k-dropdown-wrap k-state-default"><span unselectable="on" class="k-input">Jane Doe</span><span unselectable="on" class="k-select" aria-label="select"><span class="k-icon k-i-arrow-60-down"></span></span></span><input data-role="dropdownlist" data-text-field="text" data-value-field="id" data-bind="value: name, source: items" style="display: none;"></span>
</td><td class="" role="gridcell">29</td><td class="" role="gridcell">testt</td>

I hope will save a lot of time on someone else : )


问:
What's the point of this line in the "Grabbing touch events" section. (Kivy)
I'm confused about touch.grab

Documentation says

The touch coordinate is not translated to your widget space because the touch is coming directly from the Window. It’s your job to convert the coordinate to your local space.

but when I ran the code below

# -*- coding: utf-8 -*-

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.factory import Factory

class DragRecognizer(Factory.Widget):

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            touch.grab(self)
            print('on_drag_begin', touch.pos)
            return True
        else:
            return super().on_touch_down(touch)

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            touch.ungrab(self)
            print('on_drag_end', touch.pos, '(grab)')
            return True
        else:
            print('on_drag_end', touch.pos)
            return super().on_touch_up(touch)

root = Builder.load_string(r'''
<Widget>:
    canvas.after:
        Line:
            rectangle: self.x+2,self.y+2,self.width-3,self.height-3
            dash_offset: 5
            dash_length: 3

BoxLayout:
    Widget:
    RelativeLayout
        DragRecognizer:
            size_hint: 0.8, 0.8
            pos_hint: {'center_x': 0.5, 'center_y': 0.5, }
''')

runTouchApp(root)
```

<p>and pressed mouse button.</p>

<p>screenshot</p>

<p>I expected like this</p>

```on_drag_begin (88, 111)
on_drag_end (88, 111)
on_drag_end (488, 111) (grab)
```

<p>but what I got is</p>

```on_drag_begin (88, 111)
on_drag_end (88, 111)
on_drag_end (88, 111) (grab)
```

Grabbed touch is not Window coordinates! So I don't understand what's the point of the documentation. Sorry for my bad English. I really appreciate if you help me.

答:
You have to convert the coordinate to your local space by using *instance.to_window(instance.pos). Please refer to the example for details.

snippet

```<code>to_window = instance.to_window(*instance.pos)
</code>```

Example

main.py

```<code># -*- coding: utf-8 -*-

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.properties import ListProperty

class DragRecognizer(Factory.Widget):
    pressed = ListProperty([0, 0])

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            touch.grab(self)
            self.pressed = touch.pos
            print('on_touch_down: on_drag_begin', touch.pos)
            return True

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            touch.ungrab(self)
            print('on_touch_up: on_drag_end', touch.pos, '(grab)')
            return True

    def on_pressed(self, instance, pos):
        print("Pressed at {}".format(pos))
        to_window = instance.to_window(*instance.pos)
        print("to_window = {}".format(to_window))
        to_widget = instance.to_widget(*to_window)
        print("to_widget = {}".format(to_widget))

root = Builder.load_string(r'''
<Widget>:
    canvas.after:
        Line:
            rectangle: self.x+2,self.y+2,self.width-3,self.height-3
            dash_offset: 5
            dash_length: 3

BoxLayout:
    Widget:
    RelativeLayout
        DragRecognizer:
            size_hint: 0.8, 0.8
            pos_hint: {'center_x': 0.5, 'center_y': 0.5, }
''')

runTouchApp(root)
</code>```

Output

Body:
I'm confused about touch.grab

Documentation says

The touch coordinate is not translated to your widget space because the touch is coming directly from the Window. It’s your job to convert the coordinate to your local space.

but when I ran the code below

# -*- coding: utf-8 -*-

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.factory import Factory

class DragRecognizer(Factory.Widget):

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            touch.grab(self)
            print('on_drag_begin', touch.pos)
            return True
        else:
            return super().on_touch_down(touch)

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            touch.ungrab(self)
            print('on_drag_end', touch.pos, '(grab)')
            return True
        else:
            print('on_drag_end', touch.pos)
            return super().on_touch_up(touch)

root = Builder.load_string(r'''
<Widget>:
    canvas.after:
        Line:
            rectangle: self.x+2,self.y+2,self.width-3,self.height-3
            dash_offset: 5
            dash_length: 3

BoxLayout:
    Widget:
    RelativeLayout
        DragRecognizer:
            size_hint: 0.8, 0.8
            pos_hint: {'center_x': 0.5, 'center_y': 0.5, }
''')

runTouchApp(root)

and pressed mouse button.

screenshot

I expected like this

on_drag_begin (88, 111)
on_drag_end (88, 111)
on_drag_end (488, 111) (grab)

but what I got is

on_drag_begin (88, 111)
on_drag_end (88, 111)
on_drag_end (88, 111) (grab)

Grabbed touch is not Window coordinates! So I don't understand what's the point of the documentation. Sorry for my bad English. I really appreciate if you help me.

Body:
You have to convert the coordinate to your local space by using *instance.to_window(instance.pos). Please refer to the example for details.

snippet

to_window = instance.to_window(*instance.pos)

Example

main.py

# -*- coding: utf-8 -*-

from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.properties import ListProperty

class DragRecognizer(Factory.Widget):
    pressed = ListProperty([0, 0])

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            touch.grab(self)
            self.pressed = touch.pos
            print('on_touch_down: on_drag_begin', touch.pos)
            return True

    def on_touch_up(self, touch):
        if touch.grab_current is self:
            touch.ungrab(self)
            print('on_touch_up: on_drag_end', touch.pos, '(grab)')
            return True

    def on_pressed(self, instance, pos):
        print("Pressed at {}".format(pos))
        to_window = instance.to_window(*instance.pos)
        print("to_window = {}".format(to_window))
        to_widget = instance.to_widget(*to_window)
        print("to_widget = {}".format(to_widget))

root = Builder.load_string(r'''
<Widget>:
    canvas.after:
        Line:
            rectangle: self.x+2,self.y+2,self.width-3,self.height-3
            dash_offset: 5
            dash_length: 3

BoxLayout:
    Widget:
    RelativeLayout
        DragRecognizer:
            size_hint: 0.8, 0.8
            pos_hint: {'center_x': 0.5, 'center_y': 0.5, }
''')

runTouchApp(root)

Output


问:
Python, specific count of chars in string
I am trying to count the number of occurrences in a string in python. I would like to take a binary input, say '001101'. Then count the number of 1s, 0s, 11s, 00s etc.

I have tried to implement this by using count, but this will output that there are 3 1s, when i only want it to output 1 1, and 1 11s and for it to not count them individually, unless they are on their own.

I have also tried to implement this with find, but i am having the same problem.

Any help would be appreciated, thanks.

答:
Generic solution if you dont want to specify which sequences of characters to look for.

```<code>def count_unique_chars(string):
    char_count = {}
    char = ''

    for pair in zip(list(string), list(string[1:]) + [None]):

        char += pair[0]

        if pair[0] == pair[1]:
            continue

        else:

            if char in char_count.keys():
                char_count[char] += 1
            else:
                char_count[char] = 1

            char = ''

    return char_count
</code>```

Outputs a dict with the count of unique chars.

```<code>count_unique_chars('001101')
</code>```

{'0': 1, '00': 1, '1': 1, '11': 1}

or

```<code>count_unique_chars('001101011000100111101000')
</code>```

{'0': 3, '00': 2, '000': 2, '1': 3, '11': 2, '1111': 1}

```<code>count_unique_chars('hello world')
</code>```

{' ': 1, 'd': 1, 'e': 1, 'h': 1, 'l': 1, 'll': 1, 'o': 2, 'r': 1, 'w': 1}

Body:
Generic solution if you dont want to specify which sequences of characters to look for.

def count_unique_chars(string):
    char_count = {}
    char = ''

    for pair in zip(list(string), list(string[1:]) + [None]):

        char += pair[0]

        if pair[0] == pair[1]:
            continue

        else:

            if char in char_count.keys():
                char_count[char] += 1
            else:
                char_count[char] = 1

            char = ''

    return char_count

Outputs a dict with the count of unique chars.

count_unique_chars('001101')

{'0': 1, '00': 1, '1': 1, '11': 1}

or

count_unique_chars('001101011000100111101000')

{'0': 3, '00': 2, '000': 2, '1': 3, '11': 2, '1111': 1}

count_unique_chars('hello world')

{' ': 1, 'd': 1, 'e': 1, 'h': 1, 'l': 1, 'll': 1, 'o': 2, 'r': 1, 'w': 1}


问:
Coding Standard Wiki
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.

This could be extended in the future for other purposes as well.

The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.

If possible the engine should be in C# so we're able to tweak it to our needs if required.

If you think a wiki solution is the wrong way to go about this then please give an alternative :)

Update

I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.

Update 2

Could you also (if possible) let me know if any of these solutions work with Active Directory?

Cheers
Tony

答: We keep an internal wiki at my shop that has almost all of our documentation (not just coding standards).  We didn't really see the need to roll our own so we just used MediaWiki...</p>

Title: Coding Standard Wiki

OwnerDisplayName: JPunyon


问:
Getting error in pruning apriori rules in grocery dataset
I'm trying to prune the rules that created by apriori algorithm for groceries dataset but getting one error

Using R 3.4.2 and RStudio (Version 1.1.383)

Imported libraries

```<code>library(arules)
data("Groceries")
</code>```

I have created the rules

```<code>rules <- apriori(Groceries, parameter = list(supp =0.001,
                                         conf = 0.5,
                                         target = "rules"))
</code>```

Started pruning redundant rules

```<code>rules.sorted = sort(rules, by="lift")
subset.matrix <- is.subset(rules.sorted, rules.sorted)
</code>```

While coverting lower triangle of the matrix to NA I got one warning

```<code>subset.matrix[lower.tri(subset.matrix, diag=T)] = NA
</code>```

Warning message:

```<code>In `[<-`(`*tmp*`, as.vector(i), value = NA) :
x[.] <- val: x is “ngTMatrix”, val not in {TRUE, FALSE} is coerced; NA |--> TRUE
</code>```

Then tried to identify redundant rules

```<code>redundant <- colSums(subset.matrix, na.rm=T) >= 1
</code>```

Finally pruned rules

```<code>rules.pruned = rules.sorted[!redundant]
</code>```

But while inspecting it showing nothing

```<code>inspect(rules.pruned)
</code>```

Even summary of rules.pruned showing "zero" 0 rules

```<code>summary(rules.pruned)
</code>```

I guess the error mainly due to the warning during conversion of matrix lower triangle to NA values which showed a warning

How to overcome the warning?

答:
is.subset() returns since version 1.5-2 a sparse matrix (see package NEWS). If you want to use your code then you need to use:

```<code>subset.matrix <- is.subset(rules.sorted, rules.sorted, sparse = FALSE)
</code>```

however, that is very inefficient and only works for very small rule sets. Use is.redundant() instead to find redundant rules.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to prune the rules that created by apriori algorithm for groceries dataset but getting one error

Using R 3.4.2 and RStudio (Version 1.1.383)

Imported libraries

library(arules)
data("Groceries")

I have created the rules

rules <- apriori(Groceries, parameter = list(supp =0.001,
                                         conf = 0.5,
                                         target = "rules"))

Started pruning redundant rules

rules.sorted = sort(rules, by="lift")
subset.matrix <- is.subset(rules.sorted, rules.sorted)

While coverting lower triangle of the matrix to NA I got one warning

subset.matrix[lower.tri(subset.matrix, diag=T)] = NA

Warning message:

In `[<-`(`*tmp*`, as.vector(i), value = NA) :
x[.] <- val: x is “ngTMatrix”, val not in {TRUE, FALSE} is coerced; NA |--> TRUE

Then tried to identify redundant rules

redundant <- colSums(subset.matrix, na.rm=T) >= 1

Finally pruned rules

rules.pruned = rules.sorted[!redundant]

But while inspecting it showing nothing

inspect(rules.pruned)

Even summary of rules.pruned showing "zero" 0 rules

summary(rules.pruned)

I guess the error mainly due to the warning during conversion of matrix lower triangle to NA values which showed a warning

How to overcome the warning?

Body:
is.subset() returns since version 1.5-2 a sparse matrix (see package NEWS). If you want to use your code then you need to use:

subset.matrix <- is.subset(rules.sorted, rules.sorted, sparse = FALSE)

however, that is very inefficient and only works for very small rule sets. Use is.redundant() instead to find redundant rules.


问:
Firestore: remove sensitive fields on documents
I'm trying to figure it out how to remove a sensitive field on a firestore document. For example, my collection is a group information. The group is protected with a pin code field. Any one wants to join the group has to know the pin code.

In the meantime, I want to let users query what group is available to join. For query part, I don't want return group information with pin code information. Do we have anyway to remove sensitive fields from a document for Firestore for reading event?

Cloud function only supports write event. 1 possible solution is use cloud function on write event, and put pin code in a separate document. Is there a better solution? THanks.

My group schema is:

```<code>group: {
    name: string,
    pinCode: string
}
</code>```

答:
A user can either access a document, or they can't. There is no property-level access control in Firestore.

So to accomplish what you want, you will need to store the public and private information in separate documents.

You could either create a second document with the private information in the same collection and then secure them using:

```<code>match /databases/{database}/documents {
    match /groups/{group} {
      allow read: if resource.data.visibility != "private"
    }
}
</code>```

Alternatively (and simpler to secure) you could create a separate collection for the private documents.

Body:
I'm trying to figure it out how to remove a sensitive field on a firestore document. For example, my collection is a group information. The group is protected with a pin code field. Any one wants to join the group has to know the pin code.

In the meantime, I want to let users query what group is available to join. For query part, I don't want return group information with pin code information. Do we have anyway to remove sensitive fields from a document for Firestore for reading event?

Cloud function only supports write event. 1 possible solution is use cloud function on write event, and put pin code in a separate document. Is there a better solution? THanks.

My group schema is:

group: {
    name: string,
    pinCode: string
}

Body:
A user can either access a document, or they can't. There is no property-level access control in Firestore.

So to accomplish what you want, you will need to store the public and private information in separate documents.

You could either create a second document with the private information in the same collection and then secure them using:

match /databases/{database}/documents {
    match /groups/{group} {
      allow read: if resource.data.visibility != "private"
    }
}

Alternatively (and simpler to secure) you could create a separate collection for the private documents.


问:
Subsetting columns by another column and column index in Pandas
I want to get a certain subset of columns (defined by index range) of rows filtered by another column value. My data frame:

```<code>   A   B   C   D
0  11  b1  c1  d1
1  33  b2  c2  d2
2  22  b3  c3  d3
</code>```

Here I can get all columns of rows by a column criteria:

```<code>df[df['A'] == 33]
</code>```

Also, I can get certain columns of all rows by index:

```<code>df.iloc[:,0:2]
</code>```

Now I want to combine the two along this logic (this doesn't work):

```<code>df[df['A'] == 33, 0:2]
</code>```

答:
You can select columns by indexing with DataFrame.loc:

```<code>print (df.columns[0:2])
Index(['A', 'B'], dtype='object')

df = df.loc[df['A'] == 33, df.columns[0:2]]
print (df)

    A   B
1  33  b2
</code>```

because:

```<code>df = df.iloc[df['A'] == 33, 0:2]
</code>```

NotImplementedError: iLocation based boolean indexing on an integer type is not available

Body:
I want to get a certain subset of columns (defined by index range) of rows filtered by another column value. My data frame:

   A   B   C   D
0  11  b1  c1  d1
1  33  b2  c2  d2
2  22  b3  c3  d3

Here I can get all columns of rows by a column criteria:

df[df['A'] == 33]

Also, I can get certain columns of all rows by index:

df.iloc[:,0:2]

Now I want to combine the two along this logic (this doesn't work):

df[df['A'] == 33, 0:2]

Body:
You can select columns by indexing with DataFrame.loc:

print (df.columns[0:2])
Index(['A', 'B'], dtype='object')

df = df.loc[df['A'] == 33, df.columns[0:2]]
print (df)

    A   B
1  33  b2

because:

df = df.iloc[df['A'] == 33, 0:2]

NotImplementedError: iLocation based boolean indexing on an integer type is not available


问:
message queue thinking
We have implemented a message queue by using C# Queue. We know we only have ONE consumer to take available message out from the queue for processing with a while loop. We also know there is only ONE producer to put message onto the queue.

We have a lock on above message queue to make sure the consumer and producer cannot access the queue simultaneously.

My question is is that lock necessary? If the Queue increase its Count property AFTER an item is actually added and if the consumer check the Count before retrieve, the consumer should get a complete message item even we don't have that lock. Right? So we will not face a partial message item issue. Then we can get rid of that lock?

That lock will slow down the system and occasionally we can see the retrieve thread is blocked for a while because we have a very heavy producer.

EDIT:

Unfortunately we are using .Net 3.5.

答: ConcurrentQueue is available even if you're using .NET 3.5.  The Reactive Extensions includes what used to be the Parallel Extensions to .NET 3.5--the precursor to the Task Parallel Library that is included in .NET 4.0.

Title: message queue thinking


问:
How to use parameterized SQL with dplyr?
I'm trying to execute a SQL query with dplyr on SQL Server:

```<code>tbl(con, sql(sqlQuery))
</code>```

The query is generated dynamically using sprintf("SELECT ... WHERE a = '%s'). This is a bad practice because it can be abused for SQL injection, but I can't find any documentation or working example for parameterized queries in dplyr. Can it be done, how?

The connection (con) is using DBI, the odbc library, and the {SQL Server Native Client 11.0} ODBC driver:

```<code>con <- DBI::dbConnect(odbc::odbc(),
                      Driver = "{SQL Server Native Client 11.0}",
</code>```

答:
Depending on what you need your parameters for, based on your example it looks like maybe the WHERE statement, you can just define the parameter in R and then use it your dplyr verbs.

```<code>my_param <- "FILTER_VALUE" #create param
my_table <- tbl(con, "TABLE_NAME") #create ref tibble
my_table <- my_table %>% filter( a == my_param ) # filter by param
my_table <- my_table %>% collect() # execute query
</code>```

Anything you assign in R can be referenced in filter or mutate.

Body:
I'm trying to execute a SQL query with dplyr on SQL Server:

tbl(con, sql(sqlQuery))

The query is generated dynamically using sprintf("SELECT ... WHERE a = '%s'). This is a bad practice because it can be abused for SQL injection, but I can't find any documentation or working example for parameterized queries in dplyr. Can it be done, how?

The connection (con) is using DBI, the odbc library, and the {SQL Server Native Client 11.0} ODBC driver:

con <- DBI::dbConnect(odbc::odbc(),
                      Driver = "{SQL Server Native Client 11.0}",

Body:
Depending on what you need your parameters for, based on your example it looks like maybe the WHERE statement, you can just define the parameter in R and then use it your dplyr verbs.

my_param <- "FILTER_VALUE" #create param
my_table <- tbl(con, "TABLE_NAME") #create ref tibble
my_table <- my_table %>% filter( a == my_param ) # filter by param
my_table <- my_table %>% collect() # execute query

Anything you assign in R can be referenced in filter or mutate.