问:
Rapidminer, sort and filter attributes
I am using RapidMiner, and I would like to order my attributes' per example, and then filter the 15th's highest values. Can someone give me a clue on that?

Thanks.

答:
So if I understand you correctly, you have an example set and for each row you want to sort the attributes and keep only the 15 biggest?

So imagine you have this random data set:

You try to get this result for your first example (limited to 5 biggest attributes for simplicity):

This can be done by looping over your example set with Loop Examples, filter each row with Filter Example Range, then Transpose the rows to columns, which then again can be sorted with Sort and limited to the max 15 values using Filter Example Range again.

Please notice that these new examples (rows) cannot be easily represented in a single example set, since they assumingly all have different attributes in a different order, thus you will get a collection of separate, sorted example sets.

Here is an example process:

```<code><?xml version="1.0" encoding="UTF-8"?><process version="7.5.000">
  <context>
    <input/>
    <output/>
    <macros/>
  </context>
  <operator activated="true" class="process" compatibility="7.5.000" expanded="true" name="Process">
    <process expanded="true">
      <operator activated="true" class="generate_data" compatibility="7.5.000" expanded="true" height="68" name="Generate Data" width="90" x="45" y="34">
        <parameter key="number_examples" value="10"/>
        <parameter key="number_of_attributes" value="10"/>
      </operator>
      <operator activated="true" class="select_attributes" compatibility="7.5.000" expanded="true" height="82" name="Select Attributes" width="90" x="179" y="34">
        <parameter key="attribute_filter_type" value="single"/>
        <parameter key="attribute" value="label"/>
        <parameter key="invert_selection" value="true"/>
        <parameter key="include_special_attributes" value="true"/>
        <description align="center" color="transparent" colored="false" width="126">remove label for clarity</description>
      </operator>
      <operator activated="true" class="loop_examples" compatibility="7.5.000" expanded="true" height="103" name="Loop Examples" width="90" x="313" y="34">
        <process expanded="true">
          <operator activated="true" class="filter_example_range" compatibility="7.5.000" expanded="true" height="82" name="Filter Example Range" width="90" x="45" y="34">
            <parameter key="first_example" value="%{example}"/>
            <parameter key="last_example" value="%{example}"/>
            <description align="center" color="transparent" colored="false" width="126">only work on current example</description>
          </operator>
          <operator activated="true" class="transpose" compatibility="7.5.000" expanded="true" height="82" name="Transpose" width="90" x="179" y="34">
            <description align="center" color="transparent" colored="false" width="126">transpose the row to columns with attribute name and attribute value</description>
          </operator>
          <operator activated="true" class="rename" compatibility="7.5.000" expanded="true" height="82" name="Rename" width="90" x="313" y="34">
            <parameter key="old_name" value="id"/>
            <parameter key="new_name" value="Example%{example}AttributeName"/>
            <list key="rename_additional_attributes">
              <parameter key="att_1" value="Value"/>
            </list>
            <description align="center" color="transparent" colored="false" width="126">rename for clarity, include original &quot;row&quot; number in attribute name</description>
          </operator>
          <operator activated="true" class="sort" compatibility="7.5.000" expanded="true" height="82" name="Sort" width="90" x="447" y="34">
            <parameter key="attribute_name" value="Value"/>
            <parameter key="sorting_direction" value="decreasing"/>
            <description align="center" color="transparent" colored="false" width="126">sort decreasing by attribute value</description>
          </operator>
          <operator activated="true" class="filter_example_range" compatibility="7.5.000" expanded="true" height="82" name="Filter Example Range (2)" width="90" x="581" y="34">
            <parameter key="first_example" value="1"/>
            <parameter key="last_example" value="5"/>
            <description align="center" color="transparent" colored="false" width="126">keep 5 attributes with biggest values</description>
          </operator>
          <connect from_port="example set" to_op="Filter Example Range" to_port="example set input"/>
          <connect from_op="Filter Example Range" from_port="example set output" to_op="Transpose" to_port="example set input"/>
          <connect from_op="Transpose" from_port="example set output" to_op="Rename" to_port="example set input"/>
          <connect from_op="Rename" from_port="example set output" to_op="Sort" to_port="example set input"/>
          <connect from_op="Sort" from_port="example set output" to_op="Filter Example Range (2)" to_port="example set input"/>
          <connect from_op="Filter Example Range (2)" from_port="example set output" to_port="output 1"/>
          <portSpacing port="source_example set" spacing="0"/>
          <portSpacing port="sink_example set" spacing="0"/>
          <portSpacing port="sink_output 1" spacing="0"/>
          <portSpacing port="sink_output 2" spacing="0"/>
        </process>
        <description align="center" color="transparent" colored="false" width="126">Loop over all examples, current index is stored in the macro &quot;example&quot;</description>
      </operator>
      <connect from_op="Generate Data" from_port="output" to_op="Select Attributes" to_port="example set input"/>
      <connect from_op="Select Attributes" from_port="example set output" to_op="Loop Examples" to_port="example set"/>
      <connect from_op="Loop Examples" from_port="output 1" to_port="result 1"/>
      <portSpacing port="source_input 1" spacing="0"/>
      <portSpacing port="sink_result 1" spacing="0"/>
      <portSpacing port="sink_result 2" spacing="0"/>
    </process>
  </operator>
</process>
</code>```

Title: Rapidminer, sort and filter attributes

Body:
So if I understand you correctly, you have an example set and for each row you want to sort the attributes and keep only the 15 biggest?

So imagine you have this random data set:

You try to get this result for your first example (limited to 5 biggest attributes for simplicity):

This can be done by looping over your example set with Loop Examples, filter each row with Filter Example Range, then Transpose the rows to columns, which then again can be sorted with Sort and limited to the max 15 values using Filter Example Range again.

Please notice that these new examples (rows) cannot be easily represented in a single example set, since they assumingly all have different attributes in a different order, thus you will get a collection of separate, sorted example sets.

Here is an example process:

<?xml version="1.0" encoding="UTF-8"?><process version="7.5.000">
  <context>
    <input/>
    <output/>
    <macros/>
  </context>
  <operator activated="true" class="process" compatibility="7.5.000" expanded="true" name="Process">
    <process expanded="true">
      <operator activated="true" class="generate_data" compatibility="7.5.000" expanded="true" height="68" name="Generate Data" width="90" x="45" y="34">
        <parameter key="number_examples" value="10"/>
        <parameter key="number_of_attributes" value="10"/>
      </operator>
      <operator activated="true" class="select_attributes" compatibility="7.5.000" expanded="true" height="82" name="Select Attributes" width="90" x="179" y="34">
        <parameter key="attribute_filter_type" value="single"/>
        <parameter key="attribute" value="label"/>
        <parameter key="invert_selection" value="true"/>
        <parameter key="include_special_attributes" value="true"/>
        <description align="center" color="transparent" colored="false" width="126">remove label for clarity</description>
      </operator>
      <operator activated="true" class="loop_examples" compatibility="7.5.000" expanded="true" height="103" name="Loop Examples" width="90" x="313" y="34">
        <process expanded="true">
          <operator activated="true" class="filter_example_range" compatibility="7.5.000" expanded="true" height="82" name="Filter Example Range" width="90" x="45" y="34">
            <parameter key="first_example" value="%{example}"/>
            <parameter key="last_example" value="%{example}"/>
            <description align="center" color="transparent" colored="false" width="126">only work on current example</description>
          </operator>
          <operator activated="true" class="transpose" compatibility="7.5.000" expanded="true" height="82" name="Transpose" width="90" x="179" y="34">
            <description align="center" color="transparent" colored="false" width="126">transpose the row to columns with attribute name and attribute value</description>
          </operator>
          <operator activated="true" class="rename" compatibility="7.5.000" expanded="true" height="82" name="Rename" width="90" x="313" y="34">
            <parameter key="old_name" value="id"/>
            <parameter key="new_name" value="Example%{example}AttributeName"/>
            <list key="rename_additional_attributes">
              <parameter key="att_1" value="Value"/>
            </list>
            <description align="center" color="transparent" colored="false" width="126">rename for clarity, include original &amp;quot;row&amp;quot; number in attribute name</description>
          </operator>
          <operator activated="true" class="sort" compatibility="7.5.000" expanded="true" height="82" name="Sort" width="90" x="447" y="34">
            <parameter key="attribute_name" value="Value"/>
            <parameter key="sorting_direction" value="decreasing"/>
            <description align="center" color="transparent" colored="false" width="126">sort decreasing by attribute value</description>
          </operator>
          <operator activated="true" class="filter_example_range" compatibility="7.5.000" expanded="true" height="82" name="Filter Example Range (2)" width="90" x="581" y="34">
            <parameter key="first_example" value="1"/>
            <parameter key="last_example" value="5"/>
            <description align="center" color="transparent" colored="false" width="126">keep 5 attributes with biggest values</description>
          </operator>
          <connect from_port="example set" to_op="Filter Example Range" to_port="example set input"/>
          <connect from_op="Filter Example Range" from_port="example set output" to_op="Transpose" to_port="example set input"/>
          <connect from_op="Transpose" from_port="example set output" to_op="Rename" to_port="example set input"/>
          <connect from_op="Rename" from_port="example set output" to_op="Sort" to_port="example set input"/>
          <connect from_op="Sort" from_port="example set output" to_op="Filter Example Range (2)" to_port="example set input"/>
          <connect from_op="Filter Example Range (2)" from_port="example set output" to_port="output 1"/>
          <portSpacing port="source_example set" spacing="0"/>
          <portSpacing port="sink_example set" spacing="0"/>
          <portSpacing port="sink_output 1" spacing="0"/>
          <portSpacing port="sink_output 2" spacing="0"/>
        </process>
        <description align="center" color="transparent" colored="false" width="126">Loop over all examples, current index is stored in the macro &amp;quot;example&amp;quot;</description>
      </operator>
      <connect from_op="Generate Data" from_port="output" to_op="Select Attributes" to_port="example set input"/>
      <connect from_op="Select Attributes" from_port="example set output" to_op="Loop Examples" to_port="example set"/>
      <connect from_op="Loop Examples" from_port="output 1" to_port="result 1"/>
      <portSpacing port="source_input 1" spacing="0"/>
      <portSpacing port="sink_result 1" spacing="0"/>
      <portSpacing port="sink_result 2" spacing="0"/>
    </process>
  </operator>
