问:
No bean named springSecurityFilterChain is defined
I need to integrate spring security with  a small application built with spring 3.1.1, following this tutorial  at the point 3.2.1, got this error trace:

```<code>gen 31, 2014 3:08:41 PM org.apache.catalina.core.StandardContext filterStart
Grave: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1097)
    at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
    at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
    at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4775)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5452)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:656)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1635)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

gen 31, 2014 3:08:41 PM org.apache.catalina.core.StandardContext startInternal
Grave: Error filterStart
gen 31, 2014 3:08:41 PM org.apache.catalina.core.StandardContext startInternal
Grave: Context [/mmasgis] startup failed due to previous errors
gen 31, 2014 3:08:41 PM org.apache.catalina.core.ApplicationContext log
Informazioni: Closing Spring root WebApplicationContext
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Fri Jan 31 15:08:40 CET 2014]; root of context hierarchy
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@204ed39b: defining beans [dataSource]; root of factory hierarchy
gen 31, 2014 3:08:41 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
Grave: The web application [/mmasgis] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
gen 31, 2014 3:08:41 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
Grave: The web application [/mmasgis] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
gen 31, 2014 3:08:41 PM org.apache.catalina.startup.HostConfig deployDirectory
Informazioni: Deploying web application directory /home/arpho/programmi/sts/springsource/vfabric-tc-server-developer-2.9.3.RELEASE/base-instance/webapps/manager
gen 31, 2014 3:08:41 PM org.apache.catalina.startup.HostConfig deployDirectory
Informazioni: Deploying web application directory /home/arpho/programmi/sts/springsource/vfabric-tc-server-developer-2.9.3.RELEASE/base-instance/webapps/ROOT
gen 31, 2014 3:08:41 PM org.apache.coyote.AbstractProtocol start
Informazioni: Starting ProtocolHandler ["http-bio-8080"]
gen 31, 2014 3:08:41 PM org.apache.catalina.startup.Catalina start
Informazioni: Server startup in 2497 ms
</code>```

I have referred other threads but with no solution. Can someone correct me where is the problem in the configuration?

Thanks for the time.

This is my web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>mmasgisServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mmasgisServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
</code>```

This is my root-context.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

    <bean id="dataSource" name="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"></property>
        <property name="password" value="password"></property>
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url"
                          value="jdbc:mysql://localhost:3306/mmasgis">
        </property>
    </bean>

    <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:security="http://www.springframework.org/schema/security"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.springframework.org/schema/beans
                                   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                                   http://www.springframework.org/schema/security
                                   http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    </beans>
</beans>
</code>```

答:
I recently also ran into this problem, and adding the <http> element solved the main problem, but my context initialization still failed.  Digging through my Tomcat 8 error log, I noticed the following line buried:

```<code>Did you forget to add a global <authentication-manager> element to your configuration
(with child <authentication-provider> elements)? Alternatively you can use the
authentication-manager-ref attribute on your <http> and <global-method-security> elements.
</code>```

Adding this additional element, which I found in the Spring Security documentation, solved that problem:

```<code><authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
            <user name="bob" password="bobspassword" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>
</code>```

Just wanted to mention it since this problem was related and someone else new to Spring Security may run into it.

Body:
I need to integrate spring security with  a small application built with spring 3.1.1, following this tutorial  at the point 3.2.1, got this error trace:

gen 31, 2014 3:08:41 PM org.apache.catalina.core.StandardContext filterStart
Grave: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1097)
    at org.springframework.web.filter.DelegatingFilterProxy.initDelegate(DelegatingFilterProxy.java:326)
    at org.springframework.web.filter.DelegatingFilterProxy.initFilterBean(DelegatingFilterProxy.java:236)
    at org.springframework.web.filter.GenericFilterBean.init(GenericFilterBean.java:194)
    at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
    at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262)
    at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:107)
    at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4775)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5452)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:656)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1635)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

gen 31, 2014 3:08:41 PM org.apache.catalina.core.StandardContext startInternal
Grave: Error filterStart
gen 31, 2014 3:08:41 PM org.apache.catalina.core.StandardContext startInternal
Grave: Context [/mmasgis] startup failed due to previous errors
gen 31, 2014 3:08:41 PM org.apache.catalina.core.ApplicationContext log
Informazioni: Closing Spring root WebApplicationContext
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Fri Jan 31 15:08:40 CET 2014]; root of context hierarchy
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@204ed39b: defining beans [dataSource]; root of factory hierarchy
gen 31, 2014 3:08:41 PM org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc
Grave: The web application [/mmasgis] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
gen 31, 2014 3:08:41 PM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
Grave: The web application [/mmasgis] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
gen 31, 2014 3:08:41 PM org.apache.catalina.startup.HostConfig deployDirectory
Informazioni: Deploying web application directory /home/arpho/programmi/sts/springsource/vfabric-tc-server-developer-2.9.3.RELEASE/base-instance/webapps/manager
gen 31, 2014 3:08:41 PM org.apache.catalina.startup.HostConfig deployDirectory
Informazioni: Deploying web application directory /home/arpho/programmi/sts/springsource/vfabric-tc-server-developer-2.9.3.RELEASE/base-instance/webapps/ROOT
gen 31, 2014 3:08:41 PM org.apache.coyote.AbstractProtocol start
Informazioni: Starting ProtocolHandler ["http-bio-8080"]
gen 31, 2014 3:08:41 PM org.apache.catalina.startup.Catalina start
Informazioni: Server startup in 2497 ms

I have referred other threads but with no solution. Can someone correct me where is the problem in the configuration?

Thanks for the time.

This is my web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>mmasgisServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mmasgisServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

This is my root-context.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" name="dataSource"
              class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"></property>
        <property name="password" value="password"></property>
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url"
                          value="jdbc:mysql://localhost:3306/mmasgis">
        </property>
    </bean>

    <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:security="http://www.springframework.org/schema/security"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xsi:schemaLocation="http://www.springframework.org/schema/beans
                                   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                                   http://www.springframework.org/schema/security
                                   http://www.springframework.org/schema/security/spring-security-3.1.xsd">
    </beans>
</beans>

Body:
I recently also ran into this problem, and adding the <http> element solved the main problem, but my context initialization still failed.  Digging through my Tomcat 8 error log, I noticed the following line buried:

Did you forget to add a global <authentication-manager> element to your configuration
(with child <authentication-provider> elements)? Alternatively you can use the
authentication-manager-ref attribute on your <http> and <global-method-security> elements.

Adding this additional element, which I found in the Spring Security documentation, solved that problem:

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
            <user name="bob" password="bobspassword" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

Just wanted to mention it since this problem was related and someone else new to Spring Security may run into it.


来源: stackexchange

问:
How to add multiple item to a ListView with each Button click
I found much on google but not able to get the answer.
I got How to add an item to a ListView with each Button click.
here we are learning to add single item..
thanks in advance</p>

答:
Just like in the answer provided in the question you've shared, to add two items -

1) add both the data to the array

2) notify data set changes

```<code>// Add the data fields to the array
dataArray.add(0, dataField1);
dataArray.add(1, dataField2);
// Notify the adapter that data set has changed
adapter.notifyDataSetChanged();
</code>```

Try dataArray.add(dataField) inside the button's onClick and notify the adapter about the changes. Every time the button is clicked, an item gets added at the end of the list.

ContentLicense: CC BY-SA 3.0

Body:
Just like in the answer provided in the question you've shared, to add two items -

1) add both the data to the array

2) notify data set changes

// Add the data fields to the array
dataArray.add(0, dataField1);
dataArray.add(1, dataField2);
// Notify the adapter that data set has changed
adapter.notifyDataSetChanged();

Try dataArray.add(dataField) inside the button's onClick and notify the adapter about the changes. Every time the button is clicked, an item gets added at the end of the list.


问:
Natural sorting in SQL does not work
I am trying to sort a row "naturally" in SQL, and I found this answer which supposedly does exactly what I need:

https://stackoverflow.com/a/17354420/7563153

But when I tried recreating it in "SQL Fiddle" I couldn't get it to work...

Here's my attempt

What am I doing wrong?

答:
Assuming (!) that your data have the format "blabla-integer" with one and only one dash (-) separating the alphanumeric part from the integer part I would go this way:

```<code>select * from table1
order by cast(substring(test,
                        locate('-', test) + 1,
                        length(test) - locate('-', test)
                       ) as signed integer
             );
</code>```

Title: Natural sorting in SQL does not work

Body:
Assuming (!) that your data have the format "blabla-integer" with one and only one dash (-) separating the alphanumeric part from the integer part I would go this way:

select * from table1
order by cast(substring(test,
                        locate('-', test) + 1,
                        length(test) - locate('-', test)
                       ) as signed integer
             );


问:
How to find .tpl file of navbar
I am struggling to find the file of my prestashop page navigation bar.

Code snippet example

I need to delete the title tag and after two hours of searching i failed. anybody have any ideas ?

EDIT

To clarify it: I need to remove the span title appearing after hovering category on my side navigation block on homepage. Picture:
Side nav block

答:
You'll find the navigation bar in the breadcrumb.tpl of your installed template.

For the default theme:
prestashop/themes/default-bootstrap/breadcrumb.tpl

