问:
if constructor crashes from call to std::make_shared, can gdb show details of crash
In below code, I am calling make_shared<MyClass>, and the constructor of MyClass throws exception. If the core file is available, is it possible to find out the origin of crash [e.g: whether crash was from foo() or fun()] with the help of gdb?

```<code>#include <iostream>
#include <memory>
using namespace std;

class MyClass
{
    public:
        MyClass()
        {
            foo();
            fun();
        }

        ~MyClass() { }

        void foo()
        {
            throw("error 1");
        }
        void fun()
        {
            throw("error 2");
        }
};

shared_ptr<MyClass> createMyClass()
{
    return make_shared<MyClass>();
}

int main()
{
    shared_ptr<MyClass> c = createMyClass();
    return 0;
}
</code>```

backtrace just points to this line:

```<code> 29     return make_shared<MyClass>();
</code>```

backtrace:

```<code>Program received signal SIGABRT, Aborted.
0x00007ffff722d5f7 in raise () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-106.el7_2.6.x86_64 libgcc-4.8.5-4.el7.x86_64 libstdc++-4.8.5-4.el7.x86_64

    (gdb) bt
    #0  0x00007ffff722d5f7 in raise () from /lib64/libc.so.6
    #1  0x00007ffff722ece8 in abort () from /lib64/libc.so.6
    #2  0x00007ffff7b329d5 in __gnu_cxx::__verbose_terminate_handler() () from /lib64/libstdc++.so.6
    #3  0x00007ffff7b30946 in ?? () from /lib64/libstdc++.so.6
    #4  0x00007ffff7b30973 in std::terminate() () from /lib64/libstdc++.so.6
    #5  0x00007ffff7b30be9 in __cxa_rethrow () from /lib64/libstdc++.so.6
    #6  0x000000000040121e in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::__shared_count<MyClass, std::allocator<MyClass>>(std::_Sp_make_shared_tag, MyClass*, std::allocator<MyClass> const&) (this=0x7fffffffe178, __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:509
    #7  0x00000000004010ba in std::__shared_ptr<MyClass, (__gnu_cxx::_Lock_policy)2>::__shared_ptr<std::allocator<MyClass>>(std::_Sp_make_shared_tag, std::allocator<MyClass> const&) (this=0x7fffffffe170, __tag=..., __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:957
    #8  0x0000000000401052 in std::shared_ptr<MyClass>::shared_ptr<std::allocator<MyClass>>(std::_Sp_make_shared_tag, std::allocator<MyClass> const&) (this=0x7fffffffe170,
        __tag=..., __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr.h:316
    #9  0x0000000000400f98 in std::allocate_shared<MyClass, std::allocator<MyClass>>(std::allocator<MyClass> const&) (__a=...) at /usr/include/c++/4.8.2/bits/shared_ptr.h:598
    #10 0x0000000000400ee0 in std::make_shared<MyClass<> > () at /usr/include/c++/4.8.2/bits/shared_ptr.h:614
    #11 0x0000000000400ce3 in createMyClass () at abrt.cpp:29
    #12 0x0000000000400cfe in main () at abrt.cpp:34
    (gdb) q
</code>```

答: That information is lost by the time the core file is generated. The reason is that the shared_ptr constructor has to catch any exceptions from the object constructor in order to be able to deallocate the memory it allocated earlier (to prevent leaks induced by constructors that throw). By the time it catches the exception to deallocate the memory it no longer knows where in the constructor the exception was thrown.

Body:
In below code, I am calling make_shared<MyClass>, and the constructor of MyClass throws exception. If the core file is available, is it possible to find out the origin of crash [e.g: whether crash was from foo() or fun()] with the help of gdb?

#include <iostream>
#include <memory>
using namespace std;

class MyClass
{
    public:
        MyClass()
        {
            foo();
            fun();
        }

        ~MyClass() { }

        void foo()
        {
            throw("error 1");
        }
        void fun()
        {
            throw("error 2");
        }
};

shared_ptr<MyClass> createMyClass()
{
    return make_shared<MyClass>();
}

int main()
{
    shared_ptr<MyClass> c = createMyClass();
    return 0;
}

backtrace just points to this line:

 29     return make_shared<MyClass>();

backtrace:

Program received signal SIGABRT, Aborted.
0x00007ffff722d5f7 in raise () from /lib64/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.17-106.el7_2.6.x86_64 libgcc-4.8.5-4.el7.x86_64 libstdc++-4.8.5-4.el7.x86_64

    (gdb) bt
    #0  0x00007ffff722d5f7 in raise () from /lib64/libc.so.6
    #1  0x00007ffff722ece8 in abort () from /lib64/libc.so.6
    #2  0x00007ffff7b329d5 in __gnu_cxx::__verbose_terminate_handler() () from /lib64/libstdc++.so.6
    #3  0x00007ffff7b30946 in ?? () from /lib64/libstdc++.so.6
    #4  0x00007ffff7b30973 in std::terminate() () from /lib64/libstdc++.so.6
    #5  0x00007ffff7b30be9 in __cxa_rethrow () from /lib64/libstdc++.so.6
    #6  0x000000000040121e in std::__shared_count<(__gnu_cxx::_Lock_policy)2>::__shared_count<MyClass, std::allocator<MyClass>>(std::_Sp_make_shared_tag, MyClass*, std::allocator<MyClass> const&) (this=0x7fffffffe178, __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:509
    #7  0x00000000004010ba in std::__shared_ptr<MyClass, (__gnu_cxx::_Lock_policy)2>::__shared_ptr<std::allocator<MyClass>>(std::_Sp_make_shared_tag, std::allocator<MyClass> const&) (this=0x7fffffffe170, __tag=..., __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr_base.h:957
    #8  0x0000000000401052 in std::shared_ptr<MyClass>::shared_ptr<std::allocator<MyClass>>(std::_Sp_make_shared_tag, std::allocator<MyClass> const&) (this=0x7fffffffe170,
        __tag=..., __a=...) at /usr/include/c++/4.8.2/bits/shared_ptr.h:316
    #9  0x0000000000400f98 in std::allocate_shared<MyClass, std::allocator<MyClass>>(std::allocator<MyClass> const&) (__a=...) at /usr/include/c++/4.8.2/bits/shared_ptr.h:598
    #10 0x0000000000400ee0 in std::make_shared<MyClass<> > () at /usr/include/c++/4.8.2/bits/shared_ptr.h:614
    #11 0x0000000000400ce3 in createMyClass () at abrt.cpp:29
    #12 0x0000000000400cfe in main () at abrt.cpp:34
    (gdb) q


来源: stackexchange

问:
How to convert response to another type before it handled by MessageConverter in Spring MVC
For example, here's a method which returns a User:

```<code>@RequestMapping(method = GET, value = "/user")
public User getUser() {
    return new Users();
}
</code>```

For some reasons, the client expect an other type

```<code>class CommonResponse<T> {
  int code;
  T data;
}
</code>```

So I need to convert all return value from T(User for this e.g.) to CommonResponse<T> before it handled by the MessageConverter.

Cause there're many request hanlders should be modified, is there any way to write the convert data just once?

答:
Finally I find ResponseBodyAdvice to do such work.

Here the sample code:

```<code>@RestControllerAdvice
public class CommonAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getDeclaringClass().getPackage().getName().startsWith("foo.bar.demo");
        // you can change here to your logic
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return new CommonResponse<Object>().setCode(200).setData(body);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example, here's a method which returns a User:

@RequestMapping(method = GET, value = "/user")
public User getUser() {
    return new Users();
}

For some reasons, the client expect an other type

class CommonResponse<T> {
  int code;
  T data;
}

So I need to convert all return value from T(User for this e.g.) to CommonResponse<T> before it handled by the MessageConverter.

Cause there're many request hanlders should be modified, is there any way to write the convert data just once?

Body:
Finally I find ResponseBodyAdvice to do such work.

Here the sample code:

@RestControllerAdvice
public class CommonAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getDeclaringClass().getPackage().getName().startsWith("foo.bar.demo");
        // you can change here to your logic
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return new CommonResponse<Object>().setCode(200).setData(body);
    }
}


问:
WS eb init missing equal-sign error
I ran and configure the key and the rest with aws configure

But when I run eb init I got the error

ERROR: 'init/20160618/us-west-2/elasticbeanstalk/aws4_request' not a valid key=value pair (missing equal-sign) in Authorization header: 'AWS4-HMAC-SHA256 Credential=eb init/20160618/us-west-2/elasticbeanstalk/aws4_request, SignedHeaders=host;x-amz-date, Signature=95e3...56e4'.

Awsebcli and Python should be set up correctly with version EB CLI 3.7.6 (Python 2.7.1). Can someone help me figure out why?

答: You have to remove or edit the file config on the occult directory named .aws, this directory usually is in C:/User/{Your user}/.aws or unix /User/{Your user}/.aws

Title: WS eb init missing equal-sign error

ContentLicense: CC BY-SA 4.0


问:
Spring CSRF token does not work, when the request to be sent is a multipart request
I use,

Spring Framework 4.0.0 RELEASE (GA)

Spring Security 3.2.0 RELEASE (GA)

Struts 2.3.16

In which, I use an in-built security token to guard against CSRF attacks.

The Struts form looks like the following.

```<code><s:form namespace="/admin_side"
        action="Category"
        enctype="multipart/form-data"
        method="POST"
        validate="true"
        id="dataForm"
        name="dataForm">

    <s:hidden name="%{#attr._csrf.parameterName}"
              value="%{#attr._csrf.token}"/>