</process>


来源: stackexchange

问:
Get Only first object from Mongo Cursor
I'm making a query to a MongoDB and I only want the first object. I know I could use findOne, but I'm still confused where I'm going wrong.

This does not work:

```<code>if ($cursor->count() > 0) {
    $image = $cursor->current();
    // neither does this work
    // $image = $cursor[0];
    return $image;
} else {
    return false;
}

//echo $image->filename;
// Throws error: Trying to access property of non-object image
</code>```

This works though:

```<code>if ($cursor->count() > 0) {
    $image = null;
    foreach($cursor as $obj)
        $image = $obj;
    return $image;
} else {
    return false;
}
</code>```

答:
Solution provided by raina77ow uses Mongo library which is marked as legacy.

At the moment there is only one way to get first element from cursor - use MongoDB\Driver\Cursor::toArray method:

```<code>$cursor = $collection->find();
$firstDocument = $cursor->toArray()[0];
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get Only first object from Mongo Cursor

Body:
I'm making a query to a MongoDB and I only want the first object. I know I could use findOne, but I'm still confused where I'm going wrong.

This does not work:

if ($cursor->count() > 0) {
    $image = $cursor->current();
    // neither does this work
    // $image = $cursor[0];
    return $image;
} else {
    return false;
}

//echo $image->filename;
// Throws error: Trying to access property of non-object image

This works though:

if ($cursor->count() > 0) {
    $image = null;
    foreach($cursor as $obj)
        $image = $obj;
    return $image;
} else {
    return false;
}

Body:
Solution provided by raina77ow uses Mongo library which is marked as legacy.

At the moment there is only one way to get first element from cursor - use MongoDB\Driver\Cursor::toArray method:

$cursor = $collection->find();
$firstDocument = $cursor->toArray()[0];


问:
java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri
I try to start application but using Tomcat 7 and I've got an exception like this.

I think this can be something with Maven dependency, but I'm sure. If some know what is going on please for answer:)

Exception:

```<code>message Servlet execution threw an exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;
    javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:651)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.50 logs.