Looking your code that isn't the breadcrumb but the blockcategories module.
So you have to edit this file category-tree-branch.tpl that is in this location (if there isn't the override):

prestashop/modules/blockcategories

Otherwise (if there is the override):

prestashop/themes/yourtheme/modules/blockcategories

I hope this helps

Title: How to find .tpl file of navbar


问:
Build Custom App for Android Auto
I am searching a method to build custom app for android Auto (Which is not a media app nor messaging app)

Exactly like RoboCharge

Can someone give some directions for building such app.

N.B I have seen this question, but my app will be very simple and will not distract the driver.

答:
Google doesn't allow to create custom apps to 3rd parties, yet.
You have to contact them and they will give you a new SDK</p>

Title: Build Custom App for Android Auto


答:
```<code>function createDateRangeArray($strDateFrom,$strDateTo)
{
    // takes two dates formatted as YYYY-MM-DD and creates an
    // inclusive array of the dates between the from and to dates.

    // could test validity of dates here but I'm already doing
    // that in the main script

    $aryRange = [];

    $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
    $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));

    if ($iDateTo >= $iDateFrom) {
        array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
        while ($iDateFrom<$iDateTo) {
            $iDateFrom += 86400; // add 24 hours
            array_push($aryRange, date('Y-m-d', $iDateFrom));
        }
    }
    return $aryRange;
}
</code>```

source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

ContentLicense: CC BY-SA 2.5

Title: PHP: Return all dates between two dates in an array

Body:
Expected Input:

getDatesFromRange( '2010-10-01', '2010-10-05' );

Expected Output:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )

Body:
function createDateRangeArray($strDateFrom,$strDateTo)
{
    // takes two dates formatted as YYYY-MM-DD and creates an
    // inclusive array of the dates between the from and to dates.

    // could test validity of dates here but I'm already doing
    // that in the main script

    $aryRange = [];

    $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
    $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));

    if ($iDateTo >= $iDateFrom) {
        array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
        while ($iDateFrom<$iDateTo) {
            $iDateFrom += 86400; // add 24 hours
            array_push($aryRange, date('Y-m-d', $iDateFrom));
        }
    }
    return $aryRange;
}

source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

ContentLicense: CC BY-SA 4.0


问:
Creating new column in pandas from values of other column
I am dealing with the following dataframe:

```<code>          p                      q
   0      11                     2
   1      11                     2
   2      11                     2
   3      11                     3
   4      11                     3
   5      12                     2
   6      12                     2
   7      13                     2
   8      13                     2
</code>```

I want create a new column, say s, which starts with 0 and goes on. This new col is based on "p" column, whenever the p changes, the "s" should change too.

For the first 4 rows, the "p" = 11, so "s" column should have values 0 for this first 4 rows, and so on...

Below is the expectant df:

```<code>     s             p         q

 0   0             11        2
 1   0             11        2
 2   0             11        2
 3   0             11        2
 4   1             11        4
 5   1             11        4
 6   1             11        4
 7   1             11        4
 8   2             12        2
 9   2             12        2
 10  2             12        2
 11  3             12        3
 12  3             12        3
</code>```

答:
You need diff with cumsum (subtract one if you want the id to start from 0):

```<code>df["finalID"] = (df.ProjID.diff() != 0).cumsum()
df
</code>```

Update, if you want to take both voyg_id and ProjID into consideration, you can use a OR condition on the two columns difference, so that whichever column changes, you get an increase in the final id.

```<code>df['final_id'] = ((df.voyg_id.diff() != 0) | (df.proj_id.diff() != 0)).cumsum()
df
</code>```

Body:
I am dealing with the following dataframe:

          p                      q
   0      11                     2
   1      11                     2
   2      11                     2
   3      11                     3
   4      11                     3
   5      12                     2
   6      12                     2
   7      13                     2
   8      13                     2

I want create a new column, say s, which starts with 0 and goes on. This new col is based on "p" column, whenever the p changes, the "s" should change too.

For the first 4 rows, the "p" = 11, so "s" column should have values 0 for this first 4 rows, and so on...

Below is the expectant df:

     s             p         q

 0   0             11        2
 1   0             11        2
 2   0             11        2
 3   0             11        2
 4   1             11        4
 5   1             11        4
 6   1             11        4
 7   1             11        4
 8   2             12        2
 9   2             12        2
 10  2             12        2
 11  3             12        3
 12  3             12        3

Body:
You need diff with cumsum (subtract one if you want the id to start from 0):

df["finalID"] = (df.ProjID.diff() != 0).cumsum()
df

Update, if you want to take both voyg_id and ProjID into consideration, you can use a OR condition on the two columns difference, so that whichever column changes, you get an increase in the final id.

df['final_id'] = ((df.voyg_id.diff() != 0) | (df.proj_id.diff() != 0)).cumsum()
df


问:
convert csv file to matrix in R
I have a csv file

```<code> User_name    M_User    Total
    user 1    user 2     7
    user 1    user 3     19
    user 1    user 7     5
    user 3    user 2     1
    user 2    user 7     1
</code>```

and I want to convert it in matrix form

```<code>            user 1  user 2  user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0
</code>```

what I;m doing right now is something like this

```<code>require(reshape2)
m <- as.matrix(dcast(df, USER_NAME ~ M_USER, value.var = "TOTAL", fill=0))[,1:4]
</code>```

but the answer I get is

```<code> USER_NAME   user 2 user 3 user 7
[1,] "user 1"  "7"    "19"   "5"
[2,] "user 2"  "0"    " 0"   "1"
[3,] "user 3"  "1"    " 0"   "0"
</code>```

How can I modify the code so that I get this matrix

```<code>            user 1 user 2 user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0
</code>```

答:
Use tidyr::spread function as follow:

```<code>require(tidyr)
df %>% spread(key=M_User,value = Total,fill = 0)
</code>```

Title: convert csv file to matrix in R

Body:
I have a csv file

 User_name    M_User    Total
    user 1    user 2     7
    user 1    user 3     19
    user 1    user 7     5
    user 3    user 2     1
    user 2    user 7     1

and I want to convert it in matrix form

            user 1  user 2  user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0

what I;m doing right now is something like this

require(reshape2)
m <- as.matrix(dcast(df, USER_NAME ~ M_USER, value.var = "TOTAL", fill=0))[,1:4]

but the answer I get is

 USER_NAME   user 2 user 3 user 7
[1,] "user 1"  "7"    "19"   "5"
[2,] "user 2"  "0"    " 0"   "1"
[3,] "user 3"  "1"    " 0"   "0"

How can I modify the code so that I get this matrix

            user 1 user 2 user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0

Body:
Use tidyr::spread function as follow:

require(tidyr)
df %>% spread(key=M_User,value = Total,fill = 0)


问:
Setting up Aamazon EC2 Container Service with existing EC2 and existing docker
I currently have an EC2 running with a docker container, but I was told that naively running it is not good enough and EC2 Container Service can offer a lot more functionalities including auto-restart the docker and keep logging.

I tried to follow the documentation to set up the EC2 Container Service, but I found the naming conventions is quite confusing.

Can anyone please help me clarify it a bit?

It says

Retrieve the docker login command that you can use to authenticate your Docker client to your registry by pasting the aws ecr get-login command from the console into a terminal window.

What is this "console" and "terminal" it refers to?

I tried to run aws ecr get-login on both my local cmd that I used to build the docker, and the EC2, both told me that I need to sudo install awscli, after I installed it, running aws ecr get-login just lead to

```<code>aws: error: argument command: Invalid choice, valid choices are:
</code>```

Where should I run this command?

答:
The console/terminal is your local command prompt (cmd). Where you run your commands.

After you install the AWS CLI, you need to run aws configure to configure your credentials, default region, and default output format.

Configuring the AWS Command Line Interface

Once you've got that configured, run aws ecr get-login which will return a string of text that is the docker command you will use to sync docker on your machine with your AWS repository. You can just copy and paste the string into your cmd and hit return.

Make sure you set your region correctly and make sure you choose the desired output. You can always override the region or the output when running aws commands by using --region desiredregion or --output json|text.

Examples:

aws ecr describe-repositories --region us-west-1 --output text

aws ecr describe-repositories --region us-west-1 --output json

Body:
I currently have an EC2 running with a docker container, but I was told that naively running it is not good enough and EC2 Container Service can offer a lot more functionalities including auto-restart the docker and keep logging.

I tried to follow the documentation to set up the EC2 Container Service, but I found the naming conventions is quite confusing.

Can anyone please help me clarify it a bit?

It says

Retrieve the docker login command that you can use to authenticate your Docker client to your registry by pasting the aws ecr get-login command from the console into a terminal window.

What is this "console" and "terminal" it refers to?

I tried to run aws ecr get-login on both my local cmd that I used to build the docker, and the EC2, both told me that I need to sudo install awscli, after I installed it, running aws ecr get-login just lead to

aws: error: argument command: Invalid choice, valid choices are:

Where should I run this command?


问:
Jquery - Function Inside DIV not working after refreshed
I have a table "group1" contains table and rows. I use this plugin (tableDnD) to drag the row up/down, and it is all working fine. I have another Jquery function that delete row inside the DIV "group1" and the refresh the DIV only, this also works fine.