</s:form>
</code>```

The generated HTML code is as follows.

```<code><form id="dataForm"
      name="dataForm"
      action="/TestStruts/admin_side/Category.action"
      method="POST"
      enctype="multipart/form-data">

    <input type="hidden"
           name="_csrf"
           value="3748c228-85c6-4c3f-accf-b17d1efba1c5"
           id="dataForm__csrf">
</form>
</code>```

This works fine, unless the request is multipart in which case, the request ends with the status code 403.

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request
  parameter '_csrf' or header 'X-CSRF-TOKEN'.

type Status report

message Invalid CSRF Token 'null' was found on the request parameter
  '_csrf' or header 'X-CSRF-TOKEN'.

description Access to the specified resource has been forbidden.

The spring-security.xml file is as follows.

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="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-4.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http pattern="/Login.jsp*" security="none"></http>

    <http auto-config='true' use-expressions="true" disable-url-rewriting="true" authentication-manager-ref="authenticationManager">
        <session-management session-fixation-protection="newSession">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>

        <csrf/>

        <headers>
            <xss-protection />
            <frame-options />
            <!--<cache-control />-->
            <!--<hsts />-->
            <content-type-options /> <!--content sniffing-->
        </headers>

        <intercept-url pattern="/admin_side/**" access="hasRole('ROLE_ADMIN')" requires-channel="any"/>
        <form-login login-page="/admin_login/Login.action" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-handler-ref="authenticationFailureHandler"/>
        <logout logout-success-url="/admin_login/Login.action" invalidate-session="true" delete-cookies="JSESSIONID"/>
    </http>

    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

    <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="userDetailsService"/>
        <beans:property name="passwordEncoder" ref="encoder" />
    </beans:bean>

    <beans:bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
        <beans:property name="providers">
            <beans:list>
                <beans:ref bean="daoAuthenticationProvider" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="loginSuccessHandler" class="loginsuccesshandler.LoginSuccessHandler"/>
    <beans:bean id="authenticationFailureHandler" class="loginsuccesshandler.AuthenticationFailureHandler" />

    <global-method-security secured-annotations="enabled" proxy-target-class="false" authentication-manager-ref="authenticationManager">
        <protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
    </global-method-security>
</beans:beans>
</code>```

So, where to look for this token, when a request is multipart? (This should not be related to Struts at all.)

The implementation of UserDetailsService can be found in this earlier question of mine, if needed.

Placing MultipartFilter before Spring Security did not help either.