</code>```

Maven POM:

```<code><properties>
        <application.version>1.0</application.version>
        <spring.version>4.0.0.RELEASE</spring.version>
        <spring.security.version>3.2.0.RELEASE</spring.security.version>
        <jersey.version>1.18.1</jersey.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>climbing-portal-facade</groupId>
            <artifactId>climbing-portal-facade</artifactId>
            <version>${application.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
            <artifactId>jersey-test-framework-provider-jdk-http</artifactId>
            <version>2.7</version>
        </dependency>

        <!-- Jersey + Spring -->
        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-spring</artifactId>
            <version>${jersey.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-web</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</code>```

Any idea ?

答:
We need to make the below changes :

web.xml

```<code>    <servlet>
      <servlet-name>RESTful Jersey Web Service Sample</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
         <init-param>
                   <param-name>jersey.config.server.provider.packages</param-name>
                   <param-value>com.subu.jersey.rest</param-value>
         </init-param>
    </servlet>
</code>```

pom.xml

```<code>    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.17</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <version>2.17</version>
    </dependency>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I try to start application but using Tomcat 7 and I've got an exception like this.

I think this can be something with Maven dependency, but I'm sure. If some know what is going on please for answer:)

Exception:

message Servlet execution threw an exception

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

root cause

java.lang.AbstractMethodError: javax.ws.rs.core.UriBuilder.uri(Ljava/lang/String;)Ljavax/ws/rs/core/UriBuilder;
    javax.ws.rs.core.UriBuilder.fromUri(UriBuilder.java:119)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:651)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.50 logs.

Maven POM:

<properties>
        <application.version>1.0</application.version>
        <spring.version>4.0.0.RELEASE</spring.version>
        <spring.security.version>3.2.0.RELEASE</spring.security.version>
        <jersey.version>1.18.1</jersey.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>climbing-portal-facade</groupId>
            <artifactId>climbing-portal-facade</artifactId>
            <version>${application.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>${jersey.version}</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
            <artifactId>jersey-test-framework-provider-jdk-http</artifactId>
            <version>2.7</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-spring</artifactId>
            <version>${jersey.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-web</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-aop</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>

Any idea ?

Body:
We need to make the below changes :

web.xml

    <servlet>
      <servlet-name>RESTful Jersey Web Service Sample</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
         <init-param>
                   <param-name>jersey.config.server.provider.packages</param-name>
                   <param-value>com.subu.jersey.rest</param-value>
         </init-param>
    </servlet>

pom.xml

    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-server</artifactId>
        <version>2.17</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet-core</artifactId>
        <version>2.17</version>
    </dependency>


问:
How to use setState in external function?
```<code>import Request from 'superagent';

const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        this.setState({
             content: res.body
        });
    });
}

export default getApi;
</code>```

I've created function in external file for api call. How do I get access to function/setState in external file?

```<code>componentWillMount(){
   getApi();
}
</code>```

I receive this error:

'TypeError: Cannot read property 'setState' of undefined'

答:
Technically you could pass the instance to getApi so that it knows what this is supposed to be. But imo. that's a poor approach. It creates unnecessary dependencies. At the moment, getApi() needs to know how the React class works; the function is responsible to manipulate the state of the Instance correctly.

Better if getApi() only returns the value, and the instance consumes it:

```<code>const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then(res => res.body);
}

componentWillMount(){
   getApi().then(content => this.setState({ content }));
}
</code>```

Body:
import Request from 'superagent';

const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then((res) => {
        this.setState({
             content: res.body
        });
    });
}

export default getApi;

I've created function in external file for api call. How do I get access to function/setState in external file?

componentWillMount(){
   getApi();
}

I receive this error:

'TypeError: Cannot read property 'setState' of undefined'

Body:
Technically you could pass the instance to getApi so that it knows what this is supposed to be. But imo. that's a poor approach. It creates unnecessary dependencies. At the moment, getApi() needs to know how the React class works; the function is responsible to manipulate the state of the Instance correctly.

Better if getApi() only returns the value, and the instance consumes it:

const getApi = () => {
    let url = '/* URL */';
    return Request.get(url).then(res => res.body);
}

componentWillMount(){
   getApi().then(content => this.setState({ content }));
}


问:
What does norm='l2' in sklearn.preprocessing.normalize do for matrix normalization?
I normalized scipy.sparse matrix sA here by using sklearn.preprocessing.normalize. I read the document but not understand about norm='l...' well, so I tested it.

norm='l1' went ok and I got the sum result as expected as 1 in all row.

```<code>A = np.array([[1,2,0],[0,0,3],[1,0,4]])
sA = sp.csr_matrix(A)
normsA = normalize(sA, norm='l1', axis=0)
print normsA
print "---"
print sum(normsA)

>>(0, 0)    0.5
  (2, 0)    0.5
  (0, 1)    1.0
  (1, 2)    0.428571428571
  (2, 2)    0.571428571429
  ---
  (0, 0)    1.0
  (0, 1)    1.0
  (0, 2)    1.0
</code>```

However, when I tried l2, I can't find how it is normalizing the matrix. Sum of the matrix or the transposed matrix is not equal to one. What l2 does for normalizing here?

```<code>normsA2 = normalize(sA, norm='l2', axis=0)
print sum(normsA2)
print sum(normsA2.T)

>>(0, 0)    1.41421356237
  (0, 1)    1.0
  (0, 2)    1.4
  (0, 0)    1.70710678119
  (0, 1)    0.6
  (0, 2)    1.50710678119
</code>```

答:
That is using the l2 norm (or euclidean norm/distance), in other words the sum of the squares of the elements gives one.

The following outputs the expected vector of ones:

```<code>sum(normsA2 ** 2, axis=0)
</code>```

Body:
I normalized scipy.sparse matrix sA here by using sklearn.preprocessing.normalize. I read the document but not understand about norm='l...' well, so I tested it.

norm='l1' went ok and I got the sum result as expected as 1 in all row.

A = np.array([[1,2,0],[0,0,3],[1,0,4]])
sA = sp.csr_matrix(A)
normsA = normalize(sA, norm='l1', axis=0)
print normsA
print "---"
print sum(normsA)

>>(0, 0)    0.5
  (2, 0)    0.5
  (0, 1)    1.0
  (1, 2)    0.428571428571
  (2, 2)    0.571428571429
  ---
  (0, 0)    1.0
  (0, 1)    1.0
  (0, 2)    1.0

However, when I tried l2, I can't find how it is normalizing the matrix. Sum of the matrix or the transposed matrix is not equal to one. What l2 does for normalizing here?

normsA2 = normalize(sA, norm='l2', axis=0)
print sum(normsA2)
print sum(normsA2.T)

>>(0, 0)    1.41421356237
  (0, 1)    1.0
  (0, 2)    1.4
  (0, 0)    1.70710678119
  (0, 1)    0.6
  (0, 2)    1.50710678119

Body:
That is using the l2 norm (or euclidean norm/distance), in other words the sum of the squares of the elements gives one.

The following outputs the expected vector of ones:

sum(normsA2 ** 2, axis=0)


问:
How to convert the following code to Java 8 Stream?
I was wondered if it is possible to convert the following code to Java 8 Stream?

```<code>List<Borg> newBorgMembers = new ArrayList<>();

// mankind is a List<Individual>
mankind.forEach(id -> newBorgMembers.add(new Borg(id)));
</code>```

Desired structure:

```<code>List<Borg> newBorgMembers = mankind.stream().filter().map().collect()
</code>```

This question is from a tutorial, the hints are using filter and map. The difficulty to me is that how to add elements without initiate an empty holder List<Borg>.

答:
Or a little bit nicer:</p>

```<code> mankind.stream()
        .map(Individual::getId)
        .map(Borg::new)
        .collect(Collectors.toList());
</code>```

Body:
I was wondered if it is possible to convert the following code to Java 8 Stream?

List<Borg> newBorgMembers = new ArrayList<>();

// mankind is a List<Individual>
mankind.forEach(id -> newBorgMembers.add(new Borg(id)));

Desired structure:

List<Borg> newBorgMembers = mankind.stream().filter().map().collect()

This question is from a tutorial, the hints are using filter and map. The difficulty to me is that how to add elements without initiate an empty holder List<Borg>.

Body:
Or a little bit nicer:

 mankind.stream()
        .map(Individual::getId)
        .map(Borg::new)
        .collect(Collectors.toList());


问:
Issue with refactoring of a switch statement
Here is the method that performs the switch(Note The switch statement works correctly and according to the requirements)

```<code>public void performChecks() {
        priceInput = priceReader.nextDouble();
       loop: while(true){
           nameInput = nameReader.nextLine();
            switch(nameInput){
                case "A1": Cola colaItem = new Cola();
                                    if(colaItem.checkPrice(priceInput)){
                                            System.out.println("You ordered " + colaItem.getName()+ ", here is it");
                                    } else {
                                            System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                                    }
                                    break loop;

                case "B2": Chips chipsItem = new Chips();
                                    if(chipsItem.checkPrice(priceInput)){
                                        System.out.println("You ordered " + chipsItem.getName()+ ", here is it");
                                    } else {
                                        System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                                    }
                                    break loop;

                case "C3": Crackers crackerItem = new Crackers();
                                    if(crackerItem.checkPrice(priceInput)){
                                        System.out.println("You ordered " + crackerItem.getName()+ ", here is it");
                                    } else {
                                        System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                                    }
                                        break loop;
                default:
                    System.out.println("Sorry, we don't have item with such a code");
            }
        }
     }
</code>```

Now I started doing some refactoring and put the method in the super class of the items(Cola, Chips and Crackers) and it looks like this:

```<code>public void performChecks(){
    inputPrice = priceReader.nextDouble();
    inputCode = codeReader.nextLine();
    initializeItems();
    for(int i = 0; i < items.length; i++){
        if(items[i].checkCode(inputCode)){
                if(items[i].checkPrice(inputPrice)){
                    System.out.println("You ordered " + items[i].getName() + " here it is");
                    break;
                } else {
                    System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                    break;
                }
        } else if(!items[i].checkCode(inputCode)){
            continue;
        } else {
            System.out.println("Sorry, we don't have item with such a code");
            inputCode = codeReader.nextLine();
        }
    }
}
</code>```

The issue is the following: When I enter correct/incorrect price and incorrect item code, I should be getting the "Sorry, we don't have an item with such a code" message and the option to enter the item code again. I've ran out of ideas on how to implement this option inside the

```<code>else if(!items[i].checkCode(inputCode)){
                continue;
</code>```

Since I'm pretty sure, it just gets stuck there and returns nothing(for incorrect item code).

答:
I'm not absolutely sure, but I guess you can do sth like this: </p>

```<code>inputCode = codeReader.nextLine();
    do{
        if(items[i].checkCode(inputCode)){
            if(items[i].checkPrice(inputPrice)){
                System.out.println("You ordered " + items[i].getName() + " here it is");
                break;
            } else {
                System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                break;
            }
        } else {
            inputCode = codeReader.nextLine();
        }
    } while(!items[i].checkCode(inputCode));
</code>```

Body:
Here is the method that performs the switch(Note The switch statement works correctly and according to the requirements)

public void performChecks() {
        priceInput = priceReader.nextDouble();
       loop: while(true){
           nameInput = nameReader.nextLine();
            switch(nameInput){
                case "A1": Cola colaItem = new Cola();
                                    if(colaItem.checkPrice(priceInput)){
                                            System.out.println("You ordered " + colaItem.getName()+ ", here is it");
                                    } else {
                                            System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                                    }
                                    break loop;

                case "B2": Chips chipsItem = new Chips();
                                    if(chipsItem.checkPrice(priceInput)){
                                        System.out.println("You ordered " + chipsItem.getName()+ ", here is it");
                                    } else {
                                        System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                                    }
                                    break loop;

                case "C3": Crackers crackerItem = new Crackers();
                                    if(crackerItem.checkPrice(priceInput)){
                                        System.out.println("You ordered " + crackerItem.getName()+ ", here is it");
                                    } else {
                                        System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                                    }
                                        break loop;
                default:
                    System.out.println("Sorry, we don't have item with such a code");
            }
        }
     }

Now I started doing some refactoring and put the method in the super class of the items(Cola, Chips and Crackers) and it looks like this:

public void performChecks(){
    inputPrice = priceReader.nextDouble();
    inputCode = codeReader.nextLine();
    initializeItems();
    for(int i = 0; i < items.length; i++){
        if(items[i].checkCode(inputCode)){
                if(items[i].checkPrice(inputPrice)){
                    System.out.println("You ordered " + items[i].getName() + " here it is");
                    break;
                } else {
                    System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                    break;
                }
        } else if(!items[i].checkCode(inputCode)){
            continue;
        } else {
            System.out.println("Sorry, we don't have item with such a code");
            inputCode = codeReader.nextLine();
        }
    }
}

The issue is the following: When I enter correct/incorrect price and incorrect item code, I should be getting the "Sorry, we don't have an item with such a code" message and the option to enter the item code again. I've ran out of ideas on how to implement this option inside the

else if(!items[i].checkCode(inputCode)){
                continue;

Since I'm pretty sure, it just gets stuck there and returns nothing(for incorrect item code).

Body:
I'm not absolutely sure, but I guess you can do sth like this:

inputCode = codeReader.nextLine();
    do{
        if(items[i].checkCode(inputCode)){
            if(items[i].checkPrice(inputPrice)){
                System.out.println("You ordered " + items[i].getName() + " here it is");
                break;
            } else {
                System.out.println("Sorry, the amount is not enough for this purchase. Please add more money and try again");
                break;
            }
        } else {
            inputCode = codeReader.nextLine();
        }
    } while(!items[i].checkCode(inputCode));


问:
Property or indexer 'Form.MdiChildren' cannot be assigned to -- it is read only
I keep getting the error in the title, and I can't figure out where the Form is set to read-only or how I can disable this.

```<code>private void studentToolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            addStudent newStudentForm = new addStudent(this);
            newStudentForm.MdiChildren = this;
            newStudentForm.Show();
        }
</code>```

addStudent is a form that takes care of creating students, and populating a list of students which is kept on the main form. So I want to be able to edit data on Form1 from Form2 which is why I am using Mdi

Can anyone give me any tips on where I should be looking at what I should be looking for to fix this error?

EDIT: To be clear

```<code>Form1 = Parent

Form2 = Child
</code>```

答:
You don't need to set MdiChildren. Moreover, you wouldn't be able to set it this way even if it wasn't readonly - it is a collection of forms, not a form.

Logically, you try to tell that "newStudentForm has current form as MDI child", and is isn't true, you actually need "newStudentForm is a new MDI child of this".

The only thing you need to do is to set MdiParent in your child form:

```<code>private void studentToolStripMenuItem1_Click_1(object sender, EventArgs e)
{
  AddStudent newStudentForm = new AddStudent(this);
  newStudentForm.MdiParent = this;
  newStudentForm.Show();
}
</code>```

P.S. Please, use proper naming for your classes. It shuld be AddStudent, not addStudent. This one letter makes code absolutely unreadable.

Body:
I keep getting the error in the title, and I can't figure out where the Form is set to read-only or how I can disable this.

private void studentToolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            addStudent newStudentForm = new addStudent(this);
            newStudentForm.MdiChildren = this;
            newStudentForm.Show();
        }

addStudent is a form that takes care of creating students, and populating a list of students which is kept on the main form. So I want to be able to edit data on Form1 from Form2 which is why I am using Mdi

Can anyone give me any tips on where I should be looking at what I should be looking for to fix this error?

EDIT: To be clear

Form1 = Parent

Form2 = Child

Body:
You don't need to set MdiChildren. Moreover, you wouldn't be able to set it this way even if it wasn't readonly - it is a collection of forms, not a form.

Logically, you try to tell that "newStudentForm has current form as MDI child", and is isn't true, you actually need "newStudentForm is a new MDI child of this".

The only thing you need to do is to set MdiParent in your child form:

private void studentToolStripMenuItem1_Click_1(object sender, EventArgs e)
{
  AddStudent newStudentForm = new AddStudent(this);
  newStudentForm.MdiParent = this;
  newStudentForm.Show();
}

P.S. Please, use proper naming for your classes. It shuld be AddStudent, not addStudent. This one letter makes code absolutely unreadable.


问:
Django not loading static files (Pycharm)
I am working on a project which requires loading on a CSS stylesheet and a logo file. But my Django server also returns 404 resource not found while loading these files. I have checked other questions like this but none of them is using the format to specify static files I used.
This is the html code i am using

```<code>{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="/static/Emu86/style.css">
{% endblock stylesheets %}
</code>```

This is my settings.py file:

```<code>    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.9.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Application definition

INSTALLED_APPS = [
    'Emu86',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',

]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] \
                %(message)s",
                'datefmt': "%d%b%Y %H:%M:%S"
         },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Emu86.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'Emu86': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    },
}
</code>```

Project Structure:

```<code>Emu86/
  mysite/
      static/
        Emu86/
</code>```

答:
```<code>{% load static %}
{% block stylesheets %}
        <link rel="stylesheet" type="text/css" href="{% static "Emu86/style.css"%}">
{% endblock stylesheets %}
</code>```

I guess the path has to be as above

Body:
I am working on a project which requires loading on a CSS stylesheet and a logo file. But my Django server also returns 404 resource not found while loading these files. I have checked other questions like this but none of them is using the format to specify static files I used.
This is the html code i am using

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="/static/Emu86/style.css">
{% endblock stylesheets %}

This is my settings.py file:

    """
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 1.9.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Application definition

INSTALLED_APPS = [
    'Emu86',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_extensions',

]

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] \
                %(message)s",
                'datefmt': "%d%b%Y %H:%M:%S"
         },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'Emu86.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'DEBUG',
        },
        'Emu86': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    },
}

Project Structure:

Emu86/
  mysite/
      static/
        Emu86/

Body:
{% load static %}
{% block stylesheets %}
        <link rel="stylesheet" type="text/css" href="{% static "Emu86/style.css"%}">
{% endblock stylesheets %}

I guess the path has to be as above


问:
ansible playbook local_action to calculate value and assign to variable
i am new to ansible world. below is my ansible playbook and in that before applying template value for tomcat port. i am tryiny to calculate the port based on exiting no of tomcat instance on the remote server.

how can get the value as an variable using local_action after running an shell?

```<code>-
  hosts: "{{Server}}"
  tasks:
    -
      ignore_errors: true
      name: "find no of Tomcat Instance available on the Server"
      register: Tomcat_Instance_no
      shell: "find /example -name tomcat-users.xml -type f -print | wc -l"

    - debug: var=Tomcat_Instance_no
    #- local_action: copy content="{{ Tomcat_Instance_no.stdout }}" dest="/tmp/{{Server}}_Tomcat_Instance_no"
    #- local_action: "shell sh define-tomcat-instance-port.sh {{Server}} {{IName}} {{ Tomcat_Instance_no.stdout }}"
    ****- local_action: "shell sh http_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8080))"
      register: HTPN
    - local_action: "shell sh shutdown_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8005))"
      register: SHPN
    - local_action: "shell sh https_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8043))"
      register: SSPN
    - local_action: "shell sh ajp_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8009))"
      register: AJPN**

    #-
      #name: bare include
      #include_vars: "{{Server}}_{{IName}}.json"

    -
      ignore_errors: true
      name: "find no of Tomcat Instance available on the Server"
      copy:
        src: "{{ WORKSPACE }}/instance/"
        dest: /example/{{IName}}
        group: "{{IGID}}"
        owner: "{{IUID}}"
        mode: 0755
    -
      name: Deliver configuration files for tomcat
      template: src={{ item.src }} dest={{ item.dest }} backup=yes
      with_items:
          - { src: 'server.xml.j2', dest: '/example/{{IName}}/conf/server.xml' }
          - { src: 'set_env.sh.j2', dest: '/example/{{IName}}/scripts/set_env.sh' }
</code>```

thanks in advance

答:
You need set_fact:

```<code>- set_fact:
    HTPN: "{{ tomcat_no | int * 100 + 8080 }}"
    SHPN: "{{ tomcat_no | int * 100 + 8005 }}"
    SSPN: "{{ tomcat_no | int * 100 + 8043 }}"
    AJPN: "{{ tomcat_no | int * 100 + 8009 }}"
  vars:
    tomcat_no: "{{ Tomcat_Instance_no.stdout }}"
</code>```

I also defined tomcat_no alias to use in set_fact task to reduce typing.

Body:
i am new to ansible world. below is my ansible playbook and in that before applying template value for tomcat port. i am tryiny to calculate the port based on exiting no of tomcat instance on the remote server.

how can get the value as an variable using local_action after running an shell?

-
  hosts: "{{Server}}"
  tasks:
    -
      ignore_errors: true
      name: "find no of Tomcat Instance available on the Server"
      register: Tomcat_Instance_no
      shell: "find /example -name tomcat-users.xml -type f -print | wc -l"

    - debug: var=Tomcat_Instance_no
    #- local_action: copy content="{{ Tomcat_Instance_no.stdout }}" dest="/tmp/{{Server}}_Tomcat_Instance_no"
    #- local_action: "shell sh define-tomcat-instance-port.sh {{Server}} {{IName}} {{ Tomcat_Instance_no.stdout }}"
    ****- local_action: "shell sh http_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8080))"
      register: HTPN
    - local_action: "shell sh shutdown_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8005))"
      register: SHPN
    - local_action: "shell sh https_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8043))"
      register: SSPN
    - local_action: "shell sh ajp_port=$(( {{ Tomcat_Instance_no.stdout }} * 100 + 8009))"
      register: AJPN**

    #-
      #name: bare include
      #include_vars: "{{Server}}_{{IName}}.json"

    -
      ignore_errors: true
      name: "find no of Tomcat Instance available on the Server"
      copy:
        src: "{{ WORKSPACE }}/instance/"
        dest: /example/{{IName}}
        group: "{{IGID}}"
        owner: "{{IUID}}"
        mode: 0755
    -
      name: Deliver configuration files for tomcat
      template: src={{ item.src }} dest={{ item.dest }} backup=yes
      with_items:
          - { src: 'server.xml.j2', dest: '/example/{{IName}}/conf/server.xml' }
          - { src: 'set_env.sh.j2', dest: '/example/{{IName}}/scripts/set_env.sh' }

thanks in advance

Body:
You need set_fact:

- set_fact:
    HTPN: "{{ tomcat_no | int * 100 + 8080 }}"
    SHPN: "{{ tomcat_no | int * 100 + 8005 }}"
    SSPN: "{{ tomcat_no | int * 100 + 8043 }}"
    AJPN: "{{ tomcat_no | int * 100 + 8009 }}"
  vars:
    tomcat_no: "{{ Tomcat_Instance_no.stdout }}"

I also defined tomcat_no alias to use in set_fact task to reduce typing.


问:
set column format type as date or time using HSSFSheet
I want to set my column Mobile_Time as time / Date time type column.
I have tried

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        DAO d0 = new DAO();
        Map<String, String> AllUsermap = new HashMap<String, String>();
        AllUsermap = d0.colleagueMap(Integer.parseInt(request.getParameter("lid")), request.getParameter("ltype"));
        String date = request.getParameter("date");

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition",
                "attachment; filename=All Employees Tracking Report [Date]:" + date + ".xls");
        Workbook workbook = new HSSFWorkbook();

        Font font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        CellStyle HeaderStyle = workbook.createCellStyle();
        HeaderStyle.setFont(font);

        for (String userK : AllUsermap.keySet()) {
            String userinfo[] = userK.split("-");
            String userinfoval[] = AllUsermap.get(userK).split("-");

            if (userinfo.length == 2 && userinfoval.length == 3) {
                Sheet sheet = workbook.createSheet(userinfoval[0]);

                // header
                Row row = sheet.createRow(0);
                Cell serial = row.createCell(0);
                serial.setCellValue("#");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(1);
                 serial.setCellValue("LOCATION");
                 serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(2);
                 serial.setCellValue("DISTANCE");
                 serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(3);
                serial.setCellValue("BATTERY");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(4);
                serial.setCellValue("SPEED");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(5);
                serial.setCellValue("GPS_ACCURACY");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(6);
                serial.setCellValue("STATUS");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(7);
                 serial.setCellType(1);
                serial.setCellValue("MOBILE_TIME");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(8);
                serial.setCellValue("SPEED");
                serial.setCellStyle(HeaderStyle);

                // End Header

                List<DailyReport> adr = new ArrayList<DailyReport>();
                adr = d0.seletspecificdailyreport(Integer.parseInt(userinfo[0]), date, userinfo[1]);
                if (adr.size() > 0) {
                    List<DailyReportDetails> adlrd = new ArrayList<DailyReportDetails>();
                    adlrd = d0.seletdailyreportdetails(adr.get(0).getIdDailyReport());
                    int i = 1;
                    for (DailyReportDetails drd : adlrd) {
                        row = sheet.createRow(i);
                        Cell cell = row.createCell(0);
                        cell.setCellValue(i);

                        cell = row.createCell(1);
                        cell.setCellValue(drd.getLocation());

                        cell = row.createCell(2);
                        cell.setCellValue(drd.getDistance());

                        cell = row.createCell(3);
                        cell.setCellValue(drd.getBattery());

                        cell = row.createCell(4);
                        cell.setCellValue(drd.getSpeed());

                        cell = row.createCell(5);
                        cell.setCellValue(drd.getAccuracy());

                        cell = row.createCell(6);
                        cell.setCellValue(drd.getOffline() == 1 ? "ONLINE" : "OFFLINE");

                        cell = row.createCell(7);
                        cell.setCellValue(drd.getMobiletime());

                        cell = row.createCell(8);
                        cell.setCellValue(userinfoval[2]);
                        i++;
                    }
                }
            }
        }

        workbook.write(response.getOutputStream()); // Write workbook to
                                                    // response.
        workbook.close();

    }
</code>```

The upper servelet writing xcel properly but Mobile time is not in time or date format in xcel

I also have tried to put  line for  mobile_time column serial .

```<code>serial = row.createCell(7);
                    serial.setCellType(HSSFCell.LAST_COLUMN_NUMBER);
                    serial.setCellValue("MOBILE_TIME");
                    serial.setCellStyle(HeaderStyle);
</code>```

and also tried the below line at the of generating row

```<code>cell = row.createCell(7);

                    try {
                        cell.setCellValue(new SimpleDateFormat("HH:mm:ss").parse(drd.getMobiletime()));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
</code>```

But still mobile_time column is in character format .What is the proper solution?

答:
You can do something like this : </p>

```<code> Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);

// Create a cell and put a date value in it.  The first cell is not styled
// as a date.
Cell cell = row.createCell(0);
cell.setCellValue(new Date());

// we style the second cell as a date (and time).  It is important to
// create a new cell style from the workbook otherwise you can end up
// modifying the built in style and effecting not only this cell but other cells.
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

//you can also set date as java.util.Calendar
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
</code>```

Body:
I want to set my column Mobile_Time as time / Date time type column.
I have tried

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        DAO d0 = new DAO();
        Map<String, String> AllUsermap = new HashMap<String, String>();
        AllUsermap = d0.colleagueMap(Integer.parseInt(request.getParameter("lid")), request.getParameter("ltype"));
        String date = request.getParameter("date");

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition",
                "attachment; filename=All Employees Tracking Report [Date]:" + date + ".xls");
        Workbook workbook = new HSSFWorkbook();

        Font font = workbook.createFont();
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        CellStyle HeaderStyle = workbook.createCellStyle();
        HeaderStyle.setFont(font);

        for (String userK : AllUsermap.keySet()) {
            String userinfo[] = userK.split("-");
            String userinfoval[] = AllUsermap.get(userK).split("-");

            if (userinfo.length == 2 && userinfoval.length == 3) {
                Sheet sheet = workbook.createSheet(userinfoval[0]);

                // header
                Row row = sheet.createRow(0);
                Cell serial = row.createCell(0);
                serial.setCellValue("#");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(1);
                 serial.setCellValue("LOCATION");
                 serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(2);
                 serial.setCellValue("DISTANCE");
                 serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(3);
                serial.setCellValue("BATTERY");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(4);
                serial.setCellValue("SPEED");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(5);
                serial.setCellValue("GPS_ACCURACY");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(6);
                serial.setCellValue("STATUS");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(7);
                 serial.setCellType(1);
                serial.setCellValue("MOBILE_TIME");
                serial.setCellStyle(HeaderStyle);

                 serial = row.createCell(8);
                serial.setCellValue("SPEED");
                serial.setCellStyle(HeaderStyle);

                // End Header

                List<DailyReport> adr = new ArrayList<DailyReport>();
                adr = d0.seletspecificdailyreport(Integer.parseInt(userinfo[0]), date, userinfo[1]);
                if (adr.size() > 0) {
                    List<DailyReportDetails> adlrd = new ArrayList<DailyReportDetails>();
                    adlrd = d0.seletdailyreportdetails(adr.get(0).getIdDailyReport());
                    int i = 1;
                    for (DailyReportDetails drd : adlrd) {
                        row = sheet.createRow(i);
                        Cell cell = row.createCell(0);
                        cell.setCellValue(i);

                        cell = row.createCell(1);
                        cell.setCellValue(drd.getLocation());

                        cell = row.createCell(2);
                        cell.setCellValue(drd.getDistance());

                        cell = row.createCell(3);
                        cell.setCellValue(drd.getBattery());

                        cell = row.createCell(4);
                        cell.setCellValue(drd.getSpeed());

                        cell = row.createCell(5);
                        cell.setCellValue(drd.getAccuracy());

                        cell = row.createCell(6);
                        cell.setCellValue(drd.getOffline() == 1 ? "ONLINE" : "OFFLINE");

                        cell = row.createCell(7);
                        cell.setCellValue(drd.getMobiletime());

                        cell = row.createCell(8);
                        cell.setCellValue(userinfoval[2]);
                        i++;
                    }
                }
            }
        }

        workbook.write(response.getOutputStream()); // Write workbook to
                                                    // response.
        workbook.close();

    }

The upper servelet writing xcel properly but Mobile time is not in time or date format in xcel

I also have tried to put  line for  mobile_time column serial .

serial = row.createCell(7);
                    serial.setCellType(HSSFCell.LAST_COLUMN_NUMBER);
                    serial.setCellValue("MOBILE_TIME");
                    serial.setCellStyle(HeaderStyle);

and also tried the below line at the of generating row

cell = row.createCell(7);

                    try {
                        cell.setCellValue(new SimpleDateFormat("HH:mm:ss").parse(drd.getMobiletime()));
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

But still mobile_time column is in character format .What is the proper solution?

Body:
You can do something like this :

 Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);

// Create a cell and put a date value in it.  The first cell is not styled
// as a date.
Cell cell = row.createCell(0);
cell.setCellValue(new Date());

// we style the second cell as a date (and time).  It is important to
// create a new cell style from the workbook otherwise you can end up
// modifying the built in style and effecting not only this cell but other cells.
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

//you can also set date as java.util.Calendar
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();


问:
C# Databind question
OK, So Im fairly new to Web apps, been doing Windows app for a while in VB but Im switching to C# for web apps. Ok so I have a textbox and I have a SQLDataSource called SQLDataSource1. How in the world do I bind the source to the textbox so when it loads it will populate it?

Can someone give me some examples?

Ive tried the following,

```<code>Label1.Text = SqlDataSource1.SelectParameters.ToString();
</code>```

But I get something other than the value of the SQLDataSource. I get this:  System.Web.UI.WebControls.SqlDataSource

Thanks

答: One way is have your controls in a FormView or DetailsView, then set the DataSourceID of the FormView to the SqlDataSource and in your controls you bind them like so: asp:Label id=... Text='<%# DataBinder.Eval(Container.DataItem, "MyFieldName") %>' />, then on your OnInit of the page you can call MyFormView.DataBind();</p>

ContentLicense: CC BY-SA 2.5

Title: C# Databind question

Body:
OK, So Im fairly new to Web apps, been doing Windows app for a while in VB but Im switching to C# for web apps. Ok so I have a textbox and I have a SQLDataSource called SQLDataSource1. How in the world do I bind the source to the textbox so when it loads it will populate it?

Can someone give me some examples?

Ive tried the following,

Label1.Text = SqlDataSource1.SelectParameters.ToString();

But I get something other than the value of the SQLDataSource. I get this:  System.Web.UI.WebControls.SqlDataSource

Thanks


问:
return value inside db function on res render
i want make a helper and will be used in my view (pug), so i send a function as data to the view file, but the problem is, my helper / passed function wont return a value or == undefined in my view, pug, thanks

```<code>    app.get('/admin/pengguna', function(req,res){
    db.all("SELECT * FROM main_posts WHERE wdyw='2'", function(err, rows) {
        //var r = db.all("SELECT * FROM main_posts WHERE wdyw='1' AND ")
        if (!err) {
            res.render('admin/pengguna', {
                path: req.path,
                pengguna : rows,
                useringroup: function(w) {
                    db.all("SELECT * FROM main_posts WHERE wdyw='1' AND identity= $w", { $w: w }, function(err, result){
                        return result.lenght;
                    })
                }
            })
        }
    })
})
</code>```

答:
Wait for the db to return the data and then render the view. Your view can not make a call directly to db. This is why we use MVC (Model View Controller). You need to fetch all the data in your controller and then pass it to view.

You will need to use something like this,

```<code>app.get('/admin/pengguna', function(req,res){
    db.all("SELECT * FROM main_posts WHERE wdyw='2'", function(err, rows) {
        //var r = db.all("SELECT * FROM main_posts WHERE wdyw='1' AND ")
        if (!err) {
            db.all("SELECT * FROM main_posts WHERE wdyw='1' AND identity= $w", { $w: w }, function(err, result){
                res.render('admin/pengguna', {
                    path: req.path,
                    pengguna : rows,
                    useringroup: result.length
                })
            })

        }
    })
})
</code>```

Also you will need to adjust your code for w. Before you were getting it from the function you passed to the view. You'll need to get its value by any other method or modify the query.

Body:
i want make a helper and will be used in my view (pug), so i send a function as data to the view file, but the problem is, my helper / passed function wont return a value or == undefined in my view, pug, thanks

    app.get('/admin/pengguna', function(req,res){
    db.all("SELECT * FROM main_posts WHERE wdyw='2'", function(err, rows) {
        //var r = db.all("SELECT * FROM main_posts WHERE wdyw='1' AND ")
        if (!err) {
            res.render('admin/pengguna', {
                path: req.path,
                pengguna : rows,
                useringroup: function(w) {
                    db.all("SELECT * FROM main_posts WHERE wdyw='1' AND identity= $w", { $w: w }, function(err, result){
                        return result.lenght;
                    })
                }
            })
        }
    })
})

Body:
Wait for the db to return the data and then render the view. Your view can not make a call directly to db. This is why we use MVC (Model View Controller). You need to fetch all the data in your controller and then pass it to view.

You will need to use something like this,

app.get('/admin/pengguna', function(req,res){
    db.all("SELECT * FROM main_posts WHERE wdyw='2'", function(err, rows) {
        //var r = db.all("SELECT * FROM main_posts WHERE wdyw='1' AND ")
        if (!err) {
            db.all("SELECT * FROM main_posts WHERE wdyw='1' AND identity= $w", { $w: w }, function(err, result){
                res.render('admin/pengguna', {
                    path: req.path,
                    pengguna : rows,
                    useringroup: result.length
                })
            })

        }
    })
})

Also you will need to adjust your code for w. Before you were getting it from the function you passed to the view. You'll need to get its value by any other method or modify the query.


问:
How to join two queries with unequal results (different columns and rows) in PostgreSQL/Postgis
In my PostgreSQL/PostGIS database, I have two queries with different results.

Query1:

```<code>With buffer as
(
    SELECT   gid,
             (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
    FROM     cp
    group by gid, geom --cp being point layer with one row
    UNION ALL
    SELECT   gid,
             geom
    FROM     cp        --cp being point layer with only one row
)
SELECT   gid,
         generate_series(1,12) id,
         (ST_Dump(ST_DelaunayTriangles(ST_Collect(geom),0, 0))).geom as geom
FROM     buffer
group by gid
order by gid, id
</code>```

returns three columns (gid, id, geom) with 12 rows. While, query2:

```<code>With buffer as
(
    SELECT   gid,
             (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
    FROM     cp
    group by gid, geom --cp being the same point layer
    UNION ALL
    SELECT   gid,
             geom
    FROM     cp        -- cp being the same point layer
)
Select distinct geom as pts,
       gid
from   buffer
</code>```

returns two columns (pts, gid) with 13 rows. I want to join these two queries on the basis of gid as I want to automate this process for large number of points. As I recall, first query returns 12 segments/rows (triangles/pie-like wedges geometry) around point layer (cp having gid = 1). The second query returns outer vertices (13 points) of these triangles. I need to join these queries most efficiently such that the desired output should yield four columns like:

```<code> gid, id, geom, pts
 1    1   xxx   yyy
 1    2   xxx   yyy
 1    3   xxx   yyy
 1    4   xxx   yyy
 1    5   xxx   yyy
 1    6   xxx   yyy
 1    7   xxx   yyy
 1    8   xxx   yyy
 1    9   xxx   yyy
 1    10  xxx   yyy
 1    11  xxx   yyy
 1    12  xxx   yyy
 1    13  NULL  yyy
</code>```

Can anyone help me to join unequal results of above two queries? Any pointers will be highly appreciated.

答:
try such (I just CTE your statements and outer join them):</p>

```<code>with a as (
    With buffer as
    (
        SELECT   gid,
                 (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
        FROM     cp
        group by gid, geom --cp being point layer with one row
        UNION ALL
        SELECT   gid,
                 geom
        FROM     cp        --cp being point layer with only one row
    )
    SELECT   gid,
             generate_series(1,12) id,
             (ST_Dump(ST_DelaunayTriangles(ST_Collect(geom),0, 0))).geom as geom
    FROM     buffer
    group by gid
    order by gid, id
)
, b as (

    With buffer as
    (
        SELECT   gid,
                 (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
        FROM     cp
        group by gid, geom --cp being the same point layer
        UNION ALL
        SELECT   gid,
                 geom
        FROM     cp        -- cp being the same point layer
    )
    Select distinct geom as pts,
           gid
           , row_number() over () as id
    from   buffer
)
select *
from b
left outer join a on b.gid = a.gid and b.id = a.id
;
</code>```

Body:
In my PostgreSQL/PostGIS database, I have two queries with different results.

Query1:

With buffer as
(
    SELECT   gid,
             (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
    FROM     cp
    group by gid, geom --cp being point layer with one row
    UNION ALL
    SELECT   gid,
             geom
    FROM     cp        --cp being point layer with only one row
)
SELECT   gid,
         generate_series(1,12) id,
         (ST_Dump(ST_DelaunayTriangles(ST_Collect(geom),0, 0))).geom as geom
FROM     buffer
group by gid
order by gid, id

returns three columns (gid, id, geom) with 12 rows. While, query2:

With buffer as
(
    SELECT   gid,
             (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
    FROM     cp
    group by gid, geom --cp being the same point layer
    UNION ALL
    SELECT   gid,
             geom
    FROM     cp        -- cp being the same point layer
)
Select distinct geom as pts,
       gid
from   buffer

returns two columns (pts, gid) with 13 rows. I want to join these two queries on the basis of gid as I want to automate this process for large number of points. As I recall, first query returns 12 segments/rows (triangles/pie-like wedges geometry) around point layer (cp having gid = 1). The second query returns outer vertices (13 points) of these triangles. I need to join these queries most efficiently such that the desired output should yield four columns like:

 gid, id, geom, pts
 1    1   xxx   yyy
 1    2   xxx   yyy
 1    3   xxx   yyy
 1    4   xxx   yyy
 1    5   xxx   yyy
 1    6   xxx   yyy
 1    7   xxx   yyy
 1    8   xxx   yyy
 1    9   xxx   yyy
 1    10  xxx   yyy
 1    11  xxx   yyy
 1    12  xxx   yyy
 1    13  NULL  yyy

Can anyone help me to join unequal results of above two queries? Any pointers will be highly appreciated.

Body:
try such (I just CTE your statements and outer join them):

with a as (
    With buffer as
    (
        SELECT   gid,
                 (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
        FROM     cp
        group by gid, geom --cp being point layer with one row
        UNION ALL
        SELECT   gid,
                 geom
        FROM     cp        --cp being point layer with only one row
    )
    SELECT   gid,
             generate_series(1,12) id,
             (ST_Dump(ST_DelaunayTriangles(ST_Collect(geom),0, 0))).geom as geom
    FROM     buffer
    group by gid
    order by gid, id
)
, b as (

    With buffer as
    (
        SELECT   gid,
                 (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
        FROM     cp
        group by gid, geom --cp being the same point layer
        UNION ALL
        SELECT   gid,
                 geom
        FROM     cp        -- cp being the same point layer
    )
    Select distinct geom as pts,
           gid
           , row_number() over () as id
    from   buffer
)
select *
from b
left outer join a on b.gid = a.gid and b.id = a.id
;


问:
Scala function, unexpected behaviour
I have the following Scala code snippet:

(1 to 10).foreach(a => (1 to 100 by 3).toList.count(b => b % a == 0))

which, I would expect to behave like the following:

Create a list of multiple of 3 less than 100

For each item in the list previously generated, count how many multiples of 1, 2, 3... 10 there are

But, when I run the snippet, I get an empty list. What am I doing wrong?

Thanks for your help!

答:
The behavior is totally expect when using foreach.

foreach takes a procedure — a function with a result type Unit — as the right operand. It simply applies the procedure to each List element. The result of the operation is again Unit; no list of results is assembled.

It's typically used for its side effects — something like printing or saving into a database, etc.

You ought using map instead :

```<code>scala> (1 to 10).map(a => (1 to 100 by 3).toList.count(b => b % a == 0))
// res3: scala.collection.immutable.IndexedSeq[Int] = Vector(34, 17, 0, 9, 7, 0, 5, 4, 0, 4)
</code>```

Title: Scala function, unexpected behaviour

Body:
The behavior is totally expect when using foreach.

foreach takes a procedure — a function with a result type Unit — as the right operand. It simply applies the procedure to each List element. The result of the operation is again Unit; no list of results is assembled.

It's typically used for its side effects — something like printing or saving into a database, etc.

You ought using map instead :

scala> (1 to 10).map(a => (1 to 100 by 3).toList.count(b => b % a == 0))
// res3: scala.collection.immutable.IndexedSeq[Int] = Vector(34, 17, 0, 9, 7, 0, 5, 4, 0, 4)


答:
MdiChildren is just an array, which represents the current forms, which are the Mdi Childs of the dialog. You need to load the MDI child into the parent.

Something like this:

```<code>addStudent newStudentForm = new addStudent();
newStudentForm.MdiParent = this;
newStudentForm.Show();
</code>```

Title: Property or indexer 'Form.MdiChildren' cannot be assigned to -- it is read only

Body:
MdiChildren is just an array, which represents the current forms, which are the Mdi Childs of the dialog. You need to load the MDI child into the parent.

Something like this:

addStudent newStudentForm = new addStudent();
newStudentForm.MdiParent = this;
newStudentForm.Show();


问:
Getting results via WSDL - C#
I'm trying to add this Header class to my SOAP request but can't see how.  The Header class was given to me as part of the implementation but there's no instructions on how to use it and I'm a bit stuck - I've not used WSDL and web services before.  I'm sure the answer must be blindingly easy but I just can't see it.

Header Requirements

```<code><soapenv:Header>
  <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
    <wsse:UsernameToken wsu:Id="UsernameToken-19" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
      <wsse:Username>##USERNAME##</wsse:Username>
      <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">##PASSWORD##</wsse:Password>
     </wsse:UsernameToken>
  </wsse:Security>
</soapenv:Header>
</code>```

Header class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace Consuming
{
    public class SecurityHeader : MessageHeader
    {
        private readonly UsernameToken _usernameToken;

        public SecurityHeader(string id, string username, string password)
        {
            _usernameToken = new UsernameToken(id, username, password);
        }

        public override string Name
        {
            get { return "Security"; }
        }

        public override string Namespace
        {
            get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
        }

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
            serializer.Serialize(writer, _usernameToken);
        }
    }

    [XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
    public class UsernameToken
    {
        public UsernameToken()
        {
        }

        public UsernameToken(string id, string username, string password)
        {
            Id = id;
            Username = username;
            Password = new Password() { Value = password };
        }

        [XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
        public string Id { get; set; }

        [XmlElement]
        public string Username { get; set; }

        [XmlElement]
        public Password Password { get; set; }
    }

    public class Password
    {
        public Password()
        {
            Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
        }

        [XmlAttribute]
        public string Type { get; set; }

        [XmlText]
        public string Value { get; set; }
    }
}
</code>```

Code

```<code>var mySoapHeader = new SecurityHeader("ID","Username","password");
var client = new GroupWebServiceClient(); // Created from Add Web Reference

client.?????? = mySoapHeader;// I can't see how to add the Header to the request

var response = new groupNameListV1();
response = client.getAllDescendants("6335");//This needs the header - omitting gives "An error was discovered processing the <wsse:Security> header"
</code>```

EDIT

I figured it out in the end, turns out it was pretty easy - Adding the solution in case anyone else finds it useful

```<code>using (new OperationContextScope(client.InnerChannel))
    {
         OperationContext.Current.OutgoingMessageHeaders.Add(
                    new SecurityHeader("ID", "USER", "PWD"));

         var response = new groupNameListV1();
         response = client.getAllDescendants("cng_so_6553");
         //other code
    }
</code>```

答:
Generally you need to add behavior extension.

Create a class that implements IClientMessageInspector. In the BeforeSendRequest method, add your custom header to the outgoing message. It might look something like this:

```<code>public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,  System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
    httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
    if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
    {
        httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
    }
}
else
{
    httpRequestMessage = new HttpRequestMessageProperty();
    httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
    request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}
</code>```

Then create an endpoint behavior that applies the message inspector to the client runtime. You can apply the behavior via an attribute or via configuration using a behavior extension element.

Here is a example of how to add an HTTP user-agent header to all request messages. I used this in a few of my clients.

Is this what you had in mind?

Title: Getting results via WSDL - C#

Body:
I'm trying to add this Header class to my SOAP request but can't see how.  The Header class was given to me as part of the implementation but there's no instructions on how to use it and I'm a bit stuck - I've not used WSDL and web services before.  I'm sure the answer must be blindingly easy but I just can't see it.

Header Requirements

<soapenv:Header>
  <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
    <wsse:UsernameToken wsu:Id="UsernameToken-19" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
      <wsse:Username>##USERNAME##</wsse:Username>
      <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">##PASSWORD##</wsse:Password>
     </wsse:UsernameToken>
  </wsse:Security>
</soapenv:Header>

Header class

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.Web;
using System.Xml;
using System.Xml.Serialization;

namespace Consuming
{
    public class SecurityHeader : MessageHeader
    {
        private readonly UsernameToken _usernameToken;

        public SecurityHeader(string id, string username, string password)
        {
            _usernameToken = new UsernameToken(id, username, password);
        }

        public override string Name
        {
            get { return "Security"; }
        }

        public override string Namespace
        {
            get { return "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; }
        }

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(UsernameToken));
            serializer.Serialize(writer, _usernameToken);
        }
    }

    [XmlRoot(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd")]
    public class UsernameToken
    {
        public UsernameToken()
        {
        }

        public UsernameToken(string id, string username, string password)
        {
            Id = id;
            Username = username;
            Password = new Password() { Value = password };
        }

        [XmlAttribute(Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")]
        public string Id { get; set; }

        [XmlElement]
        public string Username { get; set; }

        [XmlElement]
        public Password Password { get; set; }
    }

    public class Password
    {
        public Password()
        {
            Type = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
        }

        [XmlAttribute]
        public string Type { get; set; }

        [XmlText]
        public string Value { get; set; }
    }
}

Code

var mySoapHeader = new SecurityHeader("ID","Username","password");
var client = new GroupWebServiceClient(); // Created from Add Web Reference

client.?????? = mySoapHeader;// I can't see how to add the Header to the request

var response = new groupNameListV1();
response = client.getAllDescendants("6335");//This needs the header - omitting gives "An error was discovered processing the <wsse:Security> header"

EDIT

I figured it out in the end, turns out it was pretty easy - Adding the solution in case anyone else finds it useful

using (new OperationContextScope(client.InnerChannel))
    {
         OperationContext.Current.OutgoingMessageHeaders.Add(
                    new SecurityHeader("ID", "USER", "PWD"));

         var response = new groupNameListV1();
         response = client.getAllDescendants("cng_so_6553");
         //other code
    }

Body:
Generally you need to add behavior extension.

Create a class that implements IClientMessageInspector. In the BeforeSendRequest method, add your custom header to the outgoing message. It might look something like this:

public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request,  System.ServiceModel.IClientChannel channel)
{
HttpRequestMessageProperty httpRequestMessage;
object httpRequestMessageObject;
if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
{
    httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
    if (string.IsNullOrEmpty(httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER]))
    {
        httpRequestMessage.Headers[USER_AGENT_HTTP_HEADER] = this.m_userAgent;
    }
}
else
{
    httpRequestMessage = new HttpRequestMessageProperty();
    httpRequestMessage.Headers.Add(USER_AGENT_HTTP_HEADER, this.m_userAgent);
    request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
}
return null;
}

Then create an endpoint behavior that applies the message inspector to the client runtime. You can apply the behavior via an attribute or via configuration using a behavior extension element.

Here is a example of how to add an HTTP user-agent header to all request messages. I used this in a few of my clients.

Is this what you had in mind?


问:
How do I find the caller of a method using stacktrace or reflection?
I need to find the caller of a method. Is it possible using stacktrace or reflection?</p>

答:
Oneliner:

```<code>Thread.currentThread().getStackTrace()[2].getMethodName()
</code>```

Note that you might need to replace the 2 with 1.

OwnerDisplayName: Sathish

Body:
Oneliner:

Thread.currentThread().getStackTrace()[2].getMethodName()

Note that you might need to replace the 2 with 1.


问:
How to input fetch in a function, got Uncaught SyntaxError: Invalid or unexpected token on web browser
I'm new in php query javascript code, I want to make a function for

```<code>while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
            {
                echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
            }
</code>```

so I can use it in many area, but I got this error:

Uncaught SyntaxError: Invalid or unexpected token in the web browser

This is web browser (source) error: web browser(source) error

This is my code :

```<code>`$resultQueryAntenna = mysql_query($queryAntenna) or die(mysql_error()."`[".$queryAntenna."]");

function test1(){
     while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
        {
            echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
        }
}
<script>

$(document).ready(function(){
      var i=1;
      $('#add').click(function(){
           i++;
           $('#dynamic_field').append('<tr id="row'+i+'" valign="middle" style="height:45px;">\
                <td width="10%" style="text-align:right; padding-right:20px;">\
                    <select class="form-control" id="type" name="type" onchange="">\
                      <?php
                            while ($rowType = mysql_fetch_array($resultQueryType))
                            {
                                echo "<option value=\'".$rowType['type_name']."\'>".$rowType['type_name']." </option>";
                            }
                        ?>\
                    </select>\
                </td>\
                <td width="35%">\
                <select class="form-control" id="antenna" name="antenna" onchange="">\
                      <option value="">-- None --</option>\
                      <?php test1();?>\
                </select>\
                </td>\
                .........................................
</code>```

Did I do something wrong? My code inside the function works if I don't put them in a function.

答:
Could you try declaring i variable inside the function. It might work I'm not sure,

I can't comment as I don't have 50 reputations.

Body:
I'm new in php query javascript code, I want to make a function for

while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
            {
                echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
            }

so I can use it in many area, but I got this error:

Uncaught SyntaxError: Invalid or unexpected token in the web browser

This is web browser (source) error: web browser(source) error

This is my code :

`$resultQueryAntenna = mysql_query($queryAntenna) or die(mysql_error()."`[".$queryAntenna."]");

function test1(){
     while ($rowAnt = mysql_fetch_array($resultQueryAntenna))
        {
            echo "<option value=\'".$rowAnt['Antenna']."\'>".$rowAnt['Antenna']." </option>";
        }
}


问:
Image does not display on Heroku
I have two images on a static web page in a Ruby on Rails web application. Both images are in the same place:

```<code>/app/assets/images
</code>```

The image tag for both is generated in the same way, barring some attributes:

```<code><%= image_tag("logo.png", alt: "Logo", width: 150) %>

<%= image_tag("image.jpeg", alt: "image", class: "img-responsive") %>
</code>```

Both work fine on the local server, but when I push to production, only the first image displays. The source shows the tag for the second image is not being processed correctly:

```<code><img alt="Logo" width="150" src="/assets/logo-9e9dd9c19ef18b3ef26e23f11d73a8817af6cea78a5d9e1a34691d591a780987.png" />

<img alt="image" class="img-responsive" src="/images/image.jpeg" />
</code>```

I don't understand why one works and the other doesn't?

In terms of context, the first image is PNG and part of the layout, rendered in application.html.erb. The second is part of the page view yielded into application.html.erb. Does that make a difference?

Any pointers in the right direction? Thanks for your help.

Regards,

Jonathan

答:
Seems like you are not precompiling jpeg.

Make sure you have this line in config/initializers/assets.rb

```<code>Rails.application.config.assets.precompile += %w( *.jpg *.jpeg some-other.css some-other.js)
</code>```

Title: Image does not display on Heroku

Body:
I have two images on a static web page in a Ruby on Rails web application. Both images are in the same place:

/app/assets/images

The image tag for both is generated in the same way, barring some attributes:

<%= image_tag("logo.png", alt: "Logo", width: 150) %>

<%= image_tag("image.jpeg", alt: "image", class: "img-responsive") %>

Both work fine on the local server, but when I push to production, only the first image displays. The source shows the tag for the second image is not being processed correctly:

I don't understand why one works and the other doesn't?

In terms of context, the first image is PNG and part of the layout, rendered in application.html.erb. The second is part of the page view yielded into application.html.erb. Does that make a difference?

Any pointers in the right direction? Thanks for your help.

Regards,

Jonathan

Body:
Seems like you are not precompiling jpeg.

Make sure you have this line in config/initializers/assets.rb

Rails.application.config.assets.precompile += %w( *.jpg *.jpeg some-other.css some-other.js)