```<code>    $('#group1').tableDnD({
    onDrop: function(table, row) {
        $.post('updateRecord.asp?', {
            pagesid : "1",
            arr : $.tableDnD.serialize()
        });
    }
});
</code>```

Now, after the rows deleted, updated DB, then refreshed the DIV, the jQuery above with option drag row up/down is no longer working (if I refresh entire page, it would work).  I did some research and see people suggested about using delegate option, but I am not sure how to apply to the $('#group1').tableDnD function.

Updated - I tried this, but no luck.

```<code>$(document).on('tableDnD', '#group1', function(){
onDrop: function(table, row) {
    $.post('updateRecord.asp?', {
        pagesid : "1",
        arr : $.tableDnD.serialize()
    });
}
</code>```

});

Any suggestions would be appreciated.

答:
You could create your own event and call it

```<code> $('body').on('apply_tableDnD', '#group1', function() {
  $('#group1').tableDnD({
    onDrop: function(table, row) {
      $.post('updateRecord.asp?', {
        pagesid: "1",
        arr: $.tableDnD.serialize()
      });
    }
  });
});
</code>```

This will call after div has been refreshed

```<code>$('#group1').trigger('apply_tableDnD');
</code>```

Body:
I have a table "group1" contains table and rows. I use this plugin (tableDnD) to drag the row up/down, and it is all working fine. I have another Jquery function that delete row inside the DIV "group1" and the refresh the DIV only, this also works fine.

    $('#group1').tableDnD({
    onDrop: function(table, row) {
        $.post('updateRecord.asp?', {
            pagesid : "1",
            arr : $.tableDnD.serialize()
        });
    }
});

Now, after the rows deleted, updated DB, then refreshed the DIV, the jQuery above with option drag row up/down is no longer working (if I refresh entire page, it would work).  I did some research and see people suggested about using delegate option, but I am not sure how to apply to the $('#group1').tableDnD function.

Updated - I tried this, but no luck.

$(document).on('tableDnD', '#group1', function(){
onDrop: function(table, row) {
    $.post('updateRecord.asp?', {
        pagesid : "1",
        arr : $.tableDnD.serialize()
    });
}

});

Any suggestions would be appreciated.

Body:
You could create your own event and call it

 $('body').on('apply_tableDnD', '#group1', function() {
  $('#group1').tableDnD({
    onDrop: function(table, row) {
      $.post('updateRecord.asp?', {
        pagesid: "1",
        arr: $.tableDnD.serialize()
      });
    }
  });
});

This will call after div has been refreshed

$('#group1').trigger('apply_tableDnD');


问:
Can I create a PhP array and then use the array name to create a new array?
Sorry for the bad title but I couldn't figure out how to word my question and I couldn't find the answer anywhere.

Can I do this/will this work:

```<code><p>
 <?php
  $x=array(1,2);
  $y=array(3,4);
  $z=array($x,$y);  <-----will this work?
 ?>
</p>
</code>```

答:
You are actually creating a multi dimensional array here. </p>

```<code>$x = array(1, 2);
$y = array(3, 4);
$z = array($x, $y);
</code>```

<p>The third array will be like this after execution of above script. </p>

```<code>$z = array(
    0 => array(
        0 => 1,
        1 => 2
    ),
    1 => array(
        0 => 3,
        1 => 4
    ),
) ;
</code>```

Body:
Sorry for the bad title but I couldn't figure out how to word my question and I couldn't find the answer anywhere.

Can I do this/will this work:

 <?php
  $x=array(1,2);
  $y=array(3,4);
  $z=array($x,$y);  <-----will this work?
 ?>

Body:
You are actually creating a multi dimensional array here.

$x = array(1, 2);
$y = array(3, 4);
$z = array($x, $y);

The third array will be like this after execution of above script.

$z = array(
    0 => array(
        0 => 1,
        1 => 2
    ),
    1 => array(
        0 => 3,
        1 => 4
    ),
) ;


问:
istringstream::str() does not return current contents
I have an istringstream, and I'm putting some data into it. Then, I extract some of the data I put in, and then I want to get the remaining contents of the istringstream. I thought, apparently incorrectly, that the following would do exactly that:

```<code>std::istringstream stream("Two words");
std::string word;
stream >> word;
std::cout << word << std::endl;
std::cout << stream.str() << std::endl;
</code>```

The output is:

```<code>Two words
Two
Two words
</code>```

In other words, the extraction operation is returning the correct value, and it's advancing the read pointer, as indicated by tellg, but str doesn't seem to care--it just returns the entire original contents of the istringstream.
I'm sure this is expected behavior, but I just can't fathom why.

So: how can I easily and cleanly get the remaining contents of the istringstream, and why isn't str doing it already?

答:
and why isn't str doing it already?

I am sure some people will want it one way while others will want it another way.

how can I easily and cleanly get the remaining contents of the istringstream>

That's not too hard. Use:

```<code>std::cout << stream.str().substr(stream.tellg()) << std::endl;
</code>```

Body:
I have an istringstream, and I'm putting some data into it. Then, I extract some of the data I put in, and then I want to get the remaining contents of the istringstream. I thought, apparently incorrectly, that the following would do exactly that:

std::istringstream stream("Two words");
std::string word;
stream >> word;
std::cout << word << std::endl;
std::cout << stream.str() << std::endl;

The output is:

Two words
Two
Two words

In other words, the extraction operation is returning the correct value, and it's advancing the read pointer, as indicated by tellg, but str doesn't seem to care--it just returns the entire original contents of the istringstream.
I'm sure this is expected behavior, but I just can't fathom why.

So: how can I easily and cleanly get the remaining contents of the istringstream, and why isn't str doing it already?

Body:
and why isn't str doing it already?

I am sure some people will want it one way while others will want it another way.

how can I easily and cleanly get the remaining contents of the istringstream>

That's not too hard. Use:

std::cout << stream.str().substr(stream.tellg()) << std::endl;


问:
How to resolve "Minimum Font Size greater than current font size"?
I have a iOS project, Objective-C and storyboard base. I get this warning from Xcode when I build the project:

```<code>Main.storyboard: warning: Unsupported Configuration: Minimum Font Size greater than current font size
</code>```

How do I find the offending component in my storyboard?

I could open the Main.storyboard in a text editor and do manual inspection and comparison but that seems like a lot of work for a large storyboard.

答: Open the storyboard in the source mode and look for the warning text as in the snapshot.

Body:
I have a iOS project, Objective-C and storyboard base. I get this warning from Xcode when I build the project:

Main.storyboard: warning: Unsupported Configuration: Minimum Font Size greater than current font size

How do I find the offending component in my storyboard?

I could open the Main.storyboard in a text editor and do manual inspection and comparison but that seems like a lot of work for a large storyboard.


问:
How to define wildcard matching of url routes with angular ui-router
I want to define any in url whit angular ui-router

in angular self router we can define a route like this:

```<code>$routeProvider.when('/:params*', {
    template: 'test',
  })
</code>```

and when call this url

/a/b/c

it's work

how can do same in angular ui-router

答:
For eager matching of URL parameters, use:

```<code>$stateProvider
.state('all', {
    url: "/*params",
    template: "test"
});

//OR

$stateProvider
.state('all', {
    url: "/{params:.*}",
    template: "test"
});
</code>```

From the Docs:

URL Regex Parameters

Examples:

'/files/{path:.*}' - Matches any URL starting with '/files/' and captures the rest of the path into the parameter 'path'.

'/files/*path' - Ditto. Special syntax for catch all.

— UI-Router Wiki URL-Routing regex parameters

Body:
I want to define any in url whit angular ui-router

in angular self router we can define a route like this:

$routeProvider.when('/:params*', {
    template: 'test',
  })

and when call this url

/a/b/c

it's work

how can do same in angular ui-router

Body:
For eager matching of URL parameters, use:

$stateProvider
.state('all', {
    url: "/*params",
    template: "test"
});

//OR

$stateProvider
.state('all', {
    url: "/{params:.*}",
    template: "test"
});

From the Docs:

URL Regex Parameters

Examples:

'/files/{path:.*}' - Matches any URL starting with '/files/' and captures the rest of the path into the parameter 'path'.

'/files/*path' - Ditto. Special syntax for catch all.

— UI-Router Wiki URL-Routing regex parameters


问:
element.style.display is not what rendered in the browser
Probably a duplicate question but can not find the answer.

element.style.display is not what rendered in the browser.

Instead of returning the actual value (ie. block or inline etc), it returns empty. Tested in Chrome 56.0.2924.87 (64-bit).

How do I get the actual rendered value?