The web.xml file looks like the following.

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
         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_3_0.xsd">

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

    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <servlet-name>/*</servlet-name>
    </filter-mapping>

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

    <filter>
        <filter-name>AdminLoginNocacheFilter</filter-name>
        <filter-class>filter.AdminLoginNocacheFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>AdminLoginNocacheFilter</filter-name>
        <url-pattern>/admin_login/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>NoCacheFilter</filter-name>
        <filter-class>filter.NoCacheFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>NoCacheFilter</filter-name>
        <url-pattern>/admin_side/*</url-pattern>
    </filter-mapping>

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

    <listener>
        <description>Description</description>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>struts.devMode</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
</code>```

It only works, when the token is appended as a query-string parameter as follows which is however, discouraged.

```<code><s:form namespace="/admin_side"
        action="Category?%{#attr._csrf.parameterName}=%{#attr._csrf.token}"
        enctype="multipart/form-data"
        method="POST"
        validate="true"
        id="dataForm"
        name="dataForm">
    ...
<s:form>
</code>```

答:
I solved this problem by:

sending the multi-part file using vanilla javascript, like in Mozilla's guide

adding the _csrf token in the HTML header, in meta tags, like in the Spring guideline for sending the CSRF token with Ajax

instead of using jquery, adding it directly to the XHR object

```<code>var csrfToken = $("meta[name='_csrf']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
XHR.setRequestHeader(csrfHeader, csrfToken);
XHR.setRequestHeader('Content-Type','multipart/form-data; boundary=' + boundary);

XHR.send(data);
</code>```

Body:
I use,

Spring Framework 4.0.0 RELEASE (GA)

Spring Security 3.2.0 RELEASE (GA)

Struts 2.3.16

In which, I use an in-built security token to guard against CSRF attacks.

The Struts form looks like the following.

<s:form namespace="/admin_side"
        action="Category"
        enctype="multipart/form-data"
        method="POST"
        validate="true"
        id="dataForm"
        name="dataForm">

    <s:hidden name="%{#attr._csrf.parameterName}"
              value="%{#attr._csrf.token}"/>
</s:form>

The generated HTML code is as follows.

<form id="dataForm"
      name="dataForm"
      action="/TestStruts/admin_side/Category.action"
      method="POST"
      enctype="multipart/form-data">

    <input type="hidden"
           name="_csrf"
           value="3748c228-85c6-4c3f-accf-b17d1efba1c5"
           id="dataForm__csrf">
</form>

This works fine, unless the request is multipart in which case, the request ends with the status code 403.

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request
  parameter '_csrf' or header 'X-CSRF-TOKEN'.

type Status report

message Invalid CSRF Token 'null' was found on the request parameter
  '_csrf' or header 'X-CSRF-TOKEN'.

description Access to the specified resource has been forbidden.

The spring-security.xml file is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="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-4.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http pattern="/Login.jsp*" security="none"></http>

    <http auto-config='true' use-expressions="true" disable-url-rewriting="true" authentication-manager-ref="authenticationManager">
        <session-management session-fixation-protection="newSession">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>

        <csrf/>

        <headers>
            <xss-protection />
            <frame-options />

            <content-type-options />
        </headers>

        <intercept-url pattern="/admin_side/**" access="hasRole('ROLE_ADMIN')" requires-channel="any"/>
        <form-login login-page="/admin_login/Login.action" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-handler-ref="authenticationFailureHandler"/>
        <logout logout-success-url="/admin_login/Login.action" invalidate-session="true" delete-cookies="JSESSIONID"/>
    </http>

    <beans:bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

    <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="userDetailsService"/>
        <beans:property name="passwordEncoder" ref="encoder" />
    </beans:bean>

    <beans:bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
        <beans:property name="providers">
            <beans:list>
                <beans:ref bean="daoAuthenticationProvider" />
            </beans:list>
        </beans:property>
    </beans:bean>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="loginSuccessHandler" class="loginsuccesshandler.LoginSuccessHandler"/>
    <beans:bean id="authenticationFailureHandler" class="loginsuccesshandler.AuthenticationFailureHandler" />

    <global-method-security secured-annotations="enabled" proxy-target-class="false" authentication-manager-ref="authenticationManager">
        <protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
    </global-method-security>
</beans:beans>

So, where to look for this token, when a request is multipart? (This should not be related to Struts at all.)

The implementation of UserDetailsService can be found in this earlier question of mine, if needed.

Placing MultipartFilter before Spring Security did not help either.

The web.xml file looks like the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
         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_3_0.xsd">

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

    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <servlet-name>/*</servlet-name>
    </filter-mapping>

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

    <filter>
        <filter-name>AdminLoginNocacheFilter</filter-name>
        <filter-class>filter.AdminLoginNocacheFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>AdminLoginNocacheFilter</filter-name>
        <url-pattern>/admin_login/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>NoCacheFilter</filter-name>
        <filter-class>filter.NoCacheFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>NoCacheFilter</filter-name>
        <url-pattern>/admin_side/*</url-pattern>
    </filter-mapping>

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

    <listener>
        <description>Description</description>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>struts.devMode</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

It only works, when the token is appended as a query-string parameter as follows which is however, discouraged.

<s:form namespace="/admin_side"
        action="Category?%{#attr._csrf.parameterName}=%{#attr._csrf.token}"
        enctype="multipart/form-data"
        method="POST"
        validate="true"
        id="dataForm"
        name="dataForm">
    ...
<s:form>

Body:
I solved this problem by:

sending the multi-part file using vanilla javascript, like in Mozilla's guide

adding the _csrf token in the HTML header, in meta tags, like in the Spring guideline for sending the CSRF token with Ajax

instead of using jquery, adding it directly to the XHR object

var csrfToken = $("meta[name='_csrf']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
XHR.setRequestHeader(csrfHeader, csrfToken);
XHR.setRequestHeader('Content-Type','multipart/form-data; boundary=' + boundary);

XHR.send(data);


问:
Search file for zip code in bash grep/sed
Trying to find each line containing a zip code using sed/grep
can't figure out what im missing, and cant find anything like what i am after.

zip code is 4 digits.

答:
Try egrep "[0-9]{4}" .

The [0-9] part matches any character between '0' or '9' (that is, the  numeric characters).

The {4} part states that the previous rule should happen fout times in a row. (That is, numeric-numeric-numeric-numeric).

egrep is the grep version that supports regular expressions.


问:
Karma jasmine Angular 1.6.2 testing filter throws error Uncaught Error: [$injector:unpr]
I am working on testing my AngularJS code, and I am having a problem that all the answers I could find wouldn't fix.
I am trying to test a filter that looks like this:

```<code>app.filter('capitalize', function(){
    return function(val){
        if( val && typeof val === 'string'){
            return val.charAt(0).toUpperCase() + val.substr(1).replace('_', ' ');
        }
    };
});
</code>```

my app is defined as :

```<code>var app = angular.module('myApp', ["ui.router", "ui.bootstrap", "ngSanitize", "pascalprecht.translate", "angular-google-analytics",
"ngStorage", "jsonFormatter", "selectize", "toaster"]);
</code>```

My test looks like:

```<code>describe('Filters Unit Test Suite:', function() {
    beforeEach(function() {
        angular.mock.module('myApp');
    });

    describe('capitalize filter', function() {
        var capitalizeFilter;
        beforeEach(inject(function(_$filter_) {
            capitalizeFilter = _$filter('capitalize');
        }));

        it('should capitalize the first letter of a string', function() {
            expect(capitalizeFilter('hello')).toEqual('Hello');
        });
    });
});
</code>```

Every piece of code here is pulled from a different file, namely filters.js, app.js, and fitler.test.js respectively.
I used these documentations here and the official AngularJs testing page here.

I already tested almost all the response similar to question like this asked here, but none seems to be working.

Your help will be greatly appreciated.

I might have skipped a response, if you think so, please add the link in comment.
I have spend almost three days looking, searching here on stackoverflow for the reason why, and to find how to correct that. That is too much of my time I already lost, and I feel like I am to close to this to see what I am missing, that's why I seek your help.

Thank you.

Just in case, here is how I put the files in my karma config file:

```<code>  files:[

  'src/main/resources/assets/bower_components/angular/angular.js',
   'src/main/resources/assets/bower_components/angular-ui-router/release/angular-ui-router.js',
   'src/main/resources/assets/bower_components/ngstorage/ngStorage.js',
   'src/main/resources/assets/bower_components/angular-mocks/angular-mocks.js',
  'src/main/resources/assets/bower_components/jquery/dist/jquery.min.js',
  'src/main/resources/assets/bower_components/bootstrap/dist/js/bootstrap.min.js',
  'src/main/resources/assets/js/vendor/ui-bootstrap-tpls-1.2.4.min.js',
  'src/main/resources/assets/bower_components/angular-sanitize/angular-sanitize.js',
  'src/main/resources/assets/bower_components/highcharts/highcharts.js',
  'src/main/resources/assets/bower_components/highcharts/highcharts-more.js',
  'src/main/resources/assets/bower_components/angular-translate/angular-translate.js',
  'src/main/resources/assets/bower_components/moment/min/moment.min.js',
  'src/main/resources/assets/bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
  'src/main/resources/assets/bower_components/angular-google-analytics/dist/angular-google-analytics.min.js',
  'src/main/resources/assets/bower_components/json-formatter/dist/json-formatter.js',
  'src/main/resources/assets/bower_components/selectize/dist/js/standalone/selectize.js',
  'src/main/resources/assets/bower_components/angular-selectize2/dist/angular-selectize.js',
  'src/main/resources/assets/bower_components/AngularJS-Toaster/toaster.min.js',

  'src/main/resources/assets/js/angular/app.js',
  'src/main/resources/assets/js/angular/filters.js',
  'src/test/resources/assets/js/angular/filters.test.js'
]
</code>```

答:
The error I got on running your code is this:

Here is the working fiddle.

I believe you had not added the angular-ui library to it. I added the library and it works fine. Add the following link and try your code again.

```<code>http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js
</code>```

Body:
I am working on testing my AngularJS code, and I am having a problem that all the answers I could find wouldn't fix.
I am trying to test a filter that looks like this:

app.filter('capitalize', function(){
    return function(val){
        if( val && typeof val === 'string'){
            return val.charAt(0).toUpperCase() + val.substr(1).replace('_', ' ');
        }
    };
});

my app is defined as :

var app = angular.module('myApp', ["ui.router", "ui.bootstrap", "ngSanitize", "pascalprecht.translate", "angular-google-analytics",
"ngStorage", "jsonFormatter", "selectize", "toaster"]);

My test looks like:

describe('Filters Unit Test Suite:', function() {
    beforeEach(function() {
        angular.mock.module('myApp');
    });

    describe('capitalize filter', function() {
        var capitalizeFilter;
        beforeEach(inject(function(_$filter_) {
            capitalizeFilter = _$filter('capitalize');
        }));

        it('should capitalize the first letter of a string', function() {
            expect(capitalizeFilter('hello')).toEqual('Hello');
        });
    });
});

Every piece of code here is pulled from a different file, namely filters.js, app.js, and fitler.test.js respectively.
I used these documentations here and the official AngularJs testing page here.

I already tested almost all the response similar to question like this asked here, but none seems to be working.

Your help will be greatly appreciated.

I might have skipped a response, if you think so, please add the link in comment.
I have spend almost three days looking, searching here on stackoverflow for the reason why, and to find how to correct that. That is too much of my time I already lost, and I feel like I am to close to this to see what I am missing, that's why I seek your help.

Thank you.

Just in case, here is how I put the files in my karma config file:

  files:[

  'src/main/resources/assets/bower_components/angular/angular.js',
   'src/main/resources/assets/bower_components/angular-ui-router/release/angular-ui-router.js',
   'src/main/resources/assets/bower_components/ngstorage/ngStorage.js',
   'src/main/resources/assets/bower_components/angular-mocks/angular-mocks.js',
  'src/main/resources/assets/bower_components/jquery/dist/jquery.min.js',
  'src/main/resources/assets/bower_components/bootstrap/dist/js/bootstrap.min.js',
  'src/main/resources/assets/js/vendor/ui-bootstrap-tpls-1.2.4.min.js',
  'src/main/resources/assets/bower_components/angular-sanitize/angular-sanitize.js',
  'src/main/resources/assets/bower_components/highcharts/highcharts.js',
  'src/main/resources/assets/bower_components/highcharts/highcharts-more.js',
  'src/main/resources/assets/bower_components/angular-translate/angular-translate.js',
  'src/main/resources/assets/bower_components/moment/min/moment.min.js',
  'src/main/resources/assets/bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
  'src/main/resources/assets/bower_components/angular-google-analytics/dist/angular-google-analytics.min.js',
  'src/main/resources/assets/bower_components/json-formatter/dist/json-formatter.js',
  'src/main/resources/assets/bower_components/selectize/dist/js/standalone/selectize.js',
  'src/main/resources/assets/bower_components/angular-selectize2/dist/angular-selectize.js',
  'src/main/resources/assets/bower_components/AngularJS-Toaster/toaster.min.js',

  'src/main/resources/assets/js/angular/app.js',
  'src/main/resources/assets/js/angular/filters.js',
  'src/test/resources/assets/js/angular/filters.test.js'
]

Body:
The error I got on running your code is this:

Here is the working fiddle.

I believe you had not added the angular-ui library to it. I added the library and it works fine. Add the following link and try your code again.

http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js


问:
Textbox placeholder translations WPF XAML
I have this XAML code that creates a txtbox with a placeholder text, that appears and disapears if it's focused or not.

But right now, I need to translate the aplication to 2 languages with a button. That button simply sets a global variable to "EN" for english and "ES" for spanish.

How can I adapte the code, so depending on that variable (written in code behind) the text "Please, write the reason for your request" changes?

This is the code working right now:

```<code><TextBox x:Name="txt_reasons" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalAlignment="Left" Height="74" Margin="82,247,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="344" TabIndex="4" MaxLength="150" TextChanged="txt_reasons_TextChanged" IsEnabled="False" IsHitTestVisible="True">
    <TextBox.Style>
        <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
            <Style.Resources>
                <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Top" Stretch="None">
                    <VisualBrush.Visual>
                        <Label Content="Please, write the reason for your request" Foreground="Gray" ClipToBounds="True" />
                    </VisualBrush.Visual>
                </VisualBrush>
            </Style.Resources>
            <Style.Triggers>
                <Trigger Property="Text" Value="{x:Static sys:String.Empty}">
                    <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                </Trigger>
                <Trigger Property="Text" Value="{x:Null}">
                    <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                </Trigger>
                <Trigger Property="IsKeyboardFocused" Value="True">
                    <Setter Property="Background" Value="White" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>
</code>```

答:
You could use a Label Style with a DataTrigger that binds to the window property.

Please refer to the following sample code.

XAML:

```<code><Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300" x:Name="win">
    <StackPanel>
        <TextBox x:Name="txt_reasons" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalAlignment="Left" Height="74" TextWrapping="Wrap" VerticalAlignment="Top" Width="344" TabIndex="4" MaxLength="150">
            <TextBox.Style>
                <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
                    <Style.Resources>
                        <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Top" Stretch="None">
                            <VisualBrush.Visual>
                                <Label Foreground="Gray" ClipToBounds="True">
                                    <Label.Style>
                                        <Style TargetType="Label">
                                            <Setter Property="Content" Value="Please, write the reason for your request"/>
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding TheLanguage, Source={x:Reference win}}" Value="ES">
                                                    <Setter Property="Content" Value="spanish..."/>
                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </Label.Style>
                                </Label>
                            </VisualBrush.Visual>
                        </VisualBrush>
                    </Style.Resources>
                    <Style.Triggers>
                        <Trigger Property="Text" Value="{x:Static sys:String.Empty}">
                            <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                        </Trigger>
                        <Trigger Property="Text" Value="{x:Null}">
                            <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                        </Trigger>
                        <Trigger Property="IsKeyboardFocused" Value="True">
                            <Setter Property="Background" Value="White" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

        <Button Content="Toggle Language" Click="Button_Click" />
    </StackPanel>
</Window>
</code>```

Code:

```<code>public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private string _language = "EN";
    public string TheLanguage
    {
        get { return _language; }
        set { _language = value; NotifyPropertyChanged(); }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        TheLanguage = TheLanguage == "EN" ? "ES" : "EN";
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Note that the window class must implement the INotifyPropertyChanged interface and raise the PropertyChanged event whenever the source property is set to a new value for the Label to get updated.

Body:
I have this XAML code that creates a txtbox with a placeholder text, that appears and disapears if it's focused or not.

But right now, I need to translate the aplication to 2 languages with a button. That button simply sets a global variable to "EN" for english and "ES" for spanish.

How can I adapte the code, so depending on that variable (written in code behind) the text "Please, write the reason for your request" changes?

This is the code working right now:

<TextBox x:Name="txt_reasons" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalAlignment="Left" Height="74" Margin="82,247,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="344" TabIndex="4" MaxLength="150" TextChanged="txt_reasons_TextChanged" IsEnabled="False" IsHitTestVisible="True">
    <TextBox.Style>

        </Style>
    </TextBox.Style>
</TextBox>

Body:
You could use a Label Style with a DataTrigger that binds to the window property.

Please refer to the following sample code.

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300" x:Name="win">
    <StackPanel>
        <TextBox x:Name="txt_reasons" ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalAlignment="Left" Height="74" TextWrapping="Wrap" VerticalAlignment="Top" Width="344" TabIndex="4" MaxLength="150">
            <TextBox.Style>
                <Style TargetType="TextBox" xmlns:sys="clr-namespace:System;assembly=mscorlib">
                    <Style.Resources>
                        <VisualBrush x:Key="CueBannerBrush" AlignmentX="Left" AlignmentY="Top" Stretch="None">
                            <VisualBrush.Visual>
                                <Label Foreground="Gray" ClipToBounds="True">
                                    <Label.Style>
                                        <Style TargetType="Label">
                                            <Setter Property="Content" Value="Please, write the reason for your request"/>
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding TheLanguage, Source={x:Reference win}}" Value="ES">
                                                    <Setter Property="Content" Value="spanish..."/>
                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </Label.Style>
                                </Label>
                            </VisualBrush.Visual>
                        </VisualBrush>
                    </Style.Resources>
                    <Style.Triggers>
                        <Trigger Property="Text" Value="{x:Static sys:String.Empty}">
                            <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                        </Trigger>
                        <Trigger Property="Text" Value="{x:Null}">
                            <Setter Property="Background" Value="{StaticResource CueBannerBrush}" />
                        </Trigger>
                        <Trigger Property="IsKeyboardFocused" Value="True">
                            <Setter Property="Background" Value="White" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBox.Style>
        </TextBox>

        <Button Content="Toggle Language" Click="Button_Click" />
    </StackPanel>
</Window>

Code:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private string _language = "EN";
    public string TheLanguage
    {
        get { return _language; }
        set { _language = value; NotifyPropertyChanged(); }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        TheLanguage = TheLanguage == "EN" ? "ES" : "EN";
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Note that the window class must implement the INotifyPropertyChanged interface and raise the PropertyChanged event whenever the source property is set to a new value for the Label to get updated.


问:
Does the order of fields in C# matter?
This question is inspired by Jon Skeet's answer:
Is there a c# equivalent to c++'s access-modifier regions

He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion.

Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?

答:
Here is a classic example from the C# language spec (Section 10.5.5)

```<code>class Test
{
    static int a = b + 1;
    static int b = a + 1;
    static void Main() {
        Console.WriteLine("a = {0}, b = {1}", a, b);
    }
}
</code>```

This is a completely valid program and as written (a = 1, b =2).  However if you swap the ordering of the fields they will also swap values.

OwnerDisplayName: Josh

ContentLicense: CC BY-SA 2.5

Title: Does the order of fields in C# matter?

LastEditorDisplayName: Mehrdad Afshari

Body:
Here is a classic example from the C# language spec (Section 10.5.5)

class Test
{
    static int a = b + 1;
    static int b = a + 1;
    static void Main() {
        Console.WriteLine("a = {0}, b = {1}", a, b);
    }
}

This is a completely valid program and as written (a = 1, b =2).  However if you swap the ordering of the fields they will also swap values.

OwnerDisplayName: JaredPar


问:
To access tinymce iframe elements through jquery
I an using Tinymce Editor. In need to access tinymce iframe with jquery
I had tried...

```<code>var iframe = $('#comment_ifr')[0];//document.getElementById('comment_ifr');// or $('#comment_ifr')[0]; the other is just faster.
alert(iframe);
var doc = iframe.document || iframe.contentDocument || iframe.contentWindow && iframe.contentWindow.document || null;
   //if( !doc ) return;
   //and now jquery

$( "img", doc ).click(function() {
    alert('image clicked');
   });

----------
</code>```

In my above code once an image inserted in tinymce iframe. Once i click that image i need to trigger an event. Help me.

答:
You can get easier to the iframes document by using:

```<code>var doc = tinymce.get('comment').getDoc();
</code>```

EDIT:  To achieve what you want you can catch the click event inside tinymce and do what you wish with it.
You need to insert this code into an own tinymce plugin or use the tinymce init paramater:

```<code>ed.onClick.add(function(ed, evt){

    // Firefox
    if (evt.explicitOriginalTarget){ // this is the img-element
      if (evt.explicitOriginalTarget.nodeName.toLowerCase() == 'img'){
        console.log(evt.explicitOriginalTarget);
        alert('image clicked');
      }
    }
    // IE
    else if (evt.target) { // this is the img-element
      if (evt.target.nodeName.toLowerCase() == 'img'){
        console.log(evt.target);
        alert('image clicked');
      }
    }
}); // end click event
</code>```

Body:
I an using Tinymce Editor. In need to access tinymce iframe with jquery
I had tried...

var iframe = $('#comment_ifr')[0];//document.getElementById('comment_ifr');// or $('#comment_ifr')[0]; the other is just faster.
alert(iframe);
var doc = iframe.document || iframe.contentDocument || iframe.contentWindow && iframe.contentWindow.document || null;
   //if( !doc ) return;
   //and now jquery

$( "img", doc ).click(function() {
    alert('image clicked');
   });

----------

In my above code once an image inserted in tinymce iframe. Once i click that image i need to trigger an event. Help me.

Body:
You can get easier to the iframes document by using:

var doc = tinymce.get('comment').getDoc();

EDIT:  To achieve what you want you can catch the click event inside tinymce and do what you wish with it.
You need to insert this code into an own tinymce plugin or use the tinymce init paramater:

ed.onClick.add(function(ed, evt){

    // Firefox
    if (evt.explicitOriginalTarget){ // this is the img-element
      if (evt.explicitOriginalTarget.nodeName.toLowerCase() == 'img'){
        console.log(evt.explicitOriginalTarget);
        alert('image clicked');
      }
    }
    // IE
    else if (evt.target) { // this is the img-element
      if (evt.target.nodeName.toLowerCase() == 'img'){
        console.log(evt.target);
        alert('image clicked');
      }
    }
}); // end click event


问:
Get line number of beginning and end of Ruby method given a ruby file
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

```<code>1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end
</code>```

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

答:
Finding the end is tricky. The best way I can think of is to use the parser gem. Basically you'll parse the Ruby code into an AST, then recursively traverse its nodes until you find a node with type :def whose first child is :initialize:

```<code>require "parser/current"

def recursive_find(node, &block)
  return node if block.call(node)
  return nil unless node.respond_to?(:children) && !node.children.empty?
  node.children.each do |child_node|
    found = recursive_find(child_node, &block)
    return found if found
  end
  nil
end

src = <<END
  class Home
    def initialize(color)
      @color = color
    end
  end
END
ast = Parser::CurrentRuby.parse(src)

found = recursive_find(ast) do |node|
  node.respond_to?(:type) && node.type == :def && node.children[0] == :initialize
end

puts "Start: #{found.loc.first_line}"
puts "End: #{found.loc.last_line}"

# => Start: 2
#    End: 4
</code>```

P.S. I would have recommended the Ripper module from the standard library, but as far as I can tell there's no way to get the end line out of it.

Body:
How can I find the line of the beginning and end of a Ruby method given a ruby file?

Say for example:

1 class Home
2   def initialize(color)
3     @color = color
4   end
5 end

Given the file home.rb and the method name initialize I would like to receive (2,4) which are the beginning and end lines.

Body:
Finding the end is tricky. The best way I can think of is to use the parser gem. Basically you'll parse the Ruby code into an AST, then recursively traverse its nodes until you find a node with type :def whose first child is :initialize:

require "parser/current"

def recursive_find(node, &block)
  return node if block.call(node)
  return nil unless node.respond_to?(:children) && !node.children.empty?
  node.children.each do |child_node|
    found = recursive_find(child_node, &block)
    return found if found
  end
  nil
end

src = <<END
  class Home
    def initialize(color)
      @color = color
    end
  end
END
ast = Parser::CurrentRuby.parse(src)

found = recursive_find(ast) do |node|
  node.respond_to?(:type) && node.type == :def && node.children[0] == :initialize
end

puts "Start: #{found.loc.first_line}"
puts "End: #{found.loc.last_line}"

# => Start: 2
#    End: 4

P.S. I would have recommended the Ripper module from the standard library, but as far as I can tell there's no way to get the end line out of it.


问:
Vertex shader does not apply second attribute array
Consider a simple game with two classes of objects (ball and wall). Tutorials I've found suggests using a single vertex data array in the manner like:

[... initializing ...]

```<code>vdata = new float[ENOUGH_FOR_ALL];
vertexData = ByteBuffer.allocateDirect(vertices.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
aPositionLocation = glGetAttribLocation(programId, "a_Position");
glVertexAttribPointer(aPositionLocation, 2, GL_FLOAT, false, 0, vertexData);
glEnableVertexAttribArray(aPositionLocation);
</code>```

[...drawing...]

```<code>vertexData.position(0);
vertexData.put(vdata);
glUniform4f(uColorLocation, 1.0f, 0.0f, 0.0f, 1.0f); // ball is red
glDrawArrays(GL_TRIANGLE_FAN, 0, BALL_VERTICES + 2);
glUniform4f(uColorLocation, 0.0f, 1.0f, 0.0f, 1.0f); // wall is green
glDrawArrays(GL_LINES, BALL_VERTICES + 2, 2); // wall as a single line
</code>```

and, the vertex shader is trivial:

```<code>attribute vec4 a_Position;

void main() {
    gl_Position = a_Position;
}
</code>```

This works but requires cumbersome calculation of offsets in a single buffer, moving when some object size changes...

Consider the following vertex shader

```<code>attribute vec4 a_Ball;
attribute vec4 a_Wall;
uniform float u_WhatDraw;

void main() {
    if (u_WhatDraw == 1.0) {
        gl_Position = a_Ball;
    }
    else if (u_WhatDraw == 2.0) {
        gl_Position = a_Wall;
    }
}
</code>```

data prepared as:

```<code>ball_data = new float[BALL_VERTICES + 2];
wall_data = new float[4]; // a single line
ballVertexData = ByteBuffer.allocateDirect(ball_data.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
wallVertexData = ByteBuffer.allocateDirect(wall_data.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
aBallLocation = glGetAttribLocation(programId, "a_Ball");
glVertexAttribPointer(aBallLocation, 2, GL_FLOAT, false, 0, ballVertexData);
glEnableVertexAttribArray(aBallLocation);
aWallLocation = glGetAttribLocation(programId, "a_Wall");
glVertexAttribPointer(aWallLocation, 2, GL_FLOAT, false, 0, wallVertexData);
glEnableVertexAttribArray(aWallLocation);
</code>```

[...generation of static wall_data skipped...]

[...drawing...]

```<code>ballVertexData.position(0);
ballVertexData.put(ball_data);
glUniform4f(uColorLocation, 1.0f, 0.0f, 0.0f, 1.0f); // ball is red
glUniform1f(uWhatDrawLocation, 1.0f);
glDrawArrays(GL_TRIANGLE_FAN, 0, BALL_VERTICES + 2);
glUniform4f(uColorLocation, 0.0f, 1.0f, 0.0f, 1.0f); // wall is green
glUniform1f(uWhatDrawLocation, 2.0f);
glDrawArrays(GL_LINES, 0, 2); // wall as a single line
</code>```

This does not draw wall at all, despite the ball is drawn.

Please suggest in fixing this with 2-array approach or explain a limitation why I should stick with a single array for all activity.

答:
This works but requires cumbersome calculation of offsets in a single buffer, moving when some object size changes...

If object size changes you need to reupload new mesh data, so computing offsets seems to be the least of the problems.

or explain a limitation why I should stick with a single array for all activity.

What happens when you add a third object, or a fourth, or a fifth?

You're optimizing the wrong problem.

Any time you are required to generate shaders with if (<insert uniform>) ...  you're doing it wrong - never make the GPU make control plane decisions for every vertex when the application can just do it once.

Body:
Consider a simple game with two classes of objects (ball and wall). Tutorials I've found suggests using a single vertex data array in the manner like:

[... initializing ...]

vdata = new float[ENOUGH_FOR_ALL];
vertexData = ByteBuffer.allocateDirect(vertices.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
aPositionLocation = glGetAttribLocation(programId, "a_Position");
glVertexAttribPointer(aPositionLocation, 2, GL_FLOAT, false, 0, vertexData);
glEnableVertexAttribArray(aPositionLocation);

[...drawing...]

vertexData.position(0);
vertexData.put(vdata);
glUniform4f(uColorLocation, 1.0f, 0.0f, 0.0f, 1.0f); // ball is red
glDrawArrays(GL_TRIANGLE_FAN, 0, BALL_VERTICES + 2);
glUniform4f(uColorLocation, 0.0f, 1.0f, 0.0f, 1.0f); // wall is green
glDrawArrays(GL_LINES, BALL_VERTICES + 2, 2); // wall as a single line

and, the vertex shader is trivial:

attribute vec4 a_Position;

void main() {
    gl_Position = a_Position;
}

This works but requires cumbersome calculation of offsets in a single buffer, moving when some object size changes...

Consider the following vertex shader

attribute vec4 a_Ball;
attribute vec4 a_Wall;
uniform float u_WhatDraw;

void main() {
    if (u_WhatDraw == 1.0) {
        gl_Position = a_Ball;
    }
    else if (u_WhatDraw == 2.0) {
        gl_Position = a_Wall;
    }
}

data prepared as:

ball_data = new float[BALL_VERTICES + 2];
wall_data = new float[4]; // a single line
ballVertexData = ByteBuffer.allocateDirect(ball_data.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
wallVertexData = ByteBuffer.allocateDirect(wall_data.length * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();
aBallLocation = glGetAttribLocation(programId, "a_Ball");
glVertexAttribPointer(aBallLocation, 2, GL_FLOAT, false, 0, ballVertexData);
glEnableVertexAttribArray(aBallLocation);
aWallLocation = glGetAttribLocation(programId, "a_Wall");
glVertexAttribPointer(aWallLocation, 2, GL_FLOAT, false, 0, wallVertexData);
glEnableVertexAttribArray(aWallLocation);

[...generation of static wall_data skipped...]

[...drawing...]

ballVertexData.position(0);
ballVertexData.put(ball_data);
glUniform4f(uColorLocation, 1.0f, 0.0f, 0.0f, 1.0f); // ball is red
glUniform1f(uWhatDrawLocation, 1.0f);
glDrawArrays(GL_TRIANGLE_FAN, 0, BALL_VERTICES + 2);
glUniform4f(uColorLocation, 0.0f, 1.0f, 0.0f, 1.0f); // wall is green
glUniform1f(uWhatDrawLocation, 2.0f);
glDrawArrays(GL_LINES, 0, 2); // wall as a single line

This does not draw wall at all, despite the ball is drawn.

Please suggest in fixing this with 2-array approach or explain a limitation why I should stick with a single array for all activity.


问:
How to show and close plot in matplitlib.pyplot?
I have a real-time updating pandas dataframe with two columns of coordinates. I want to use geopandas to insert a shapefile map in jupyter notebook as a background, and plot the real time coordinates in the map in every 5 seconds, without closing and opening the background map every time. Here are the simplified codes.

```<code>geo_data.plot(alpha=0,figsize=(12, 12))

plt.ion()
while True:
    plt.figure()
    for i in range(len(paths)):
        plt.plot(paths.ix[i:i+1,'z'],paths.ix[i:i+1,'x'])
    plt.show()
    time.sleep(5)
    plt.close()
</code>```

However the "close" doesn't work. It plots one graph after one. I also tried to change the places of "ion", "show", "sleep" and "close" in and out side the "while" loop. None of them is working.

In a word, the geopandas map should be static in the plot. And the real-time coordinates data refreshes on top of the map every five seconds.

答: just add plt.clear() at the end instead of plt.close(). It will replace your old plot and bring the new one on top of it.</p>

Body:
I have a real-time updating pandas dataframe with two columns of coordinates. I want to use geopandas to insert a shapefile map in jupyter notebook as a background, and plot the real time coordinates in the map in every 5 seconds, without closing and opening the background map every time. Here are the simplified codes.

geo_data.plot(alpha=0,figsize=(12, 12))

plt.ion()
while True:
    plt.figure()
    for i in range(len(paths)):
        plt.plot(paths.ix[i:i+1,'z'],paths.ix[i:i+1,'x'])
    plt.show()
    time.sleep(5)
    plt.close()

However the "close" doesn't work. It plots one graph after one. I also tried to change the places of "ion", "show", "sleep" and "close" in and out side the "while" loop. None of them is working.

In a word, the geopandas map should be static in the plot. And the real-time coordinates data refreshes on top of the map every five seconds.


问:
How to find a javascript function using selenium/python/chrome
Im struggling to find and click javascript element which inspected looks like this:

```<code>"<a href="javascript:setTopicMode('PAAdvanced-search','300')">Patch advisories</a>"
</code>```

I tried to find by name, partial name and a href but I am a beginner so I did not managed to make it work.

driver.find_element_by_css_selector("a[onlick*=PAAdvanced-search','300]").click(); does not work either

Can someone advise?

Thank you

答:
If your requirement is to click on above mentioned link then find that using text.
Use //a[text()='Patch advisories'] xpath :

```<code>element=driver.find_element_by_xpath("//a[text()='Patch advisories']")
element.click()
</code>```

Body:
Im struggling to find and click javascript element which inspected looks like this:

"Patch advisories"

I tried to find by name, partial name and a href but I am a beginner so I did not managed to make it work.

driver.find_element_by_css_selector("a[onlick*=PAAdvanced-search','300]").click(); does not work either

Can someone advise?

Thank you

Body:
If your requirement is to click on above mentioned link then find that using text.
Use //a[text()='Patch advisories'] xpath :

element=driver.find_element_by_xpath("//a[text()='Patch advisories']")
element.click()


问:
All columns in join in ruby on rails
```<code>class Category < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :category
  has_many :comments
  has_many :tags
end
</code>```

Category.joins(:articles) in rails equivalently

```<code>SELECT categories.* FROM categories
  INNER JOIN articles ON articles.category_id = categories.id
</code>```

if i want have rails-code is equivalently sql

```<code>SELECT * FROM categories
  INNER JOIN articles ON articles.category_id = categories.id
</code>```

what should I do?

答:
```<code>Category.select('*').joins(:articles)
</code>```

or

```<code>categoyes = Category.select('*').includes(:articles)
</code>```

and

```<code>categoyes.each do |category|
    puts category.articles
end
</code>```

Title: All columns in join in ruby on rails

Body:
class Category < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :category
  has_many :comments
  has_many :tags
end

Category.joins(:articles) in rails equivalently

SELECT categories.* FROM categories
  INNER JOIN articles ON articles.category_id = categories.id

if i want have rails-code is equivalently sql

SELECT * FROM categories
  INNER JOIN articles ON articles.category_id = categories.id

what should I do?

Body:
Category.select('*').joins(:articles)

or

categoyes = Category.select('*').includes(:articles)

and

categoyes.each do |category|
    puts category.articles
end


问:
Script to download file by name according to date on a Windows?
I need to daily run a script that will download a file from a fixed location (http://www.meteoman.it/ilmeteo/audio/) and save it on my computer.
The format of filename is yyyy-mm-dd.mp3 and everyday a new file in added.
The script must recognize the date and save the appropriate file whit the date of today in the folder "today" and the file whit the date of tomorrow in the folder "tomorrow".
thank you !!!

the script if for automate the forecast on my web-radio
the file of forecast are freeware
sorry for my English!
cheers from Italy

答:
The calls to Right are to pad the month and day with a leading zero if needed (adds a zero to any month/day and then extract only the last 2 digits).

```<code>dt = Date
yearStr = Year(dt)
monthStr = Right("0" & Month(dt), 2)
dayStr = Right("0" & Day(dt), 2)
fileName = yearStr & "-" & monthStr & "-" & dayStr & ".mp3"
</code>```

To get tomorrow's date, just change the first line to:

```<code>dt = DateAdd("d", 1, Date)
</code>```

Body:
The calls to Right are to pad the month and day with a leading zero if needed (adds a zero to any month/day and then extract only the last 2 digits).

dt = Date
yearStr = Year(dt)
monthStr = Right("0" & Month(dt), 2)
dayStr = Right("0" & Day(dt), 2)
fileName = yearStr & "-" & monthStr & "-" & dayStr & ".mp3"

To get tomorrow's date, just change the first line to:

dt = DateAdd("d", 1, Date)


问:
python regular expressions index long string and eliminate all things between regular patterns A and B
I have the following sentence where I want to get rid of everything with the format '(number)/(... ;  number)' :

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure (1; 2 ;  3). Many of these architectural proteins are
  molecular bridges that can bind at two or more distinct DNA sites to
  form loops. For example, bacterial DNA is looped and compacted by the
  histonelike protein H-NS, which has two distinct DNA-binding domains
  (4). In eukaryotes, complexes of transcription factors and RNA
  polymerases stabilize enhancer-promoter loops (5; 6; 7 ;  8), while
  HP1 (9), histone H1 (10), and the polycomb-repressor complex PRC1/2
  (11 ;  12) organize inactive chromatin. Proteins also bind to specific
  DNA sequences to form larger structures, like nucleoli and the
  histone-locus, or Cajal and promyeloleukemia bodies (13; 14; 15; 16;
  17 ;  18). The selective binding of molecular bridges to active and
  inactive regions of chromatin has also been highlighted as one
  possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions (6; 8
  ;  19).

I want it to be in the form:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure . Many of these architectural proteins are molecular bridges
  that can bind at two or more distinct DNA sites to form loops. For
  example, bacterial DNA is looped and compacted by the histonelike
  protein H-NS, which has two distinct DNA-binding domains . In
  eukaryotes, complexes of transcription factors and RNA polymerases
  stabilize enhancer-promoter loops , while HP1 , histone H1 , and the
  polycomb-repressor complex PRC1/2  organize inactive chromatin.
  Proteins also bind to specific DNA sequences to form larger
  structures, like nucleoli and the histone-locus, or Cajal and
  promyeloleukemia bodies . The selective binding of molecular bridges
  to active and inactive regions of chromatin has also been highlighted
  as one possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions .

My attempt was as follows:

```<code>import re
x=re.sub(r'\(.+;  \d+\)', '', x) # eliminate brackets with multiple numbers
#### NOTE: there are 2 spaces between the last ';' and the last digit
x=re.sub(r'\d+\)', '', x) # eliminate brackets with single number
</code>```

My output was this:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure .

So clearly my code is missing something. I thought that '(.+)' would identify all brackets containing non-arbitrary characters and then I could further specify that I want all the ones ending in a ';  number'.

I just want a flexible way of indexing a sentence at all places with '(number' and 'number)' and eliminate everything in between....

答:
I found a glitch in your expected text, there's 1 space missing after PRC1/2. But this code works, with that space added back in:

```<code>text="""
In all living organisms, from bacteria to man, DNA and chromatin are invariably
associated with binding proteins, which organize their structure (1; 2 ; 3).
Many of these architectural proteins are molecular bridges that can bind at two
or more distinct DNA sites to form loops. For example, bacterial DNA is looped
and compacted by the histonelike protein H-NS, which has two distinct
DNA-binding domains (4). In eukaryotes, complexes of transcription factors and
RNA polymerases stabilize enhancer-promoter loops (5; 6; 7 ; 8), while HP1 (9),
histone H1 (10), and the polycomb-repressor complex PRC1/2 (11 ; 12) organize
inactive chromatin. Proteins also bind to specific DNA sequences to form larger
structures, like nucleoli and the histone-locus, or Cajal and promyeloleukemia
bodies (13; 14; 15; 16; 17 ; 18). The selective binding of molecular bridges to
active and inactive regions of chromatin has also been highlighted as one
possible mechanism underlying the formation of topologically associated domains
(TADs)—regions rich in local DNA interactions (6; 8 ; 19).
""".replace('\n', ' ')

expected="""
In all living organisms, from bacteria to man, DNA and chromatin are invariably
associated with binding proteins, which organize their structure . Many of
these architectural proteins are molecular bridges that can bind at two or more
distinct DNA sites to form loops. For example, bacterial DNA is looped and
compacted by the histonelike protein H-NS, which has two distinct DNA-binding
domains . In eukaryotes, complexes of transcription factors and RNA polymerases
stabilize enhancer-promoter loops , while HP1 , histone H1 , and the
polycomb-repressor complex PRC1/2  organize inactive chromatin. Proteins also
bind to specific DNA sequences to form larger structures, like nucleoli and the
histone-locus, or Cajal and promyeloleukemia bodies . The selective binding of
molecular bridges to active and inactive regions of chromatin has also been
highlighted as one possible mechanism underlying the formation of topologically
associated domains (TADs)—regions rich in local DNA interactions .
""".replace('\n', ' ')

import re

cites = r"\(\s*\d+(?:\s*;\s+\d+)*\s*\)"

edited = re.sub(cites, '', text)

i = 0
while i < len(edited):
    if edited[i] == expected[i]:
        print(edited[i], sep='', end='')
    else:
        print('[', edited[i], ']', sep='', end='')
    i+=1

print('')
</code>```

The regex I'm using is cites, and it looks like this:

```<code>r"\(\s*\d+(?:\s*;\s+\d+)*\s*\)"
</code>```

The syntax r"..." means "raw", which for our purposes means "leave backslashes alone!" It's what you should (nearly) always use for regexes.

The outer \( and \) match the actual parens in the citation.

The \s* matches zero or more "white-space" characters, which include spaces, tabs, and newlines.

The \d+ matches one or more digits [0..9].

So to start with, there's a regex like:

```<code>\( \s* \d+ \s* \)
</code>```

Which is just "parens around a number, maybe with spaces before or after."

The inner part,

```<code>(?:\s*;\s+\d+)*
</code>```

says "don't capture": (?:...) is a non-capturing group, because we don't care about \1 or getting anything out of the pattern, we just want to delete it.

The \s*; matches optional spaces before a semicolon.

The \s+\d+ matches required spaces before another number - you might have to make those optional spaces if you have something like "(1;3;5)".

The * after the non-capturing group means zero or more occurrences.

Put it all together and you have:

```<code>open-paren
optional spaces
number
followed by zero or more of:
    optional spaces
    semicolon
    required spaces
    number
optional spaces
close-paren
</code>```

Body:
I have the following sentence where I want to get rid of everything with the format '(number)/(... ;  number)' :

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure (1; 2 ;  3). Many of these architectural proteins are
  molecular bridges that can bind at two or more distinct DNA sites to
  form loops. For example, bacterial DNA is looped and compacted by the
  histonelike protein H-NS, which has two distinct DNA-binding domains
  (4). In eukaryotes, complexes of transcription factors and RNA
  polymerases stabilize enhancer-promoter loops (5; 6; 7 ;  8), while
  HP1 (9), histone H1 (10), and the polycomb-repressor complex PRC1/2
  (11 ;  12) organize inactive chromatin. Proteins also bind to specific
  DNA sequences to form larger structures, like nucleoli and the
  histone-locus, or Cajal and promyeloleukemia bodies (13; 14; 15; 16;
  17 ;  18). The selective binding of molecular bridges to active and
  inactive regions of chromatin has also been highlighted as one
  possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions (6; 8
  ;  19).

I want it to be in the form:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure . Many of these architectural proteins are molecular bridges
  that can bind at two or more distinct DNA sites to form loops. For
  example, bacterial DNA is looped and compacted by the histonelike
  protein H-NS, which has two distinct DNA-binding domains . In
  eukaryotes, complexes of transcription factors and RNA polymerases
  stabilize enhancer-promoter loops , while HP1 , histone H1 , and the
  polycomb-repressor complex PRC1/2  organize inactive chromatin.
  Proteins also bind to specific DNA sequences to form larger
  structures, like nucleoli and the histone-locus, or Cajal and
  promyeloleukemia bodies . The selective binding of molecular bridges
  to active and inactive regions of chromatin has also been highlighted
  as one possible mechanism underlying the formation of topologically
  associated domains (TADs)—regions rich in local DNA interactions .

My attempt was as follows:

import re
x=re.sub(r'\(.+;  \d+\)', '', x) # eliminate brackets with multiple numbers
#### NOTE: there are 2 spaces between the last ';' and the last digit
x=re.sub(r'\d+\)', '', x) # eliminate brackets with single number

My output was this:

In all living organisms, from bacteria to man, DNA and chromatin are
  invariably associated with binding proteins, which organize their
  structure .

So clearly my code is missing something. I thought that '(.+)' would identify all brackets containing non-arbitrary characters and then I could further specify that I want all the ones ending in a ';  number'.

I just want a flexible way of indexing a sentence at all places with '(number' and 'number)' and eliminate everything in between....

Body:
I found a glitch in your expected text, there's 1 space missing after PRC1/2. But this code works, with that space added back in:

text="""
In all living organisms, from bacteria to man, DNA and chromatin are invariably
associated with binding proteins, which organize their structure (1; 2 ; 3).
Many of these architectural proteins are molecular bridges that can bind at two
or more distinct DNA sites to form loops. For example, bacterial DNA is looped
and compacted by the histonelike protein H-NS, which has two distinct
DNA-binding domains (4). In eukaryotes, complexes of transcription factors and
RNA polymerases stabilize enhancer-promoter loops (5; 6; 7 ; 8), while HP1 (9),
histone H1 (10), and the polycomb-repressor complex PRC1/2 (11 ; 12) organize
inactive chromatin. Proteins also bind to specific DNA sequences to form larger
structures, like nucleoli and the histone-locus, or Cajal and promyeloleukemia
bodies (13; 14; 15; 16; 17 ; 18). The selective binding of molecular bridges to
active and inactive regions of chromatin has also been highlighted as one
possible mechanism underlying the formation of topologically associated domains
(TADs)—regions rich in local DNA interactions (6; 8 ; 19).
""".replace('\n', ' ')

expected="""
In all living organisms, from bacteria to man, DNA and chromatin are invariably
associated with binding proteins, which organize their structure . Many of
these architectural proteins are molecular bridges that can bind at two or more
distinct DNA sites to form loops. For example, bacterial DNA is looped and
compacted by the histonelike protein H-NS, which has two distinct DNA-binding
domains . In eukaryotes, complexes of transcription factors and RNA polymerases
stabilize enhancer-promoter loops , while HP1 , histone H1 , and the
polycomb-repressor complex PRC1/2  organize inactive chromatin. Proteins also
bind to specific DNA sequences to form larger structures, like nucleoli and the
histone-locus, or Cajal and promyeloleukemia bodies . The selective binding of
molecular bridges to active and inactive regions of chromatin has also been
highlighted as one possible mechanism underlying the formation of topologically
associated domains (TADs)—regions rich in local DNA interactions .
""".replace('\n', ' ')

import re

cites = r"\(\s*\d+(?:\s*;\s+\d+)*\s*\)"

edited = re.sub(cites, '', text)

i = 0
while i < len(edited):
    if edited[i] == expected[i]:
        print(edited[i], sep='', end='')
    else:
        print('[', edited[i], ']', sep='', end='')
    i+=1

print('')

The regex I'm using is cites, and it looks like this:

r"\(\s*\d+(?:\s*;\s+\d+)*\s*\)"

The syntax r"..." means "raw", which for our purposes means "leave backslashes alone!" It's what you should (nearly) always use for regexes.

The outer \( and \) match the actual parens in the citation.

The \s* matches zero or more "white-space" characters, which include spaces, tabs, and newlines.

The \d+ matches one or more digits [0..9].

So to start with, there's a regex like:

\( \s* \d+ \s* \)

Which is just "parens around a number, maybe with spaces before or after."

The inner part,

(?:\s*;\s+\d+)*

says "don't capture": (?:...) is a non-capturing group, because we don't care about \1 or getting anything out of the pattern, we just want to delete it.

The \s*; matches optional spaces before a semicolon.

The \s+\d+ matches required spaces before another number - you might have to make those optional spaces if you have something like "(1;3;5)".

The * after the non-capturing group means zero or more occurrences.

Put it all together and you have:

open-paren
optional spaces
number
followed by zero or more of:
    optional spaces
    semicolon
    required spaces
    number
optional spaces
close-paren


问:
Error with Tuple in C# 2008
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

```<code>private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
</code>```

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

```<code>public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}
</code>```

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks

答:
Tuple is new in .NET Framework 4. Visual Studio only targets .NET Framework 3.5 as the latest version. Therefore, you are targetting a Framework that does not contain the Tuple class, and it won't compile.

If you really need it in Framework 3.5 / VS2008, it wouldn't be too hard to write your own Tuple class to make the existing code compile under that version (provided you are not using any other 4.0 specific stuff).

Title: Error with Tuple in C# 2008

Body:
I have made a program in C# 2010 and my code contains a Tuple, but when I put my program into C# 2008 it does not recognise it, and comes up with the error of:

"The type of namespace name 'Tuple' could not be found"

So I don't know how to make this work, this is the line of code in which the error occurs:

private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();

Please help.

EDIT

Basically this is my code at the moment which doesn't compile due to the error:

public partial class Form1 : Form
{
    private bool isMoving = false;
    private Point mouseDownPosition = Point.Empty;
    private Point mouseMovePosition = Point.Empty;
    private List<Tuple<Point, Point>> lines = new List<Tuple<Point, Point>>();
    public Form1()
    {
        InitializeComponent();
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        if (isMoving)
        {
            g.Clear(pictureBox1.BackColor);
            g.DrawLine(Pens.Black, mouseDownPosition, mouseMovePosition);
            foreach (var line in lines)
            {
                g.DrawLine(Pens.Black, line.Item1, line.Item2);
            }
        }
    }

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isMoving = true;
        mouseDownPosition = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            mouseMovePosition = e.Location;
            pictureBox1.Invalidate();
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        if (isMoving)
        {
            lines.Add(Tuple.Create(mouseDownPosition, mouseMovePosition));
        }
        isMoving = false;
    }
}

So I need a way of changing or making the Tuple work in VS C# 2008 as well as 2010,

Thanks


问:
MySQL Complex Count Issue
I am trying to do a query whereby if a football team wins a home game (e.g. Liverpool FC) then a 1 is added to a column, and the same for a loss (which would be AwayWins, and a draw would be 'Draw').

The following query works great, it just compares the goals scores and adds the 1 in the appropriate place.

```<code>SELECT *,
    IF(max(`goalsHomeTeam`)>`awayTeamName`,'1','') as HomeWins,
    IF(max(`goalsHomeTeam`)<`awayTeamName`,'1','') as AwayWins,
    IF(max(`goalsHomeTeam`)=`awayTeamName`,'1','') as Draw
FROM fixtures
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY fixtures_id
LIMIT 10
</code>```

And this looks like:

However, what I'd really like to display is just the 3 fields:

HomeWins, AwayWins and Draw

and then a count for each box (e.g. based on the picture above HomeWins: 9, AwayWins: 0 and Draw: 0.

I've tried adding simple stuff like wrapping a count around the IF's but that didn't work. Any advice?

答:
You can do something like this:

```<code>Select SUM(T1.HomeWins), SUM(T1.AwayWins), SUM(T1.Draw)
From (#your query here#) AS T1
</code>```

and simple example that it works: http://rextester.com/SYQI26450

Title: MySQL Complex Count Issue

Body:
I am trying to do a query whereby if a football team wins a home game (e.g. Liverpool FC) then a 1 is added to a column, and the same for a loss (which would be AwayWins, and a draw would be 'Draw').

The following query works great, it just compares the goals scores and adds the 1 in the appropriate place.

SELECT *,
    IF(max(`goalsHomeTeam`)>`awayTeamName`,'1','') as HomeWins,
    IF(max(`goalsHomeTeam`)<`awayTeamName`,'1','') as AwayWins,
    IF(max(`goalsHomeTeam`)=`awayTeamName`,'1','') as Draw
FROM fixtures
WHERE `homeTeamName` = 'Liverpool FC'
GROUP BY fixtures_id
LIMIT 10

And this looks like:

However, what I'd really like to display is just the 3 fields:

HomeWins, AwayWins and Draw

and then a count for each box (e.g. based on the picture above HomeWins: 9, AwayWins: 0 and Draw: 0.

I've tried adding simple stuff like wrapping a count around the IF's but that didn't work. Any advice?

Body:
You can do something like this:

Select SUM(T1.HomeWins), SUM(T1.AwayWins), SUM(T1.Draw)
From (#your query here#) AS T1

and simple example that it works: http://rextester.com/SYQI26450


问:
Retrieving two values from each line of a text document
I am trying to get the contents from a file, the ping result and the description. The everything through pinging works, but I how do I get the description in my output?

```<code>GC D:\Temp\System.txt | %{
    If (Test-Connection $_ -Quiet -Count 2){
        Write-Host "$_ is UP" -b Green
    }
    Else{
        Write-Host "$_ is Down" -b Red
    }
}
PAUSE
</code>```

Content with IP addresses to ping and their descriptions

```<code>10.200.11.2     Firewall
10.200.11.14    Test1
192.168.254.81  Test2
192.168.254.133 Test3
</code>```

答:
To add several other ways to do this:

Since it looks like you are using tabs delimiters you could split on the tabs.

```<code>GC D:\Temp\System.txt | % {
    $hostname = ($_.Split("`t") | ? {$_ -ne ""})[0]
    $description = ($_.Split("`t") | ? {$_ -ne ""})[1]
    If (Test-Connection $hostname -Quiet -Count 2) {
        Write-Host "Hostname: $hostname Description: $description is UP" -b Green
    } Else {
        Write-Host "Hostname: $hostname Description: $description is Down" -b Red
    }
}
</code>```

Or you could import it as a CSV with a tab delimiter

```<code>Import-CSV D:\Temp\System.txt -Delimiter `t -Header hostname,description | % {
    If (Test-Connection $_.hostname -Quiet -Count 2) {
        Write-Host "Hostname: $($_.hostname) Description: $($_.description) is UP" -b Green
        [pscustomobject]@{
            Hostname = $_.hostname
            Description = $_.description
            Status = "Up"
        }
    } Else {
        Write-Host "Hostname: $($_.hostname) Description: $($_.description) is Down" -b Red
        [pscustomobject]@{
            Hostname = $_.hostname
            Description = $_.description
            Status = "Down"
        }
    }
} | ConvertTo-HTML | Out-File D:\Temp\Example.html
</code>```

Body:
I am trying to get the contents from a file, the ping result and the description. The everything through pinging works, but I how do I get the description in my output?

GC D:\Temp\System.txt | %{
    If (Test-Connection $_ -Quiet -Count 2){
        Write-Host "$_ is UP" -b Green
    }
    Else{
        Write-Host "$_ is Down" -b Red
    }
}
PAUSE

Content with IP addresses to ping and their descriptions

10.200.11.2     Firewall
10.200.11.14    Test1
192.168.254.81  Test2
192.168.254.133 Test3

Body:
To add several other ways to do this:

Since it looks like you are using tabs delimiters you could split on the tabs.

GC D:\Temp\System.txt | % {
    $hostname = ($_.Split("`t") | ? {$_ -ne ""})[0]
    $description = ($_.Split("`t") | ? {$_ -ne ""})[1]
    If (Test-Connection $hostname -Quiet -Count 2) {
        Write-Host "Hostname: $hostname Description: $description is UP" -b Green
    } Else {
        Write-Host "Hostname: $hostname Description: $description is Down" -b Red
    }
}

Or you could import it as a CSV with a tab delimiter

Import-CSV D:\Temp\System.txt -Delimiter `t -Header hostname,description | % {
    If (Test-Connection $_.hostname -Quiet -Count 2) {
        Write-Host "Hostname: $($_.hostname) Description: $($_.description) is UP" -b Green
        [pscustomobject]@{
            Hostname = $_.hostname
            Description = $_.description
            Status = "Up"
        }
    } Else {
        Write-Host "Hostname: $($_.hostname) Description: $($_.description) is Down" -b Red
        [pscustomobject]@{
            Hostname = $_.hostname
            Description = $_.description
            Status = "Down"
        }
    }
} | ConvertTo-HTML | Out-File D:\Temp\Example.html