function displayStyle(aEvent) {
aEvent.target.textContent=aEvent.target.style.display;
}
window.onload = function() {
var  top_array = document.getElementsByClassName("top");
for(var i = 0; i <  top_array.length; i++)
{
   top_array[i].addEventListener("click", displayStyle, false);
}
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.top{
background-color:#FFF8DC;
}</code>```

top (click it and it will disappear because its style.display is empty)
```

答:
CSS styles are not available to JavaScript unless they have been formerly set in JavaScript or they have been hardcoded as inline styles.

Use getComputedStyle() instead:

function displayStyle(aEvent) {
  var target = aEvent.target;
  target.textContent = window.getComputedStyle(target).getPropertyValue('display');
}

window.onload = function() {
  var top_array = document.getElementsByClassName("top");
  for (var i = 0; i < top_array.length; i++) {
    top_array[i].addEventListener("click", displayStyle, false);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.top {
  background-color: #FFF8DC;
}</code>```

top (click it and it will now show "block" since we're getting its computed style.)
```

Body:
Probably a duplicate question but can not find the answer.

element.style.display is not what rendered in the browser.

Instead of returning the actual value (ie. block or inline etc), it returns empty. Tested in Chrome 56.0.2924.87 (64-bit).

How do I get the actual rendered value?

function displayStyle(aEvent) {
aEvent.target.textContent=aEvent.target.style.display;
}
window.onload = function() {
var  top_array = document.getElementsByClassName("top");
for(var i = 0; i <  top_array.length; i++)
{
   top_array[i].addEventListener("click", displayStyle, false);
}
}

.top{
background-color:#FFF8DC;
}

top (click it and it will disappear because its style.display is empty)

Body:
CSS styles are not available to JavaScript unless they have been formerly set in JavaScript or they have been hardcoded as inline styles.

Use getComputedStyle() instead:

function displayStyle(aEvent) {
  var target = aEvent.target;
  target.textContent = window.getComputedStyle(target).getPropertyValue('display');
}

window.onload = function() {
  var top_array = document.getElementsByClassName("top");
  for (var i = 0; i < top_array.length; i++) {
    top_array[i].addEventListener("click", displayStyle, false);
  }
}

.top {
  background-color: #FFF8DC;
}

<div class="top">top (click it and it will now show "block" since we're getting its computed style.)</div>


问:
Django and django-pyodbc error NotImplementedError SQL Server v8 is not supported
I'm working with Django and PyODBC to connect to a SQL Server 2000 database and I'm gettinh this error:

Exception Type: NotImplementedError

Exception Value: SQL Server v8 is not supported.

My traceback:

```<code>Environment:

Request Method: POST
Request URL: http://localhost/sistemas/cadastro_paciente/

Django Version: 1.10.5
Python Version: 2.7.12
Installed Applications:
['admin_tools',
 'admin_tools.theming',
 'admin_tools.menu',
 'admin_tools.dashboard',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'cadastro',
 'fenotipo',
 'cuser']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'cuser.middleware.CuserMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/var/www/sistemas/cadastro/views.py" in cadastro_paciente
  1297.             if pacienteDB and pacienteHGP:

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __nonzero__
  264.         return type(self).__bool__(self)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __bool__
  260.         self._fetch_all()

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _fetch_all
  1087.             self._result_cache = list(self.iterator())

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __iter__
  54.         results = compiler.execute_sql()

File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  824.             sql, params = self.as_sql()

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/compiler.py" in as_sql
  82.             supports_offset_clause = self.connection.sql_server_version >= 2012

File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __get__
  35.         res = instance.__dict__[self.name] = self.func(instance)

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/base.py" in sql_server_version
  390.         with self.temporary_connection() as cursor:

File "/usr/lib/python2.7/contextlib.py" in __enter__
  17.             return self.gen.next()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in temporary_connection
  564.         cursor = self.cursor()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in cursor
  231.             cursor = self.make_debug_cursor(self._cursor())

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in _cursor
  204.         self.ensure_connection()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in ensure_connection
  199.                 self.connect()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in connect
  173.         self.init_connection_state()

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/base.py" in init_connection_state
  349.         if self.sql_server_version < 2008:

File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __get__
  35.         res = instance.__dict__[self.name] = self.func(instance)

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/base.py" in sql_server_version
  395.                 raise NotImplementedError('SQL Server v%d is not supported.' % ver)

Exception Type: NotImplementedError at /cadastro_paciente/
Exception Value: SQL Server v8 is not supported.
</code>```

My odbc.ini:

```<code>[HGP]
Driver = FREETDS
Server = "IP"
Port = 1433
Database = database
Driver = /usr/local/lib/libtdsodbc.so
UsageCount = 1
</code>```

My freetds.conf

```<code>[HGP]
database = database
host = "IP"
port = 1433
tds version = 8.0
</code>```

Driver configuration on odbcinst.int

```<code>[FREETDS]
Description = FreeTDS
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount = 1
</code>```

The my settings.py

```<code>'hgp': {
        'ENGINE': 'sql_server.pyodbc', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'hemovida',            # Or path to database file if using sqlite3.
        'USER': 'sa',                  # Not used with sqlite3.
        'PASSWORD': '',                # Not used with sqlite3.
        'HOST': 'IP',         # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',

        'OPTIONS': {
                'driver': 'FREETDS',
                'MARS_Connection': False,
                'dsn' : 'HGP',
            },
    },
</code>```

My query

```<code>pacienteHGP = Paciente_Hemovida.objects.using('hgp').filter(paciente=postPaciente)
</code>```

答:
As mentioned before, using SQL Server 2000 is a really bad idea; it doesn't receive any support, bug fixes, or most importantly, security patches from Microsoft.

That said, if you're using django-pyodbc-azure, you may be able to monkey patch it to get it working. See this line:

https://github.com/michiya/django-pyodbc-azure/blob/azure-1.10/sql_server/pyodbc/base.py#L145

Add 8: 2000, to the _sql_server_version dictionary:

```<code>_sql_server_versions = {
    8: 2000,
    9: 2005,
    10: 2008,
    11: 2012,
    12: 2014,
    13: 2016,
    14: 2017,
}
</code>```

I can place no guarantees on how this will or won't work, but you're welcome to try. That should get you past the error you're encountering.

You will also want to modify your freetds.conf, as 8.0 is not a valid TDS Version:

```<code>[HGP]
database = database
host = "IP"
port = 1433
tds version = 7.1
</code>```

Source: http://www.freetds.org/userguide/choosingtdsprotocol.htm

Good luck, and again, I highly recommend upgrading to a modern version of SQL Server.

Body:
I'm working with Django and PyODBC to connect to a SQL Server 2000 database and I'm gettinh this error:

Exception Type: NotImplementedError

Exception Value: SQL Server v8 is not supported.

My traceback:

Environment:

Request Method: POST
Request URL: http://localhost/sistemas/cadastro_paciente/

Django Version: 1.10.5
Python Version: 2.7.12
Installed Applications:
['admin_tools',
 'admin_tools.theming',
 'admin_tools.menu',
 'admin_tools.dashboard',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'cadastro',
 'fenotipo',
 'cuser']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'cuser.middleware.CuserMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/var/www/sistemas/cadastro/views.py" in cadastro_paciente
  1297.             if pacienteDB and pacienteHGP:

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __nonzero__
  264.         return type(self).__bool__(self)

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __bool__
  260.         self._fetch_all()

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _fetch_all
  1087.             self._result_cache = list(self.iterator())

File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in __iter__
  54.         results = compiler.execute_sql()

File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  824.             sql, params = self.as_sql()

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/compiler.py" in as_sql
  82.             supports_offset_clause = self.connection.sql_server_version >= 2012

File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __get__
  35.         res = instance.__dict__[self.name] = self.func(instance)

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/base.py" in sql_server_version
  390.         with self.temporary_connection() as cursor:

File "/usr/lib/python2.7/contextlib.py" in __enter__
  17.             return self.gen.next()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in temporary_connection
  564.         cursor = self.cursor()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in cursor
  231.             cursor = self.make_debug_cursor(self._cursor())

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in _cursor
  204.         self.ensure_connection()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in ensure_connection
  199.                 self.connect()

File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py" in connect
  173.         self.init_connection_state()

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/base.py" in init_connection_state
  349.         if self.sql_server_version < 2008:

File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py" in __get__
  35.         res = instance.__dict__[self.name] = self.func(instance)

File "/usr/local/lib/python2.7/dist-packages/sql_server/pyodbc/base.py" in sql_server_version
  395.                 raise NotImplementedError('SQL Server v%d is not supported.' % ver)

Exception Type: NotImplementedError at /cadastro_paciente/
Exception Value: SQL Server v8 is not supported.

My odbc.ini:

[HGP]
Driver = FREETDS
Server = "IP"
Port = 1433
Database = database
Driver = /usr/local/lib/libtdsodbc.so
UsageCount = 1

My freetds.conf

[HGP]
database = database
host = "IP"
port = 1433
tds version = 8.0

Driver configuration on odbcinst.int

[FREETDS]
Description = FreeTDS
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount = 1

The my settings.py

'hgp': {
        'ENGINE': 'sql_server.pyodbc', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'hemovida',            # Or path to database file if using sqlite3.
        'USER': 'sa',                  # Not used with sqlite3.
        'PASSWORD': '',                # Not used with sqlite3.
        'HOST': 'IP',         # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',

        'OPTIONS': {
                'driver': 'FREETDS',
                'MARS_Connection': False,
                'dsn' : 'HGP',
            },
    },

My query

pacienteHGP = Paciente_Hemovida.objects.using('hgp').filter(paciente=postPaciente)

Body:
As mentioned before, using SQL Server 2000 is a really bad idea; it doesn't receive any support, bug fixes, or most importantly, security patches from Microsoft.

That said, if you're using django-pyodbc-azure, you may be able to monkey patch it to get it working. See this line:

https://github.com/michiya/django-pyodbc-azure/blob/azure-1.10/sql_server/pyodbc/base.py#L145

Add 8: 2000, to the _sql_server_version dictionary:

_sql_server_versions = {
    8: 2000,
    9: 2005,
    10: 2008,
    11: 2012,
    12: 2014,
    13: 2016,
    14: 2017,
}

I can place no guarantees on how this will or won't work, but you're welcome to try. That should get you past the error you're encountering.

You will also want to modify your freetds.conf, as 8.0 is not a valid TDS Version:

[HGP]
database = database
host = "IP"
port = 1433
tds version = 7.1

Source: http://www.freetds.org/userguide/choosingtdsprotocol.htm

Good luck, and again, I highly recommend upgrading to a modern version of SQL Server.


问:
How I delete custom dexterity objects in Plone 4?
I'm trying delete some custom dexterity objects, bellow have snipets code of this custom object.

```<code>class IDigitalFile(model.Schema):
        """Dexterity-Schema
        """

    ...

    directives.read_permission(auto="cmf.ManagePortal")
    directives.write_permission(auto="cmf.ManagePortal")
    fieldset('Admins Only', fields=['auto', 'uploded_at', 'codLote'] )
    auto = schema.Bool(
        title=_(u"Upload via Script?"),
        required=True,
        default=False,
    )
    ...
</code>```

And I try use sudo plone_daemon bin/client2 -O Plone debug and apply this code:

```<code>from zope.site.hooks import setSite
site = 'Plone'
context = app[site]
setSite(context)
portal_catalog = context.portal_catalog
itens = portal_catalog(portal_type='digitalfile', path='/ged/')
print itens
</code>```

After rum this script my output is [], just epmty but if i use the similar code in ZMI I have all brains.

So, in ZMI we can't user methods to delete 'cuz have restrictions.
And my goal is delete all objects digitalfileif flag Truein autofield.

How can I do it if my results are empties?
Or what I did wrong for output is empty?

[UPDATE 1]

This problem apper to me:

```<code>zero@srv-d:/opt/Plone439/zeocluster$ sudo -u plone_daemon bin/client2 -O Plone debug
Starting debugger (the name "app" is bound to the top-level Zope object)
2017-03-31 10:09:04 WARNING ZODB.blob (18048) Blob dir /opt/Plone439/zeocluster/var/blobstorage/ has insecure mode setting
Traceback (most recent call last):
  File "/opt/Plone439/zeocluster/parts/client2/bin/interpreter", line 281, in <module>
    exec(_val)
  File "<string>", line 1, in <module>
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/BaseRequest.py", line 623, in traverse
    response.unauthorized()
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/HTTPResponse.py", line 756, in unauthorized
    raise Unauthorized, m
zExceptions.unauthorized.Unauthorized: You are not authorized to access this resource.
</code>```

[UPDATE 2 - SOLVED]

Maybe have a easy way to do, but in this moment, this script solved my problem and I'm sharing if someone need...

```<code># -*- coding: utf-8 -*-
from zope.site.hooks import setSite
from plone import api
import transaction

# Setting the plone portal in var context
site = 'Plone'
context = app[site]
setSite(context)

# grabbing portal_catalog tool
portal_catalog = context.portal_catalog

# setting the user that have permission
with api.env.adopt_user(username='admin'):
    # grabbing all items digitalfile
    brains = portal_catalog(portal_type='digitalfile', path='/ged')

for brain in brains:
    if 'TO BE DELETE' in brain.Description:
        item = api.content.get(path=brain.getPath())
        api.content.delete(obj=item)
        transaction.commit()
</code>```

答:
I think portal_type is 'Dexterity Item' in this case. Try portal_catalog(object_provides=IDigitalFile.__identifier__) instead.
You don't need the path argument, if you want to do this globally.

Body:
I'm trying delete some custom dexterity objects, bellow have snipets code of this custom object.

class IDigitalFile(model.Schema):
        """Dexterity-Schema
        """

    ...

    directives.read_permission(auto="cmf.ManagePortal")
    directives.write_permission(auto="cmf.ManagePortal")
    fieldset('Admins Only', fields=['auto', 'uploded_at', 'codLote'] )
    auto = schema.Bool(
        title=_(u"Upload via Script?"),
        required=True,
        default=False,
    )
    ...

And I try use sudo plone_daemon bin/client2 -O Plone debug and apply this code:

from zope.site.hooks import setSite
site = 'Plone'
context = app[site]
setSite(context)
portal_catalog = context.portal_catalog
itens = portal_catalog(portal_type='digitalfile', path='/ged/')
print itens

After rum this script my output is [], just epmty but if i use the similar code in ZMI I have all brains.

So, in ZMI we can't user methods to delete 'cuz have restrictions.
And my goal is delete all objects digitalfileif flag Truein autofield.

How can I do it if my results are empties?
Or what I did wrong for output is empty?

[UPDATE 1]

This problem apper to me:

zero@srv-d:/opt/Plone439/zeocluster$ sudo -u plone_daemon bin/client2 -O Plone debug
Starting debugger (the name "app" is bound to the top-level Zope object)
2017-03-31 10:09:04 WARNING ZODB.blob (18048) Blob dir /opt/Plone439/zeocluster/var/blobstorage/ has insecure mode setting
Traceback (most recent call last):
  File "/opt/Plone439/zeocluster/parts/client2/bin/interpreter", line 281, in <module>
    exec(_val)
  File "<string>", line 1, in <module>
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/BaseRequest.py", line 623, in traverse
    response.unauthorized()
  File "/opt/Plone439/buildout-cache/eggs/Zope2-2.13.24-py2.7.egg/ZPublisher/HTTPResponse.py", line 756, in unauthorized
    raise Unauthorized, m
zExceptions.unauthorized.Unauthorized: You are not authorized to access this resource.

[UPDATE 2 - SOLVED]

Maybe have a easy way to do, but in this moment, this script solved my problem and I'm sharing if someone need...

# -*- coding: utf-8 -*-
from zope.site.hooks import setSite
from plone import api
import transaction

# Setting the plone portal in var context
site = 'Plone'
context = app[site]
setSite(context)

# grabbing portal_catalog tool
portal_catalog = context.portal_catalog

# setting the user that have permission
with api.env.adopt_user(username='admin'):
    # grabbing all items digitalfile
    brains = portal_catalog(portal_type='digitalfile', path='/ged')

for brain in brains:
    if 'TO BE DELETE' in brain.Description:
        item = api.content.get(path=brain.getPath())
        api.content.delete(obj=item)
        transaction.commit()


问:
didRegisterForRemoteNotificationsWithDeviceToken is not called on ios10
I have 2 iphones: 1 - with ios 10 and 2 - with ios 9

While trying the 1st iphone:

didRegisterForRemoteNotificationsWithDeviceToken method is not called when user clicks "allow" on the alert
Though, the method didRegisterUserNotificationSettings IS called.
In this case device does NOT receive push notifications.

While trying the 2nd iphone:

Both methods are called here. And device DOES receive push notifications.

Then I checked on simulator ios 8

In this case the same as in 1st. Only one method is called.

I checked some answers for similar question but they didn't help me.
I doubt that the issue is somewhere within push notifications settings, cuz ios 9 works OK.
So the issue is somewhere within ios 10.

The very questions are:

How can I call method didRegisterForRemoteNotificationsWithDeviceToken

Or how can I get the device token since it's the goal

Looking forward for your help!

答:
You should call this method inside didFinishLaunchingWithOptions</p>

```<code>func registerForNotifications(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.alert,.sound,.badge]) { (granted, error) in
                if granted{
                    UIApplication.shared.registerForRemoteNotifications()
                }else{
                    print("Notification permission denied.")
                    if !(SharedPrefs.sharedInstance!.isLoggedIn){
                        Defaults.sharedPref.removeNotificationToken()
                    }else{
                        UIApplication.shared.unregisterForRemoteNotifications()
                        print("We will delete the token at the time of logout")
                    }
                }
            }

        } else {
            // For ios 9 and below
            let type: UIUserNotificationType = [.alert,.sound,.badge];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications()
        }
    }
</code>```

Body:
You should call this method inside didFinishLaunchingWithOptions

func registerForNotifications(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options:[.alert,.sound,.badge]) { (granted, error) in
                if granted{
                    UIApplication.shared.registerForRemoteNotifications()
                }else{
                    print("Notification permission denied.")
                    if !(SharedPrefs.sharedInstance!.isLoggedIn){
                        Defaults.sharedPref.removeNotificationToken()
                    }else{
                        UIApplication.shared.unregisterForRemoteNotifications()
                        print("We will delete the token at the time of logout")
                    }
                }
            }

        } else {
            // For ios 9 and below
            let type: UIUserNotificationType = [.alert,.sound,.badge];
            let setting = UIUserNotificationSettings(types: type, categories: nil);
            UIApplication.shared.registerUserNotificationSettings(setting);
            UIApplication.shared.registerForRemoteNotifications()
        }
    }


问:
Crosstabs Using R
I have a data frame with columns of Age_group(10 to 20,20 to 30,30 to 40,40 to 50) 60), Tenure(1:5) and Response(True or False )how to create a table which gives me count of true for each group and tenure.

For eg

```<code>       1 2 3 4 5
10-20
20-30  Count of True's
30-40
40-50
</code>```

Title: Crosstabs Using R

Body:
I have a data frame with columns of Age_group(10 to 20,20 to 30,30 to 40,40 to 50) 60), Tenure(1:5) and Response(True or False )how to create a table which gives me count of true for each group and tenure.

For eg

       1 2 3 4 5
10-20
20-30  Count of True's
30-40
40-50

Body:
require(reshape2)

df <- data.frame(age = sample(seq(10,50,5),100, replace = T),
             tenure = sample(1:5, 100, replace = T),
             response = sample(0:1, 100, replace = T))

 head(df)

age tenure response
1  10      5        0
2  50      4        0
3  30      5        0
4  10      4        0
5  25      5        0
6  35      1        0

dcast(df, age ~ tenure,sum, value.var = 'response')

  age 1 2 3 4 5
1  10 0 0 2 1 1
2  15 1 2 3 0 0
3  20 3 0 0 0 0
4  25 0 1 1 3 0
5  30 2 2 0 2 2
6  35 0 1 2 0 5
7  40 2 0 2 0 0
8  45 0 0 3 1 0
9  50 1 0 0 2 0


问:
How to make a MVC 3 Webgrid with checkbox column?
The code below will insert an actionlink into one of the web grids' columns.

```<code>    @{
    View.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    var usersGrid = new WebGrid(source: Model,
        rowsPerPage: 40);
}
@usersGrid.GetHtml(
        tableStyle: "grid",
        headerStyle: "head",
        alternatingRowStyle: "alt",
                columns: usersGrid.Columns(
                    usersGrid.Column(format: (item) =>
                         Html.ActionLink("Edit", "Edit", new { id = item.Id})),
                    usersGrid.Column("Surname")
        )
    )
</code>```

But if i exchange that line for this:

```<code>                usersGrid.Column(format: (item) => Html.CheckBox(item.Id)),
</code>```

I get this error:

Error 4   The best overloaded method
  match for
  'System.Web.Helpers.WebGrid.Column(string,
  string, System.Func,
  string, bool)' has some invalid
  arguments.

I don't quite understand the difference between the two.. why does one work and the other error?

The ultimate goal is to be able to tick a number of check boxes and then send to print their info.

答:
This error is occurring because the CheckBox call is not returning the same datatype that ActionLink is returning.

This is what you do. Do a message box call on the action link call and the check box call with same arguments, rap each inside the function call TypeName() and display the results in a msgbox for u to see. Also, do a .ToString in both as well, now, look at the results, it should tell you if there is a discrepancy between the datatypes returned, if you can, post the results, and I can tell you more. Let me know.

Body:
The code below will insert an actionlink into one of the web grids' columns.

    @{
    View.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";

    var usersGrid = new WebGrid(source: Model,
        rowsPerPage: 40);
}
@usersGrid.GetHtml(
        tableStyle: "grid",
        headerStyle: "head",
        alternatingRowStyle: "alt",
                columns: usersGrid.Columns(
                    usersGrid.Column(format: (item) =>
                         Html.ActionLink("Edit", "Edit", new { id = item.Id})),
                    usersGrid.Column("Surname")
        )
    )

But if i exchange that line for this:

                usersGrid.Column(format: (item) => Html.CheckBox(item.Id)),

I get this error:

Error 4   The best overloaded method
  match for
  'System.Web.Helpers.WebGrid.Column(string,
  string, System.Func,
  string, bool)' has some invalid
  arguments.

I don't quite understand the difference between the two.. why does one work and the other error?

The ultimate goal is to be able to tick a number of check boxes and then send to print their info.


问:
Jenkins - passing variables between jobs?
I have two jobs in jenkins, both of which need the same parameter.

How can I run the first job with a parameter so that when it triggers the second job, the same parameter is used?

答:
Reading through the answers, I don't see another option that I like so will offer it as well.  I love the parameterization of jobs, but it doesn't always scale well.  If you have jobs which are not directly downstream of the first job but farther down the pipeline, you don't really want to parameterize every job in the pipeline so as to be able to pass the parameters all the way through.  Or if you have a large number of parameters used by a variety of other jobs (especially those not necessarily tied to one parent or master job), again parameterization doesn't work.

In these cases, I favor outputting the values to a properties file and then injecting that in whatever job I need using the EnvInject plugin.  This can be done dynamically, which is another way to solve the issue from another answer above where parameterized jobs were still used.  This solution scales very well in many scenarios.


答:
Works if you set it directly in style attribute:

function displayStyle(aEvent) {
aEvent.target.textContent=aEvent.target.style.display;
}
window.onload = function() {
var  top_array = document.getElementsByClassName("top");
for(var i = 0; i <  top_array.length; i++)
{
   top_array[i].addEventListener("click", displayStyle, false);
}
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.top{
background-color:#FFF8DC;
}</code>```

top (click it and it will disappear because its style.display is empty)
```

Obs.: setting it on CSS also doesn't work.

I still don't know why, anyway.

Now I know, thanks to Rick Hitchcock's answer.

Title: element.style.display is not what rendered in the browser

Body:
Works if you set it directly in style attribute:

function displayStyle(aEvent) {
aEvent.target.textContent=aEvent.target.style.display;
}
window.onload = function() {
var  top_array = document.getElementsByClassName("top");
for(var i = 0; i <  top_array.length; i++)
{
   top_array[i].addEventListener("click", displayStyle, false);
}
}

.top{
background-color:#FFF8DC;
}

<div class="top" style="display: block;">top (click it and it will disappear because its style.display is empty)</div>

Obs.: setting it on CSS also doesn't work.

I still don't know why, anyway.

Now I know, thanks to Rick Hitchcock's answer.


问:
Why should we use init(coder) when we can just dump everything inside awakeFromNib?
I read What exactly is init coder aDecoder?

but that doesn't answer to why not put everything inside awakeFromNib and forget using init(coder aCoder : NSCoder)?

In the comments of the accepted answer Fattie says:

"sometimes you can't do that". You typically can but not always

Can anyone provide more explanation to that?

答:
If you have lets that need to be initialized in an init, you have to use that instead of awakeFromNib.

Doing so allows you to avoid implicitly unwrapped optionals.

EDIT:

If you want your class to have properties, you can either do

```<code> let a: String
</code>```

or

```<code> var a: String! = nil // this is called an "implicitly unwrapped optional" -- it's the ! at the end of the type that makes it that.
</code>```

The first is preferable because it is safe. In the second, you run the risk of accessing a before it is initialized.

But, to make sure a is always initialized, it needs to get its value in an init of the class.

So,

```<code>init(coder aCoder : NSCoder) {
   a = "hello" // usually this is something more complex
   // read in coder or whatever else you need to do
}
</code>```

If you don't have an init, then you can't have an init that gets initialized later.

Body:
If you have lets that need to be initialized in an init, you have to use that instead of awakeFromNib.

Doing so allows you to avoid implicitly unwrapped optionals.

EDIT:

If you want your class to have properties, you can either do

 let a: String

or

 var a: String! = nil // this is called an "implicitly unwrapped optional" -- it's the ! at the end of the type that makes it that.

The first is preferable because it is safe. In the second, you run the risk of accessing a before it is initialized.

But, to make sure a is always initialized, it needs to get its value in an init of the class.

So,

init(coder aCoder : NSCoder) {
   a = "hello" // usually this is something more complex
   // read in coder or whatever else you need to do
}

If you don't have an init, then you can't have an init that gets initialized later.


问:
enum switcher for functions with different signatures
many times, it happens to find situations where I have an enum or an int, and I have functions parameterized on the specific enum values / integers. At runtime I have an enum / integer that I use to call the specific function. With some code it should be clearer:

```<code>template<int i>
struct MyTrait
  {
  void f(int) { return 999;}
  };

template<>
struct MyTrait<1>
  {
  void f(int a, int b) { return 1; }
  };

template<>
struct MyTrait<2>
  {
  static const int ARD = 2;
  void f(int a, int b, int c) { return 100;}
  };

template<>
struct MyTrait<3>
  {
  static const int ARD = 3;
  void f(int a) { return 120;}
  };

template<class... Args>
int switcher(int value, Args... arguments)
  {
  switch(value)
    {
    case indices:
      return MyTrait<1>::f(arguments...);
    case 2:
      MyTrait<2>::f(arguments...);
    case 3:
      MyTrait<3>::f(arguments...);
    default:
       0;
    }
  return 1;
  }

// switcher(3, 10) should call MyTrait<3>::f
</code>```

To make an example of why this can be useful please check here

I'm using C++11 and I've implemented something similar to the cswitch presented in the link I've posted. Problem is that, for now, it only works with function with the same signature. My goal is instead to make it also work  with functions with different signatures, like the ones in the traits of the example.

Primary goal here is performance: same speed as the switch.
Of course, everything would be quite easy if it could have been possible to use the ... operator in the switch, functions that returned (depending on the argument) different values or if the named label gcc extension were a standard feature (alas I've also considered the goto statement as last resort).

I've tried tens of approaches etc but nothing seems to work as I want.. I'm starting to think that at the moment this is impossible.. feel free (I really hope it!!) to contradict me.

The closest solution I've found so far is to create a jump table, store the arguments into a tuple, convert that tuple (the address) to void* and then convert it back in the traits. But there are performance costs also here and I'm not totally sure if this can produce UB.

I would exclude solutions that use MACROS, C++17 features (ideally C++11 only) and non standard features..

Thanks

答:
If you want to maintain your MyTrait classes, it's a matter of defining a fallback template function for each specialization.

As an example:

```<code>template<>
struct MyTrait<1> {
    template<typename... Args> static int f(Args&&...) { return {}; }
    static int f(int, int) { return 1; }
};
</code>```

See here a working example.

If you can refactor a bit your code, you can use free functions, tag dispatching and a single fallback functions to avoid compilation errors.

As an example:

```<code>#include<iostream>
#include<utility>

template<int>
struct tag {};

int f(tag<1>, int, int) { return 1; }
int f(tag<2>, int, int, int) { return 100;}
int f(tag<3>, int) { std::cout << "&";  return 120; }

template<typename... Args>
auto caller(int, Args&&... args) -> decltype(f(std::forward<Args>(args)...)) {
    return f(std::forward<Args>(args)...);
}

template<typename... Args>
int caller(char, Args&&... args) {
    return {};
}

template<class... Args>
int switcher(int value, Args&&... arguments) {
    switch(value) {
    case 1:
        caller(0, tag<1>{}, std::forward<Args>(arguments)...);
        break;
    case 2:
        caller(0, tag<2>{}, std::forward<Args>(arguments)...);
        break;
    case 3:
        caller(0, tag<3>{}, std::forward<Args>(arguments)...);
        break;
    default:
        (void)0;
    }

    return 1;
}

int main() {
    switcher(3, 10);
}
</code>```

EDIT

After this comment:

I'm trying to remove that switch, and the solution you proposed has a switch

I'm proposing a slightly modified version that has no longer a switch but relies on recursion and inheritance:

```<code>#include <type_traits>
#include<iostream>
#include<utility>

template<int N> struct tag: tag<N-1> {};
template<> struct tag<0> {};

int f(tag<1>, int, int) { return 1; }
int f(tag<2>, int, int, int) { return 100;}
int f(tag<3>, int) { std::cout << "&";  return 120; }

template<typename... Args>
int f(Args&&...) { return {}; }

template<int N, typename... Args>
std::enable_if_t<(N == 0), int>
caller(tag<N> t, Args&&... args) {
    return f(t, std::forward<Args>(args)...);
}

template<int N, typename... Args>
std::enable_if_t<(N > 0), int>
caller(tag<N> t, int value, Args&&... args) {
    return N == value ? f(t, std::forward<Args>(args)...) : caller(tag<N-1>{}, value, std::forward<Args>(args)...);
}

template<class... Args>
int switcher(int value, Args&&... arguments) {
    return caller(tag<3>{}, value, std::forward<Args>(arguments)...);
}

int main() {
    switcher(3, 10);
}
</code>```

Body:
many times, it happens to find situations where I have an enum or an int, and I have functions parameterized on the specific enum values / integers. At runtime I have an enum / integer that I use to call the specific function. With some code it should be clearer:

template<int i>
struct MyTrait
  {
  void f(int) { return 999;}
  };

template<>
struct MyTrait<1>
  {
  void f(int a, int b) { return 1; }
  };

template<>
struct MyTrait<2>
  {
  static const int ARD = 2;
  void f(int a, int b, int c) { return 100;}
  };

template<>
struct MyTrait<3>
  {
  static const int ARD = 3;
  void f(int a) { return 120;}
  };

template<class... Args>
int switcher(int value, Args... arguments)
  {
  switch(value)
    {
    case indices:
      return MyTrait<1>::f(arguments...);
    case 2:
      MyTrait<2>::f(arguments...);
    case 3:
      MyTrait<3>::f(arguments...);
    default:
       0;
    }
  return 1;
  }

// switcher(3, 10) should call MyTrait<3>::f

To make an example of why this can be useful please check here

I'm using C++11 and I've implemented something similar to the cswitch presented in the link I've posted. Problem is that, for now, it only works with function with the same signature. My goal is instead to make it also work  with functions with different signatures, like the ones in the traits of the example.

Primary goal here is performance: same speed as the switch.
Of course, everything would be quite easy if it could have been possible to use the ... operator in the switch, functions that returned (depending on the argument) different values or if the named label gcc extension were a standard feature (alas I've also considered the goto statement as last resort).

I've tried tens of approaches etc but nothing seems to work as I want.. I'm starting to think that at the moment this is impossible.. feel free (I really hope it!!) to contradict me.

The closest solution I've found so far is to create a jump table, store the arguments into a tuple, convert that tuple (the address) to void* and then convert it back in the traits. But there are performance costs also here and I'm not totally sure if this can produce UB.

I would exclude solutions that use MACROS, C++17 features (ideally C++11 only) and non standard features..

Thanks

Body:
If you want to maintain your MyTrait classes, it's a matter of defining a fallback template function for each specialization.

As an example:

template<>
struct MyTrait<1> {
    template<typename... Args> static int f(Args&&...) { return {}; }
    static int f(int, int) { return 1; }
};

See here a working example.

If you can refactor a bit your code, you can use free functions, tag dispatching and a single fallback functions to avoid compilation errors.

As an example:

#include<iostream>
#include<utility>

template<int>
struct tag {};

int f(tag<1>, int, int) { return 1; }
int f(tag<2>, int, int, int) { return 100;}
int f(tag<3>, int) { std::cout << "&";  return 120; }

template<typename... Args>
auto caller(int, Args&&... args) -> decltype(f(std::forward<Args>(args)...)) {
    return f(std::forward<Args>(args)...);
}

template<typename... Args>
int caller(char, Args&&... args) {
    return {};
}

template<class... Args>
int switcher(int value, Args&&... arguments) {
    switch(value) {
    case 1:
        caller(0, tag<1>{}, std::forward<Args>(arguments)...);
        break;
    case 2:
        caller(0, tag<2>{}, std::forward<Args>(arguments)...);
        break;
    case 3:
        caller(0, tag<3>{}, std::forward<Args>(arguments)...);
        break;
    default:
        (void)0;
    }

    return 1;
}

int main() {
    switcher(3, 10);
}

EDIT

After this comment:

I'm trying to remove that switch, and the solution you proposed has a switch

I'm proposing a slightly modified version that has no longer a switch but relies on recursion and inheritance:

#include <type_traits>
#include<iostream>
#include<utility>

template<int N> struct tag: tag<N-1> {};
template<> struct tag<0> {};

int f(tag<1>, int, int) { return 1; }
int f(tag<2>, int, int, int) { return 100;}
int f(tag<3>, int) { std::cout << "&";  return 120; }

template<typename... Args>
int f(Args&&...) { return {}; }

template<int N, typename... Args>
std::enable_if_t<(N == 0), int>
caller(tag<N> t, Args&&... args) {
    return f(t, std::forward<Args>(args)...);
}

template<int N, typename... Args>
std::enable_if_t<(N > 0), int>
caller(tag<N> t, int value, Args&&... args) {
    return N == value ? f(t, std::forward<Args>(args)...) : caller(tag<N-1>{}, value, std::forward<Args>(args)...);
}

template<class... Args>
int switcher(int value, Args&&... arguments) {
    return caller(tag<3>{}, value, std::forward<Args>(arguments)...);
}

int main() {
    switcher(3, 10);
}


问:
How to run a php script with arguments from a batch file?
I have a php script named test.php

in this file i have to pass one parameter using $argv.

i want to create window batch file that require one argument or parameter and pass that parameter in php script.

forexample in Windows Dos

```<code>test.bat hello123
</code>```

so hello123 is passed to test.php ($argv[1] is first parameter)

Can anyone help me to write batch file for this this kind of script?

答:
```<code>@c:/path/to/php.exe test.php %1
</code>```

Body:
I have a php script named test.php

in this file i have to pass one parameter using $argv.

i want to create window batch file that require one argument or parameter and pass that parameter in php script.

forexample in Windows Dos

test.bat hello123

so hello123 is passed to test.php ($argv[1] is first parameter)

Can anyone help me to write batch file for this this kind of script?

Body: @c:/path/to/php.exe test.php %1


问:
How to scale WPF controls with windows font?
I am creating a personal project to get the hang of WPF and want to play around with its powerful layouts and options. Is it possible to scale my WPF form/window with the font size set in the windows settings? For example, a user can change their font sizes through the windows OS and I want my form to scale accordingly. How would I approach starting to set this up?

Edit: My original question is not phrased correctly. Essentially I am looking for an explanation on how WPF handles automatic scaling differently than winforms. Also I want to know how to set up automatic scaling from the beginning in a wpf form.

答:
You should be able to accomplish this by setting the AutoScaleMode on your controls:

this.AutoScaleMode = AutoScaleMode.Dpi

or

this.AutoScaleMode = AutoScaleMode.Font

Not sure which will work best for the OS Font scaling (i am assuming DPI would be the choice, but i could be wrong).


问:
Extracting numbers and slashes from a string
I have the following string

```<code>Policy 023203232/02/05 saved successfully
</code>```

And I need to extract 023203232/02/05 from the above string and I have written the following code

```<code>puts a[/\d+\/\d+\/\d+/]
</code>```

And it works fine. But If the number increases with the slashes like, 023203232/02/05/06 I have to include one more \d+ but I don't know how many slashes and number would repeat this way, So any one can suggest me to write some generic solution

If string is

```<code>Policy 023203232/02/05 saved successfully
</code>```

Then

```<code>023203232/02/05
</code>```

If string is

```<code>Policy 023203232/02/05/06 saved successfully
</code>```

Then

```<code>023203232/02/05/06
</code>```

If string is

```<code>Policy 023203232/02/05/06/08 saved successfully
</code>```

Then

```<code>023203232/02/05/06/08
</code>```

How to write such a generic regular expression?

答:
Assuming contiguous digits and slashes (i.e. no spaces in between), this should work:</p>

```<code>a.scan(/\d+\/?/).join
</code>```

Body:
I have the following string

Policy 023203232/02/05 saved successfully

And I need to extract 023203232/02/05 from the above string and I have written the following code

puts a[/\d+\/\d+\/\d+/]

And it works fine. But If the number increases with the slashes like, 023203232/02/05/06 I have to include one more \d+ but I don't know how many slashes and number would repeat this way, So any one can suggest me to write some generic solution

If string is

Policy 023203232/02/05 saved successfully

Then

023203232/02/05

If string is

Policy 023203232/02/05/06 saved successfully

Then

023203232/02/05/06

If string is

Policy 023203232/02/05/06/08 saved successfully

Then

023203232/02/05/06/08

How to write such a generic regular expression?

Body:
Assuming contiguous digits and slashes (i.e. no spaces in between), this should work:

a.scan(/\d+\/?/).join


答:
why isn't str doing it already?

Because that is documented behavior of this method:

Returns a copy of the underlying string as if by calling rdbuf()->str().

It always returns whole underlying string

how can I easily and cleanly get the remaining contents of the istringstream

Just change your code to:

```<code>std::cout << stream.rdbuf() << std::endl;
</code>```

live example

output is:

```<code>Two
 words
</code>```

Title: istringstream::str() does not return current contents

Body:
I have an istringstream, and I'm putting some data into it. Then, I extract some of the data I put in, and then I want to get the remaining contents of the istringstream. I thought, apparently incorrectly, that the following would do exactly that:

std::istringstream stream("Two words");
std::string word;
stream >> word;
std::cout << word << std::endl;
std::cout << stream.str() << std::endl;

The output is:

Two words
Two
Two words

In other words, the extraction operation is returning the correct value, and it's advancing the read pointer, as indicated by tellg, but str doesn't seem to care--it just returns the entire original contents of the istringstream.
I'm sure this is expected behavior, but I just can't fathom why.

So: how can I easily and cleanly get the remaining contents of the istringstream, and why isn't str doing it already?

Body:
why isn't str doing it already?

Because that is documented behavior of this method:

Returns a copy of the underlying string as if by calling rdbuf()->str().

It always returns whole underlying string

how can I easily and cleanly get the remaining contents of the istringstream

Just change your code to:

std::cout << stream.rdbuf() << std::endl;

live example

output is:

Two
 words


问:
jacorb.orb warning em Jboss EAP 7 / Wildfly 10
SO... I'm receiving strange WARNs from a application in JBoss-EAP 7 / Wildfly 10:

```<code>[Server:teste] INFO  2017-02-15 13:52:02,669 [jacorb.orb] Initialising ORB with ID:
[Server:teste] WARN  2017-02-15 13:52:02,701 [jacorb.orb] unable to build ORBInitializer from class true: Ignoring
[Server:teste] INFO  2017-02-15 13:52:02,750 [orb.interceptors] InterceptorManager started with 0 Server Interceptors, 0 Client Interceptors and 1 IOR Interceptors
</code>```

This app have ten years and need the CORBA libs to use a JMS Queue.

Should I worry?
What this WARNING mean?

[EDITED]

```<code>Additional logs popout out now:

javax.naming.InvalidNameException: Couldn't resolve initial reference: NameService [Root exception is org.omg.CORBA.ORBPackage.InvalidName: IDL:omg.org/CORBA/ORB/InvalidName:1.0]
        at weblogic.corba.j2ee.naming.Utils.wrapNamingException(Utils.java:52)
        at weblogic.corba.j2ee.naming.ORBHelper.getORBReferenceWithRetry(ORBHelper.java:644)
        at weblogic.corba.j2ee.naming.ORBHelper.getORBReference(ORBHelper.java:594)
        at weblogic.corba.j2ee.naming.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:85)
        at weblogic.corba.j2ee.naming.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:31)
        at weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:46)
        at org.jboss.as.naming.InitialContext.getDefaultInitCtx(InitialContext.java:114)
        at org.jboss.as.naming.InitialContext.init(InitialContext.java:99)
        at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154)
        at org.jboss.as.naming.InitialContext.<init>(InitialContext.java:89)
        at org.jboss.as.naming.InitialContextFactory.getInitialContext(InitialContextFactory.java:43)
        at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
        at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
        at javax.naming.InitialContext.init(InitialContext.java:244)
        at javax.naming.InitialContext.<init>(InitialContext.java:216)
        at com.alu.feeder.tasks.ExpediterRfbNotificationConsumerTask.executarProcesso(ExpediterRfbNotificationConsumerTask.java:88)
        at com.alu.feeder.tasks.ExpediterRfbNotificationConsumerTask.run(ExpediterRfbNotificationConsumerTask.java:51)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
        at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:260)
        at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
        at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
        at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: org.omg.CORBA.ORBPackage.InvalidName: IDL:omg.org/CORBA/ORB/InvalidName:1.0
        at org.jacorb.orb.ORB.resolve_initial_references(ORB.java:1609)
        at weblogic.corba.j2ee.naming.ORBHelper.getORBReferenceWithRetry(ORBHelper.java:631)
        ... 24 more
</code>```

答:
So, The problem happens because weblogic.jar contains a version of antlr.jar which is loaded by a classloader, while the hibernate stuff are loaded by another classloader. So when the server runs it’s using the version of antlr bundled with weblogic which cannot see the hibernate classes.

I follow this solution and all become OK: https://thejavablog.wordpress.com/tag/antlr/

Body:
SO... I'm receiving strange WARNs from a application in JBoss-EAP 7 / Wildfly 10:

[Server:teste] INFO  2017-02-15 13:52:02,669 [jacorb.orb] Initialising ORB with ID:
[Server:teste] WARN  2017-02-15 13:52:02,701 [jacorb.orb] unable to build ORBInitializer from class true: Ignoring
[Server:teste] INFO  2017-02-15 13:52:02,750 [orb.interceptors] InterceptorManager started with 0 Server Interceptors, 0 Client Interceptors and 1 IOR Interceptors

This app have ten years and need the CORBA libs to use a JMS Queue.

Should I worry?
What this WARNING mean?

[EDITED]

Additional logs popout out now:

javax.naming.InvalidNameException: Couldn't resolve initial reference: NameService [Root exception is org.omg.CORBA.ORBPackage.InvalidName: IDL:omg.org/CORBA/ORB/InvalidName:1.0]
        at weblogic.corba.j2ee.naming.Utils.wrapNamingException(Utils.java:52)
        at weblogic.corba.j2ee.naming.ORBHelper.getORBReferenceWithRetry(ORBHelper.java:644)
        at weblogic.corba.j2ee.naming.ORBHelper.getORBReference(ORBHelper.java:594)
        at weblogic.corba.j2ee.naming.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:85)
        at weblogic.corba.j2ee.naming.InitialContextFactoryImpl.getInitialContext(InitialContextFactoryImpl.java:31)
        at weblogic.jndi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:46)
        at org.jboss.as.naming.InitialContext.getDefaultInitCtx(InitialContext.java:114)
        at org.jboss.as.naming.InitialContext.init(InitialContext.java:99)
        at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154)
        at org.jboss.as.naming.InitialContext.<init>(InitialContext.java:89)
        at org.jboss.as.naming.InitialContextFactory.getInitialContext(InitialContextFactory.java:43)
        at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684)
        at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
        at javax.naming.InitialContext.init(InitialContext.java:244)
        at javax.naming.InitialContext.<init>(InitialContext.java:216)
        at com.alu.feeder.tasks.ExpediterRfbNotificationConsumerTask.executarProcesso(ExpediterRfbNotificationConsumerTask.java:88)
        at com.alu.feeder.tasks.ExpediterRfbNotificationConsumerTask.run(ExpediterRfbNotificationConsumerTask.java:51)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.util.MethodInvoker.invoke(MethodInvoker.java:273)
        at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean$MethodInvokingJob.executeInternal(MethodInvokingJobDetailFactoryBean.java:260)
        at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:86)
        at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
        at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: org.omg.CORBA.ORBPackage.InvalidName: IDL:omg.org/CORBA/ORB/InvalidName:1.0
        at org.jacorb.orb.ORB.resolve_initial_references(ORB.java:1609)
        at weblogic.corba.j2ee.naming.ORBHelper.getORBReferenceWithRetry(ORBHelper.java:631)
        ... 24 more