问:
Access Child object in Custom element
I am creating a custom object which extends a table cell object.
The new cell object contains an input text box.

Here is my code:

```<code><html>
    <head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
        //table
        class DataTable extends HTMLTableElement {
          constructor() {
            super()
            console.info('data-table created')
          }
        }
        customElements.define('data-table',
                            DataTable,
                            {
                              extends: 'table'
                            });

        //cell
        class DataCell extends  HTMLTableCellElement {
          connectedCallback() {
            console.info('cell connected')
            if (typeof this.renderContent === 'function')
              this.renderContent()
          }
          renderContent() {
            console.info('data-string render')
            this.textBox= document.createElement("input");
            this.textBox.type="text";
            this.appendChild(this.textBox);

          }
          set value(v)
          {
            this.textBox.value=v;
          }
          get value()
          {
            return this.textBox.value;
          }
        }
        customElements.define('data-string',
                            DataCell,
                            {
                                extends: 'td'
                            });

        $( document ).ready(function(){
                var t=new DataTable();
                var row=t.insertRow(t.rows);
                var cell=new DataCell();

                row.appendChild(cell);
                cell.value="gfg";
                $(document.body).append(t);
            });
    </script>
    </head>
    <body>
        <h4>Test Table Extension v1</h4>

    </body>
</html>
</code>```

I would like to add a "value" attribute to the new cell.
I got "Cannot set property 'value' of undefined" when I set the value to the text box. In the "set value(v)" function, "this" is refer to document, not the cell, that is the problem.

答:
You have to create the textBox-input before you access it with .value. Currently it is not created/assigned when you call .value. A Solution is to do the creation of the input-element inside the constructor of the Cell:

//table
class DataTable extends HTMLTableElement {
    constructor() {
        super();
        console.info('data-table created');
    }
}
customElements.define('data-table',
    DataTable, {
        extends: 'table'
    });

//cell
class DataCell extends HTMLTableCellElement {
    constructor() {
        super();
        this.textBox = document.createElement("input");
        this.textBox.type = "text";
        console.info('data-cell created');
    }
    connectedCallback() {
        console.info('cell connected')
        if (typeof this.renderContent === 'function')
            this.renderContent()
    }
    renderContent() {
        console.info('data-string render')
        this.appendChild(this.textBox);

    }
    set value(v) {
        this.textBox.value = v;
    }
    get value() {
        return this.textBox.value;
    }
}
customElements.define('data-string',
    DataCell, {
        extends: 'td'
    });

$(document).ready(function() {
    var t = new DataTable();
    var row = t.insertRow(t.rows);
    var cell = new DataCell();

    row.appendChild(cell);
    cell.value = "gfg";
    $(document.body).append(t);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h4>Test Table Extension v1</h4></code>```

Title: Access Child object in Custom element

Body:
I am creating a custom object which extends a table cell object.
The new cell object contains an input text box.

Here is my code:

Test Table Extension v1

I would like to add a "value" attribute to the new cell.
I got "Cannot set property 'value' of undefined" when I set the value to the text box. In the "set value(v)" function, "this" is refer to document, not the cell, that is the problem.

Body:
You have to create the textBox-input before you access it with .value. Currently it is not created/assigned when you call .value. A Solution is to do the creation of the input-element inside the constructor of the Cell:

//table
class DataTable extends HTMLTableElement {
    constructor() {
        super();
        console.info('data-table created');
    }
}
customElements.define('data-table',
    DataTable, {
        extends: 'table'
    });

//cell
class DataCell extends HTMLTableCellElement {
    constructor() {
        super();
        this.textBox = document.createElement("input");
        this.textBox.type = "text";
        console.info('data-cell created');
    }
    connectedCallback() {
        console.info('cell connected')
        if (typeof this.renderContent === 'function')
            this.renderContent()
    }
    renderContent() {
        console.info('data-string render')
        this.appendChild(this.textBox);

    }
    set value(v) {
        this.textBox.value = v;
    }
    get value() {
        return this.textBox.value;
    }
}
customElements.define('data-string',
    DataCell, {
        extends: 'td'
    });

$(document).ready(function() {
    var t = new DataTable();
    var row = t.insertRow(t.rows);
    var cell = new DataCell();

    row.appendChild(cell);
    cell.value = "gfg";
    $(document.body).append(t);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h4>Test Table Extension v1</h4>


来源: stackexchange

问:
Spring Boot properties not loading 2.1.5
I have written a spring boot app to monitor jobs and have wired the configuration properties for the clients to call services in the job services. I am using a yml file called application-test.yml in src/test/resources. I have also set the active profiles when running the test to -Dspring.profiles.active='test' and spring says the active profile is test. However when I run the tests, the configuration properties host and path are always null. Here is my configuration file:

```<code>spring:
 profiles: test
</code>```

myservices:
  clients:

```<code>printservice:
  host: app/sms/appdev.com
  path: jobs/{jobId}

monitorNgService:
  host: app/monitor/appdev.com
  path: iqueue/jobs/{jobKey}/servers
</code>```

Here are my classes for the configurations:

```<code>@Configuration
@ConfigurationProperties(prefix="myservices.clients")
 class  PrintServiceProperties{
 String host;
 String path;
 }
</code>```

The other configuration class loads the second configuration in the yml file. It also has null for host and path. Here is that file;

```<code>   @Configuration
   @ConfigurationProperties(prefix="myservices.clients")
   class  MonitorNgServiceProperties{
      String host;
      String path;
   }
</code>```

I am injecting this class in a class that uses these properties but they are null

Here is the class

```<code>@Service

 @Import(MonitorNgServiceProperties)
   @Slf4j
   class MonitorService implements InitializingBean{
    @Autowired
    MonitorNgServiceProperties monitorNgService
</code>```

I have spent hours on this but can't figure out why the properties won't load. I'd be really grateful for help in resolving this issue

答:
The problem was that I was missing the last prefix:</p>

```<code> @ConfigurationProperties(prefix="myservices.clients.printservice")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have written a spring boot app to monitor jobs and have wired the configuration properties for the clients to call services in the job services. I am using a yml file called application-test.yml in src/test/resources. I have also set the active profiles when running the test to -Dspring.profiles.active='test' and spring says the active profile is test. However when I run the tests, the configuration properties host and path are always null. Here is my configuration file:

spring:
 profiles: test

myservices:
  clients:

printservice:
  host: app/sms/appdev.com
  path: jobs/{jobId}

monitorNgService:
  host: app/monitor/appdev.com
  path: iqueue/jobs/{jobKey}/servers

Here are my classes for the configurations:

@Configuration
@ConfigurationProperties(prefix="myservices.clients")
 class  PrintServiceProperties{
 String host;
 String path;
 }

The other configuration class loads the second configuration in the yml file. It also has null for host and path. Here is that file;

   @Configuration
   @ConfigurationProperties(prefix="myservices.clients")
   class  MonitorNgServiceProperties{
      String host;
      String path;
   }

I am injecting this class in a class that uses these properties but they are null

Here is the class

@Service

 @Import(MonitorNgServiceProperties)
   @Slf4j
   class MonitorService implements InitializingBean{
    @Autowired
    MonitorNgServiceProperties monitorNgService

I have spent hours on this but can't figure out why the properties won't load. I'd be really grateful for help in resolving this issue

Body:
The problem was that I was missing the last prefix:

 @ConfigurationProperties(prefix="myservices.clients.printservice")


问:
How would one sum the individual indexes within a single array in PHP?
No matter how much I look at the docs, I just cannot grasp adding (+) two arrays individual indexes together. Could someone please explain how I would achieve the below result?

Sample array:

```<code>array1 = [1,0,2,3,4];
array2 = [3,5,6,7,8];
</code>```

Expected Output:

```<code>[4, 5, 8, 10, 12]
</code>```

I tried

```<code>$arrSum = $array1 + $array2;
</code>```

But alas it wasn't the result I was looking for.

```<code>$arrSum Array
(
    [0] => 1
    [1] => 0
    [2] => 2
    [3] => 3
    [4] => 4
)
</code>```

答:
code

```<code><?php

// Sample array:
$array1 = [1,0,2,3,4];
$array2 = [3,5,6,7,8];

// Expected Output:
// [4, 5, 8, 10, 12]

function addArrays(array $array1, array $array2) : array
{
    $result = [];
    $counter = 0;

    //iterate over all values from array 1
    foreach($array1 as $key => $value) {

        //if in array 2 exists a value at the same key
        //as in array 1 that we iterate
        if (isset($array2[$key])) {
            //the sum is addition of the value
            //of array 1 and value of array 2 under
            //the same key
            $singleSum = $value + $array2[$key];

        } else {
            //array 2 does not have value
            //at the same key so the sum
            //is just a value of array 1
            $singleSum = $value;
        }

        //store sum in result array
        $result[$key] = $singleSum;

        //increment counter of processed
        //values in array 1
        $counter++;
    }

    $array2Count = count($array2);

    //if array 2 has more values than array 1
    if ($array2Count > $counter) {

        //there are some remaining values
        //in array 2 that havent been put
        //into result

        //start from value at position that you end
        //last time and iterate till the last
        //value of array 2
        for ($i = $counter; $i < $array2Count; $i++) {

            //just put that value to result array
            $result[] = $array2[$i];
        }
    }

    return $result;
}

echo "\n--- exammple 1 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2,3,4];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3,5,6,7,8];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 2 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3,5,6,7,8];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 3 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 4 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 5 ---\n";
echo "\n--- input array1 ---\n";
$array1 = [];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3,5];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 6 ---\n";
echo "\n--- input array1 ---\n";
$array1 = [];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);
</code>```

result

```<code>--- exammple 1 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
    [3] => 3
    [4] => 4
)

--- input array2 ---
Array
(
    [0] => 3
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 8
)

--- result ---
Array
(
    [0] => 4
    [1] => 5
    [2] => 8
    [3] => 10
    [4] => 12
)

--- exammple 2 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- input array2 ---
Array
(
    [0] => 3
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 8
)

--- result ---
Array
(
    [0] => 4
    [1] => 5
    [2] => 8
    [3] => 7
    [4] => 8
)

--- exammple 3 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- input array2 ---
Array
(
    [0] => 3
)

--- result ---
Array
(
    [0] => 4
    [1] => 0
    [2] => 2
)

--- exammple 4 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- input array2 ---
Array
(
)

--- result ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- exammple 5 ---

--- input array1 ---
Array
(
)

--- input array2 ---
Array
(
    [0] => 3
    [1] => 5
)

--- result ---
Array
(
    [0] => 3
    [1] => 5
)

--- exammple 6 ---

--- input array1 ---
Array
(
)

--- input array2 ---
Array
(
)

--- result ---
Array
(
)
</code>```

Body:
No matter how much I look at the docs, I just cannot grasp adding (+) two arrays individual indexes together. Could someone please explain how I would achieve the below result?

Sample array:

array1 = [1,0,2,3,4];
array2 = [3,5,6,7,8];

Expected Output:

[4, 5, 8, 10, 12]

I tried

$arrSum = $array1 + $array2;

But alas it wasn't the result I was looking for.

$arrSum Array
(
    [0] => 1
    [1] => 0
    [2] => 2
    [3] => 3
    [4] => 4
)

Body:
code

<?php

// Sample array:
$array1 = [1,0,2,3,4];
$array2 = [3,5,6,7,8];

// Expected Output:
// [4, 5, 8, 10, 12]

function addArrays(array $array1, array $array2) : array
{
    $result = [];
    $counter = 0;

    //iterate over all values from array 1
    foreach($array1 as $key => $value) {

        //if in array 2 exists a value at the same key
        //as in array 1 that we iterate
        if (isset($array2[$key])) {
            //the sum is addition of the value
            //of array 1 and value of array 2 under
            //the same key
            $singleSum = $value + $array2[$key];

        } else {
            //array 2 does not have value
            //at the same key so the sum
            //is just a value of array 1
            $singleSum = $value;
        }

        //store sum in result array
        $result[$key] = $singleSum;

        //increment counter of processed
        //values in array 1
        $counter++;
    }

    $array2Count = count($array2);

    //if array 2 has more values than array 1
    if ($array2Count > $counter) {

        //there are some remaining values
        //in array 2 that havent been put
        //into result

        //start from value at position that you end
        //last time and iterate till the last
        //value of array 2
        for ($i = $counter; $i < $array2Count; $i++) {

            //just put that value to result array
            $result[] = $array2[$i];
        }
    }

    return $result;
}

echo "\n--- exammple 1 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2,3,4];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3,5,6,7,8];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 2 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3,5,6,7,8];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 3 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 4 ---\n";

echo "\n--- input array1 ---\n";
$array1 = [1,0,2];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 5 ---\n";
echo "\n--- input array1 ---\n";
$array1 = [];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [3,5];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

echo "\n--- exammple 6 ---\n";
echo "\n--- input array1 ---\n";
$array1 = [];
print_r($array1);

echo "\n--- input array2 ---\n";
$array2 = [];
print_r($array2);

echo "\n--- result ---\n";
$result = addArrays($array1, $array2);
print_r($result);

result

--- exammple 1 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
    [3] => 3
    [4] => 4
)

--- input array2 ---
Array
(
    [0] => 3
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 8
)

--- result ---
Array
(
    [0] => 4
    [1] => 5
    [2] => 8
    [3] => 10
    [4] => 12
)

--- exammple 2 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- input array2 ---
Array
(
    [0] => 3
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 8
)

--- result ---
Array
(
    [0] => 4
    [1] => 5
    [2] => 8
    [3] => 7
    [4] => 8
)

--- exammple 3 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- input array2 ---
Array
(
    [0] => 3
)

--- result ---
Array
(
    [0] => 4
    [1] => 0
    [2] => 2
)

--- exammple 4 ---

--- input array1 ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- input array2 ---
Array
(
)

--- result ---
Array
(
    [0] => 1
    [1] => 0
    [2] => 2
)

--- exammple 5 ---

--- input array1 ---
Array
(
)

--- input array2 ---
Array
(
    [0] => 3
    [1] => 5
)

--- result ---
Array
(
    [0] => 3
    [1] => 5
)

--- exammple 6 ---

--- input array1 ---
Array
(
)

--- input array2 ---
Array
(
)

--- result ---
Array
(
)


问:
Get angular-cli to ng serve over HTTPS
The following doesn't seem to do anything.

```<code>ng serve --ssl true --ssl-key <key-path> --ssl-cert <cert-path>
</code>```

Creating the Certificate and key by providing them in the default ssl directory still does nothing.

It looks like ng server is completely ignoring the --ssl parameter and keeps saying NG Live Development Server is running on http://localhost:4200.

答:
Angular CLI 1.0.0+.

ng serve --ssl 1 --ssl-key {{key-path}} --ssl-cert {{cert-path}}

Angular CLI 6+

ng serve --ssl true --sslKey {{key-path}} --sslCert {{cert-path}}

Change the values in {{*-path}}, to the corresponding values.

Title: Get angular-cli to ng serve over HTTPS

Body:
The following doesn't seem to do anything.

ng serve --ssl true --ssl-key <key-path> --ssl-cert <cert-path>

Creating the Certificate and key by providing them in the default ssl directory still does nothing.

It looks like ng server is completely ignoring the --ssl parameter and keeps saying NG Live Development Server is running on http://localhost:4200.


问:
DispatcherServlet and web.xml in Spring Boot
I'm currently trying to move my project from Java EE to Spring Boot project.
However, i've been stucked and confused on the part with dispatcher servlet and web.xml and it seems like web.xml is no longer being read by the project anymore. The current project is running on tomcat 7.

In my web.xml file, I have lots of servlet, servlet-mapping, filter and filter mapping and I don't really understand how to do the mapping in the dispatcher.

I've attached a sample of my web.xml below and the version is 2.5.

<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>displayName</display-name>
  <description>description</description>
  <resource-ref>
    ...
  </resource-ref>
  <filter>
    <filter-name>Some Filter Name</filter-name>
    <filter-class>Some Filter Class</filter-class>
    <init-param>
      <param-name>Some Param Name</param-name>
      <param-value>Some Value</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Some Filter Name</filter-name>
    <url-pattern>Some url-pattern</url-pattern>
  </filter-mapping>
  <context-param>
    <param-name>Some Param Name</param-name>
    <param-value>Some Param Value</param-value>
  </context-param>
  <servlet>
    <servlet-name>Some Servlet Name</servlet-name>
    <servlet-class>Some Servlet Class</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Some Servlet Name</servlet-name>
    <url-pattern>Some Url Pattern</url-pattern>
  </servlet-mapping>
</web-app>```

Qns:

Should I convert all the stuff in my web.xml to rely on the spring dispatcher, if yes how can I achieve that?

Is moving away from the web.xml the way to go for spring boot project?

Can anyone please guide me along here? Thanks!!

答:
Spent quite some time so sharing three things I remember to make it working from command line.

Most important: JSPs should be kept only in folder /src/main/resources/META-INF/resources. more info here

Make sure that maven while building jar is considering your folders /src/main/resources, otherwise add these lines in your pom.xml

  <resources>
     <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>```
</div>
</div>
</p>
<ol start="3">
<li><p>In your mvc config file</p>
```@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Bean
    public InternalResourceViewResolver viewResolver(){
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/Representation/");
    resolver.setSuffix(".jsp");
    return resolver;
}
```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently trying to move my project from Java EE to Spring Boot project.
However, i've been stucked and confused on the part with dispatcher servlet and web.xml and it seems like web.xml is no longer being read by the project anymore. The current project is running on tomcat 7.

In my web.xml file, I have lots of servlet, servlet-mapping, filter and filter mapping and I don't really understand how to do the mapping in the dispatcher.

I've attached a sample of my web.xml below and the version is 2.5.

<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>displayName</display-name>
  <description>description</description>
  <resource-ref>
    ...
  </resource-ref>
  <filter>
    <filter-name>Some Filter Name</filter-name>
    <filter-class>Some Filter Class</filter-class>
    <init-param>
      <param-name>Some Param Name</param-name>
      <param-value>Some Value</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Some Filter Name</filter-name>
    <url-pattern>Some url-pattern</url-pattern>
  </filter-mapping>
  <context-param>
    <param-name>Some Param Name</param-name>
    <param-value>Some Param Value</param-value>
  </context-param>
  <servlet>
    <servlet-name>Some Servlet Name</servlet-name>
    <servlet-class>Some Servlet Class</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Some Servlet Name</servlet-name>
    <url-pattern>Some Url Pattern</url-pattern>
  </servlet-mapping>
</web-app>

Qns:

Should I convert all the stuff in my web.xml to rely on the spring dispatcher, if yes how can I achieve that?

Is moving away from the web.xml the way to go for spring boot project?

Can anyone please guide me along here? Thanks!!

Body:
Spent quite some time so sharing three things I remember to make it working from command line.

Most important: JSPs should be kept only in folder /src/main/resources/META-INF/resources. more info here

Make sure that maven while building jar is considering your folders /src/main/resources, otherwise add these lines in your pom.xml

  <resources>
     <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>

In your mvc config file

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Bean
    public InternalResourceViewResolver viewResolver(){
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/Representation/");
    resolver.setSuffix(".jsp");
    return resolver;
}


问:
How do use Javascript Async-Await as an alternative to polling for a statechange?
I'd like to accomplish the following using promises: only execute further once the state of something is ready. I.e. like polling for an external state-change.

I've tried using promises and async-await but am not getting the desired outcome. What am I doing wrong here, and how do I fix it?

The MDN docs have something similar but their settimeout is called within the promise--that's not exactly what I'm looking for though.

I expect the console.log to show "This function is now good to go!" after 5 seconds, but instead execution seems to stop after calling await promiseForState();

var state = false;

function stateReady (){
 state = true;
}

function promiseForState(){
 var msg = "good to go!";
 var promise = new Promise(function (resolve,reject){
        if (state){
            resolve(msg);
        }
    });

  return promise;
}

async function waiting (intro){

    var result = await promiseForState();
    console.log(intro + result)

}
setTimeout(stateReady,5000);
waiting("This function is now ");```

答:
Here is an alternative using .requestAnimationFrame().

It provides a clean interface that is simple to understand.

var serverStuffComplete = false
// mock the server delay of 5 seconds
setTimeout(()=>serverStuffComplete = true, 5000);

// continue until serverStuffComplete is true
function waitForServer(now) {
  if (serverStuffComplete) {
    doSomethingElse();
  } else {
    // place this request on the next tick
    requestAnimationFrame(waitForServer);
  }
}
console.log("Waiting for server...");
// starts the process off
requestAnimationFrame(waitForServer);

//resolve the promise or whatever
function doSomethingElse() {
  console.log('Done baby!');
}```


问:
writing screen output (stdErr) and output (stdOut) of a Linux command to separate files
I am working with a command line package and to get its the output in a file I use:

```<code>my_command > outfile
</code>```

but it also produces some information on the screen while running and writing the output in the outfile and I want the get the screen output in  a second outfile. In the useful thread in here , there is no suggested way to separate these two outputs. Is there actually a way to separate these two outputs and write them in different files?

答:
Sounds like the additional output comes from stderr, which you can capture with 2>:

```<code>mycommand > outfile 2> stderr
</code>```

Body:
I am working with a command line package and to get its the output in a file I use:

my_command > outfile

but it also produces some information on the screen while running and writing the output in the outfile and I want the get the screen output in  a second outfile. In the useful thread in here , there is no suggested way to separate these two outputs. Is there actually a way to separate these two outputs and write them in different files?

Body:
Sounds like the additional output comes from stderr, which you can capture with 2>:

mycommand > outfile 2> stderr


问:
Get document collections in Firestore
this is my firebase database

```<code>- conversations (collection)
-- xxx (document)
--- users (collection)
---- xxx (document)
</code>```

I want to list all the conversations and its users

```<code>this.db.collection('conversations').get().then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
        console.log(doc.collection('users').get())
    });
});
</code>```

I´m getting doc.collection is not a function

update: this is what I have after getting the id and making a new query. now the question is. is this performant?

```<code>    this.db.collection('conversations').get().then(conversationsQuerySnapshot => {
        conversationsQuerySnapshot.docs.forEach(doc => {
            this.db.collection('conversations').doc(doc.id).collection('users').get().then(usersQuerySnapshot => {
                usersQuerySnapshot.docs.forEach(doc => {
                    console.table(doc.data());
                });
            });
        });
    });
</code>```

答:
You're looking for doc.ref.collection('users'), since you need go get from the DocumentSnapshot to its DocumentReference through doc.ref.

Note that I find it easiest to spot such mistakes by simply following the types. Your querySnapshot is a QuerySnapshot, which means that your doc is a QueryDocumentSnapshot. Since QueryDocumentSnapshot doesn't have a collection method, it's easier to figure out what's going wrong.

Title: Get document collections in Firestore

Body:
this is my firebase database

- conversations (collection)
-- xxx (document)
--- users (collection)
---- xxx (document)

I want to list all the conversations and its users

this.db.collection('conversations').get().then(querySnapshot => {
    querySnapshot.docs.forEach(doc => {
        console.log(doc.collection('users').get())
    });
});

I´m getting doc.collection is not a function

update: this is what I have after getting the id and making a new query. now the question is. is this performant?

    this.db.collection('conversations').get().then(conversationsQuerySnapshot => {
        conversationsQuerySnapshot.docs.forEach(doc => {
            this.db.collection('conversations').doc(doc.id).collection('users').get().then(usersQuerySnapshot => {
                usersQuerySnapshot.docs.forEach(doc => {
                    console.table(doc.data());
                });
            });
        });
    });


问:
Using an IF statement to control the return statement?
```<code>public static int seqSearch(int numRecords, String[] stuName,
      double[] stuGpa, String nameKey, double gpaKey)

        for(int i = 0; i < numRecords; i++)
           if(stuName[i] == nameKey && stuGpa[i] == gpaKey)
              return i;
        return -1;
</code>```

So, how would I used an if statement to control this? I'm doing sequential search to find if the name is found in the array and if the gpa is in the array, then it should return the position it was found in (i). But, all it does do is return -1 and print out that none were found.

答:
Strings must be compared with .equals in Java, not ==.</p>

```<code>if(stuName[i].equals (nameKey) && stuGpa[i] == gpaKey)
</code>```

Body:
public static int seqSearch(int numRecords, String[] stuName,
      double[] stuGpa, String nameKey, double gpaKey)

        for(int i = 0; i < numRecords; i++)
           if(stuName[i] == nameKey && stuGpa[i] == gpaKey)
              return i;
        return -1;

So, how would I used an if statement to control this? I'm doing sequential search to find if the name is found in the array and if the gpa is in the array, then it should return the position it was found in (i). But, all it does do is return -1 and print out that none were found.

Body:
Strings must be compared with .equals in Java, not ==.

if(stuName[i].equals (nameKey) && stuGpa[i] == gpaKey)


问:
Trouble understanding C++ dependent types, vs what's on the current instantiation
The code below is adapted from the answer here: https://stackoverflow.com/a/17579889/352552

My purpose in asking this question is try to to understand better how C++ handles type resolution around dependent types, versus what's considered to be on the current instantiation, and therefore not needing a typename qualifier.  I've been getting contradictory results from different compilers, so I've come here looking for a more canonical answer.

Consider this code

```<code>#include <iostream>

struct B {
  typedef int result_type;
};

template<typename T>
struct C {
};

template<>
struct C<float> {
  typedef float result_type;
};

template<typename T>
struct D : B, C<T> {
  std::string show() {
    //A) Default to current instantiation - ignore dependent type, even if one exists, or so I hope
    D::result_type r1;

    //B) What **exactly** does typename add, here?
    //typename D::result_type r1;

    return whichType(r1);
  }

  std::string whichType (int val){
    return "INT";
  }
  std::string whichType (float val){
    return "FLOAT";
  }
};

int main() {
  D<std::string> stringD;
  D<float> floatD;
  std::cout<<"String initialization "<<stringD.show()<<std::endl;
  std::cout<<"Float initialization "<<floatD.show()<<std::endl;
}
</code>```

line A) in show(), if I understand correctly, tells the compiler to use the current instantiation, so I should get INT INT.  On GCC, I do. So far, so good.

Line B, again if I understand correctly, should either tell the compiler to consider dependent types, which would make that line error out because of the ambiguity; or, if that means only consider dependent types, I should get INT FLOAT.  On GCC I get INT INT there, too.  Why?

Running this on Clang.

Line A doesn't compile at all.

error: no type named 'result_type' in 'D'; did you mean simply 'result_type'? D::result_type r1;

dropping the D:: does indeed yield INT INT.

Should it have compiled, or is Clang correct here?

Line B does indeed error on the ambiguity

error: member 'result_type' found in multiple base classes of different types typename D::result_type r1

Can anyone here say with authority which compiler (if any!) is canonically correct, and why?

Assuming Clang is correct, it might imply that

MyType::F

is invalid for referencing a type from the current instantiation if it exists on a base type; it's only valid if the type is defined on that class. Ie adding

typedef double dd;

to D

and then

```<code>D::dd d = 1.1;
std::cout<<d;
</code>```

in show would work just fine, which is indeed the case.

Moreover,

typename D::sometype

seems to mean consider dependent types, but not exclusively, and so expect errors if such a type winds up defined in multiple places, either in the current instantiation, and or dependent on a template parameter.

But again, this all assumes Clang's behavior is correct according to spec, which I can't speak to.

Link to GCC repl I was using:
https://wandbox.org/

Link to Clang repl I was using:
https://repl.it/languages/cpp11

答:
Moreover,

typename D::sometype

seems to mean consider dependent types

Where did you get that idea? typename only means that what follows isn't a data member but a type name, so that the parsing of a template can be done. Do you know how primitive C++ compilers parsed template functions and classes in the old time? They did no meaningful parsing, they just ate all symbols doing only {/} balancing. Yes at some point you could include almost any garbage inside template definitions if they were never instantiated! It was simplistic and dirty but not that inane if you think about it, as the alternative (correct parsing) was not really practicable at the time.

In order to even meaningfully parse (without even resolving many names) inside a template some things need to be made explicit: the category (variable-or-function, type name, template name) of symbols that can't be resolved before instantiation, so simple stuff like X * Y;, X * (Y); and X(Y); is ambiguous and not parsable (declaration or expression). So typename is used to indicate that a symbol that can't be found at template definition time designate a type, so if X is typename T::U then all three previous syntagmes are declaration; without the typename and if T::U is dependent they would be parse as expression-statements and there is no second parsing when templates are instantiated so if U was actually a type it would be an error.

```<code>//A) Default to current instantiation - ignore dependent type, even if one exists, or so I hope
D::result_type r1;
</code>```

According to https://en.cppreference.com/w/cpp/language/dependent_name lookup from the "current instantiation" considers only non dependent base classes at definition time and then:

If the lookup of a member of current instantiation gives a different
  result between the point of instantiation and the point of definition,
  the lookup is ambiguous.

So hopefully what you "hoped" for shouldn't happen!

Body:
The code below is adapted from the answer here: https://stackoverflow.com/a/17579889/352552

My purpose in asking this question is try to to understand better how C++ handles type resolution around dependent types, versus what's considered to be on the current instantiation, and therefore not needing a typename qualifier.  I've been getting contradictory results from different compilers, so I've come here looking for a more canonical answer.

Consider this code

#include <iostream>

struct B {
  typedef int result_type;
};

template<typename T>
struct C {
};

template<>
struct C<float> {
  typedef float result_type;
};

template<typename T>
struct D : B, C<T> {
  std::string show() {
    //A) Default to current instantiation - ignore dependent type, even if one exists, or so I hope
    D::result_type r1;

    //B) What **exactly** does typename add, here?
    //typename D::result_type r1;

    return whichType(r1);
  }

  std::string whichType (int val){
    return "INT";
  }
  std::string whichType (float val){
    return "FLOAT";
  }
};

int main() {
  D<std::string> stringD;
  D<float> floatD;
  std::cout<<"String initialization "<<stringD.show()<<std::endl;
  std::cout<<"Float initialization "<<floatD.show()<<std::endl;
}

line A) in show(), if I understand correctly, tells the compiler to use the current instantiation, so I should get INT INT.  On GCC, I do. So far, so good.

Line B, again if I understand correctly, should either tell the compiler to consider dependent types, which would make that line error out because of the ambiguity; or, if that means only consider dependent types, I should get INT FLOAT.  On GCC I get INT INT there, too.  Why?

Running this on Clang.

Line A doesn't compile at all.

error: no type named 'result_type' in 'D'; did you mean simply 'result_type'? D::result_type r1;

dropping the D:: does indeed yield INT INT.

Should it have compiled, or is Clang correct here?

Line B does indeed error on the ambiguity

error: member 'result_type' found in multiple base classes of different types typename D::result_type r1

Can anyone here say with authority which compiler (if any!) is canonically correct, and why?

Assuming Clang is correct, it might imply that

MyType::F

is invalid for referencing a type from the current instantiation if it exists on a base type; it's only valid if the type is defined on that class. Ie adding

typedef double dd;

to D

and then

D::dd d = 1.1;
std::cout<<d;

in show would work just fine, which is indeed the case.

Moreover,

typename D::sometype

seems to mean consider dependent types, but not exclusively, and so expect errors if such a type winds up defined in multiple places, either in the current instantiation, and or dependent on a template parameter.

But again, this all assumes Clang's behavior is correct according to spec, which I can't speak to.

Link to GCC repl I was using:
https://wandbox.org/

Link to Clang repl I was using:
https://repl.it/languages/cpp11

Body:
Moreover,

typename D::sometype

seems to mean consider dependent types

Where did you get that idea? typename only means that what follows isn't a data member but a type name, so that the parsing of a template can be done. Do you know how primitive C++ compilers parsed template functions and classes in the old time? They did no meaningful parsing, they just ate all symbols doing only {/} balancing. Yes at some point you could include almost any garbage inside template definitions if they were never instantiated! It was simplistic and dirty but not that inane if you think about it, as the alternative (correct parsing) was not really practicable at the time.

In order to even meaningfully parse (without even resolving many names) inside a template some things need to be made explicit: the category (variable-or-function, type name, template name) of symbols that can't be resolved before instantiation, so simple stuff like X * Y;, X * (Y); and X(Y); is ambiguous and not parsable (declaration or expression). So typename is used to indicate that a symbol that can't be found at template definition time designate a type, so if X is typename T::U then all three previous syntagmes are declaration; without the typename and if T::U is dependent they would be parse as expression-statements and there is no second parsing when templates are instantiated so if U was actually a type it would be an error.

//A) Default to current instantiation - ignore dependent type, even if one exists, or so I hope
D::result_type r1;

According to https://en.cppreference.com/w/cpp/language/dependent_name lookup from the "current instantiation" considers only non dependent base classes at definition time and then:

If the lookup of a member of current instantiation gives a different
  result between the point of instantiation and the point of definition,
  the lookup is ambiguous.

So hopefully what you "hoped" for shouldn't happen!


问:
Electron using Accelerator to call a menu item in context menu
How do I use the accelerator to call a menu item in context menu?

```<code>var menu = new Menu();

menu.append(new MenuItem({
  label: 'Say something',
  click: function(){
    alert("Hello");
  },
  accelerator: "CmdOrCtrl+E"
}));

window.addEventListener('contextmenu', function (e) {
  e.preventDefault();
  menu.popup(currentWindow);
}, false);
</code>```

The above code works. The context menu appears and when the menu item is clicked the click callback works.

But the accelerator command doesn't work. Any ideas?

Side question:

can I pass the click event to menu.popup and then pass it to the menu-item click callback? Right now I am just storing the click event in a global variable.

答:
I find that the easiest way to register context menu accelerators today is by appending the context menu to your application menu, which will register them, but setting visible: false so they won't actually appear.

It's quite simple when using menu templates.

```<code>function registerAppMenu(app, invisibleMenus) {
  const template = [ ... ]; // use app to create the file-menu
  template.push(...invisibleMenus.map(menu => ({...menu, visible: false})));
  Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}

</code>```

Body:
How do I use the accelerator to call a menu item in context menu?

var menu = new Menu();

menu.append(new MenuItem({
  label: 'Say something',
  click: function(){
    alert("Hello");
  },
  accelerator: "CmdOrCtrl+E"
}));

window.addEventListener('contextmenu', function (e) {
  e.preventDefault();
  menu.popup(currentWindow);
}, false);

The above code works. The context menu appears and when the menu item is clicked the click callback works.

But the accelerator command doesn't work. Any ideas?

Side question:

can I pass the click event to menu.popup and then pass it to the menu-item click callback? Right now I am just storing the click event in a global variable.

Body:
I find that the easiest way to register context menu accelerators today is by appending the context menu to your application menu, which will register them, but setting visible: false so they won't actually appear.

It's quite simple when using menu templates.

function registerAppMenu(app, invisibleMenus) {
  const template = [ ... ]; // use app to create the file-menu
  template.push(...invisibleMenus.map(menu => ({...menu, visible: false})));
  Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}


问:
How to pull from a string into first, middle, and last name. And how to recognize when there is no middle name inputed
I need to do the following:

Many documents use a specific format for a person's name. Write a program whose input is: firstName middleName lastName, and whose output is: lastName, firstName middleInitial.

It's through a textbook so I haven't been taught how to split strings. That's all I can find online, but that's not what the textbook is asking for. So far I've been taught how to compare strings, get a strings length, branches, switch statements, string operations.

    import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);

      String firstName;
      String middleName;
      String lastName;
      String name;

      name = scnr.nextLine();

      int firstSpace = name.indexOf(" ");
      firstName = name.substring(0, firstSpace);

      int secondSpace = name.indexOf(" ", firstSpace + 1);

      if (secondSpace < 0) {
         lastName = name.substring(firstSpace);
         System.out.println(lastName + ", " + firstName);
      }
      else {
         middleName = name.substring(firstSpace, secondSpace);
         lastName = name.substring(secondSpace);
         System.out.println(lastName + ", " + firstName + " " + middleName.charAt(0) + ".");
      }

   }
}

```

This is what I have so far.

答:
This is the correct code:    </p>

```<code>import java.util.Scanner;

public class LabProgram {
public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);

  String firstName;
  String middleName;
  String lastName;
  String name;

  name = scnr.nextLine();

  int firstSpace = name.indexOf(" ");
  firstName = name.substring(0, firstSpace);

  int secondSpace = name.indexOf(" ", firstSpace + 1);

  if (secondSpace < 0) {
     lastName = name.substring(firstSpace + 1);
     System.out.println(lastName + ", " + firstName);
  }
  else {
     middleName = name.substring(firstSpace, secondSpace);
     lastName = name.substring(secondSpace + 1);
     System.out.println(lastName + ", " + firstName + " " +     middleName.charAt(1) + ".");
  }

  }
}
</code>```

Body:
I need to do the following:

Many documents use a specific format for a person's name. Write a program whose input is: firstName middleName lastName, and whose output is: lastName, firstName middleInitial.

It's through a textbook so I haven't been taught how to split strings. That's all I can find online, but that's not what the textbook is asking for. So far I've been taught how to compare strings, get a strings length, branches, switch statements, string operations.

    import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);

      String firstName;
      String middleName;
      String lastName;
      String name;

      name = scnr.nextLine();

      int firstSpace = name.indexOf(" ");
      firstName = name.substring(0, firstSpace);

      int secondSpace = name.indexOf(" ", firstSpace + 1);

      if (secondSpace < 0) {
         lastName = name.substring(firstSpace);
         System.out.println(lastName + ", " + firstName);
      }
      else {
         middleName = name.substring(firstSpace, secondSpace);
         lastName = name.substring(secondSpace);
         System.out.println(lastName + ", " + firstName + " " + middleName.charAt(0) + ".");
      }

   }
}

This is what I have so far.

Body:
This is the correct code:

import java.util.Scanner;

public class LabProgram {
public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);

  String firstName;
  String middleName;
  String lastName;
  String name;

  name = scnr.nextLine();

  int firstSpace = name.indexOf(" ");
  firstName = name.substring(0, firstSpace);

  int secondSpace = name.indexOf(" ", firstSpace + 1);

  if (secondSpace < 0) {
     lastName = name.substring(firstSpace + 1);
     System.out.println(lastName + ", " + firstName);
  }
  else {
     middleName = name.substring(firstSpace, secondSpace);
     lastName = name.substring(secondSpace + 1);
     System.out.println(lastName + ", " + firstName + " " +     middleName.charAt(1) + ".");
  }

  }
}


答:
Since we have arrays with equal sizes, we can just write a for loop and add them up: </p>

```<code>$array1 = [1, 0, 2, 3, 4];
$array2 = [3, 5, 6, 7, 8];

$array_sum = [];

if (sizeof($array1) != sizeof($array2)) {
    echo "Our arrays do not have equal length. ";
}

for ($i = 0; $i < sizeof($array1); $i++) {
    $array_sum[$i] = $array1[$i] + $array2[$i];
}

var_dump($array_sum);
</code>```

Title: How would one sum the individual indexes within a single array in PHP?

Body:
Since we have arrays with equal sizes, we can just write a for loop and add them up:

$array1 = [1, 0, 2, 3, 4];
$array2 = [3, 5, 6, 7, 8];

$array_sum = [];

if (sizeof($array1) != sizeof($array2)) {
    echo "Our arrays do not have equal length. ";
}

for ($i = 0; $i < sizeof($array1); $i++) {
    $array_sum[$i] = $array1[$i] + $array2[$i];
}

var_dump($array_sum);


问:
Execute batch of microsoft translation queries
We are trying to use Microsoft translation service provided on Azure market place. I started with the sample code provided at http://code.msdn.microsoft.com/windowsazure/Walkthrough-Translator-in-7e0be0f7/view/SourceCode

Using their  sample code I can get a single translation. However I would like to get multiple translations in a single request. I tried using DataServiceContext.ExecuteBatch but it throws WebException with "The remote server returned an error: (404) Not Found."

```<code>TranslatorContainer cont = new TranslatorContainer(new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/"));
var accountKey = "<account-key>";
cont.Credentials = new NetworkCredential(accountKey, accountKey);

// This works
var result1 = cont.Translate("Nothing to translate", "nl", "en").Execute().ToList();

DataServiceQuery<Translation>[] queries = new DataServiceQuery<Translation>[]
{
    cont.Translate("Nothing", "nl", "en"),
    cont.Translate("Nothing to translate", "nl", "en"),
    cont.Translate("What happend", "nl", "en"),
};

// This throws exception
var result2 = cont.ExecuteBatch(queries);
</code>```

I could use multiple threads and make multiple requests in parallel. But I like to avoid that. Anyone have tried this before ?

答:
Use this NuGet package for batch translation on CognitiveServices Translator API 3.0

This Nuget can help you on Batch-Translation, easily and quickly.

How it work: It'll transform your contents to some perfect packages for translating.

Speed: On my PC, about 300~500 items(not characters) per second

Here are steps:

Create an instance of Translator with your BaseUrl and Key:

```<code>Translator translator = new Translator(BaseUrl, Key);
</code>```

Add content to the Translator:

```<code>translator.AddContent("哈啰");
//Here you can add many times, more than 100, 1000 or 10000.
//You can also set the "Contents" property instead.
</code>```

Get results aysnc:

```<code>List<string> translation = await translator.TranslateAsync("en");
</code>```

Body:
We are trying to use Microsoft translation service provided on Azure market place. I started with the sample code provided at http://code.msdn.microsoft.com/windowsazure/Walkthrough-Translator-in-7e0be0f7/view/SourceCode

Using their  sample code I can get a single translation. However I would like to get multiple translations in a single request. I tried using DataServiceContext.ExecuteBatch but it throws WebException with "The remote server returned an error: (404) Not Found."

TranslatorContainer cont = new TranslatorContainer(new Uri("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/"));
var accountKey = "<account-key>";
cont.Credentials = new NetworkCredential(accountKey, accountKey);

// This works
var result1 = cont.Translate("Nothing to translate", "nl", "en").Execute().ToList();

DataServiceQuery<Translation>[] queries = new DataServiceQuery<Translation>[]
{
    cont.Translate("Nothing", "nl", "en"),
    cont.Translate("Nothing to translate", "nl", "en"),
    cont.Translate("What happend", "nl", "en"),
};

// This throws exception
var result2 = cont.ExecuteBatch(queries);

I could use multiple threads and make multiple requests in parallel. But I like to avoid that. Anyone have tried this before ?

Body:
Use this NuGet package for batch translation on CognitiveServices Translator API 3.0

This Nuget can help you on Batch-Translation, easily and quickly.

How it work: It'll transform your contents to some perfect packages for translating.

Speed: On my PC, about 300~500 items(not characters) per second

Here are steps:

Create an instance of Translator with your BaseUrl and Key:

Translator translator = new Translator(BaseUrl, Key);

Add content to the Translator:

translator.AddContent("哈啰");
//Here you can add many times, more than 100, 1000 or 10000.
//You can also set the "Contents" property instead.

Get results aysnc:

List<string> translation = await translator.TranslateAsync("en");


答:
You probably want</p>

```<code>if (stuName[i].equals(nameKey) && stuGpa[i].equals(gpaKey))
</code>```

Title: Using an IF statement to control the return statement?

Body:
You probably want

if (stuName[i].equals(nameKey) && stuGpa[i].equals(gpaKey))


问:
Capitalizing first letter of each token of a string split on punctuation and whitespace
I'm trying to title the following string:

"Men's L/s button-up"

I'm using string.capwords right now but it's not working as expected.

For example:

```<code>x = "Men's L/s button-up"
y = string.capwords(x)
print(y)
</code>```

outputs:

Men's L/s Button-up

but I want:

Men's L/S Button-Up (uppercased S after the / and uppercased U after the -)

More generally, how do I ensure that all letters following a space or punctuation are capitalized?

This is a follow-up from:

Keep uppercase after / in a string

答:
The way I would approach this is by splitting up each word you want to capitalize (using re.split), capitalize said word (using str.capitalize), and then recombine the words to get a single string (using str.join):

```<code>>>> from re import split
>>>
>>> string = "Men's L/s button-up"
>>> ''.join([word.capitalize() for word in split("([ /-])", string)])
"Men's L/S Button-Up"
>>
</code>```

If you need to split on more punctuation characters, simply add them to the regular expression. For example, if you do decide you need to capitalize words/characters after apostrophes, adding:

```<code>"([ '/-])"
</code>```

to the regular expression would work:

```<code>>>> ''.join([word.capitalize() for word in split("([ '/-])", string)])
"Men'S L/S Button-Up"
>>>
</code>```

Body:
I'm trying to title the following string:

"Men's L/s button-up"

I'm using string.capwords right now but it's not working as expected.

For example:

x = "Men's L/s button-up"
y = string.capwords(x)
print(y)

outputs:

Men's L/s Button-up

but I want:

Men's L/S Button-Up (uppercased S after the / and uppercased U after the -)

More generally, how do I ensure that all letters following a space or punctuation are capitalized?

This is a follow-up from:

Keep uppercase after / in a string

Body:
The way I would approach this is by splitting up each word you want to capitalize (using re.split), capitalize said word (using str.capitalize), and then recombine the words to get a single string (using str.join):

>>> from re import split
>>>
>>> string = "Men's L/s button-up"
>>> ''.join([word.capitalize() for word in split("([ /-])", string)])
"Men's L/S Button-Up"
>>

If you need to split on more punctuation characters, simply add them to the regular expression. For example, if you do decide you need to capitalize words/characters after apostrophes, adding:

"([ '/-])"

to the regular expression would work:

>>> ''.join([word.capitalize() for word in split("([ '/-])", string)])
"Men'S L/S Button-Up"
>>>


问:
Django table doesn't exist after migration
I'm developing a test app in Google App Engine with Django + Python 3.7; I successfully launched the test app and created a new app both at local side and on app engine server.
Now I'm trying to create a little bit more complex model.
I created the model + view + url file and template and migrated it (with an apparent success), but if I try to visualize the template at the local server, I retrieve this error:

ProgrammingError at /
(1146, "Table 'djangoseo.keywords_keywords' doesn't exist")

I tried to migrate the model another time, used syncdb command with no success.

This is the model

```<code>from django.db import models

class Keywords(models.Model):
    keyword_name = models.CharField(max_length=200)
    keyword_tags = models.ManyToManyField('Tags')
    keyword_urls = models.ManyToManyField('Urls', through='Rankings')
    avg_volume = models.IntegerField(default=0)
    jan_volume = models.IntegerField(default=0)
    feb_volume = models.IntegerField(default=0)
    mar_volume = models.IntegerField(default=0)
    apr_volume = models.IntegerField(default=0)
    may_volume = models.IntegerField(default=0)
    jun_volume = models.IntegerField(default=0)
    jul_volume = models.IntegerField(default=0)
    aug_volume = models.IntegerField(default=0)
    sep_volume = models.IntegerField(default=0)
    oct_volume = models.IntegerField(default=0)
    nov_volume = models.IntegerField(default=0)
    dec_volume = models.IntegerField(default=0)
    intent = models.CharField(max_length=200)
    micromoment = models.CharField(max_length=200)
    language = models.CharField(max_length=200)
    addedby = models.CharField(max_length=200)

    def __str__(self):
        return self.keyword_name

class Tags(models.Model):
    tag_name = models.CharField(max_length=200)
    addedby = models.CharField(max_length=200)

    def __str__(self):
        return self.tag_name

class Urls(models.Model):
    url_name = models.CharField(max_length=300)
    domain = models.CharField(max_length=200)

    def __str__(self):
        return self.url_name

class Rankings(models.Model):
    keyword = models.ForeignKey(Keywords, on_delete=models.CASCADE)
    url = models.ForeignKey(Urls, on_delete=models.CASCADE)
    date_ranking = models.DateTimeField()
    ranking = models.IntegerField(default=0)

    def __str__(self):
        return self.ranking'''
</code>```

This is the view

```<code>from django.views import generic

from .models import Keywords

class IndexView(generic.ListView):
    template_name = 'keywords/index.html'
    context_object_name = 'keywords_list'

    def get_queryset(self):
        """Return the first ten keywords."""
        return Keywords.objects.order_by('keyword_name')[:10]
</code>```

And this is the template for index.html

```<code>{% if keywords_list %}
<ul>
{% for keyword in keywords_list %}
    <li>{{ keyword.keyword_name }}</li>
{% endfor %}
</ul>
{% else %}
<p>No keywords are available.</p>
{% endif %}
</code>```

I retrieve this error:

ProgrammingError at /
(1146, "Table 'djangoseo.keywords_keywords' doesn't exist")
Request Method: GET
Request URL:    http://localhost:8000/

How can I fix it? Why do I get it?

答:
If you haven't done an initial migration yet, that could be the issue. Follow the linked initial migration docs first to ensure that that has been done.

If you have done an initial migration, you'll need to check to ensure that when you ran

```<code>python manage.py makemigrations
</code>```

you received a migration file in your module's yourmodule/migrations/ directory. If that file does not exist, you need to double-check your syntax for makemigrations and ensure you are running the command from the same directory that your manage.py file is in.

If you have a migration file, you need to run migrate:

```<code>python manage.py migrate
</code>```

to apply it to the database. To ensure that it applied, check your database for a table named djangomigrations and run select * from djangomigrations order by id desc;. If you see your filename in the table, you should be good to go.

Body:
I'm developing a test app in Google App Engine with Django + Python 3.7; I successfully launched the test app and created a new app both at local side and on app engine server.
Now I'm trying to create a little bit more complex model.
I created the model + view + url file and template and migrated it (with an apparent success), but if I try to visualize the template at the local server, I retrieve this error:

ProgrammingError at /
(1146, "Table 'djangoseo.keywords_keywords' doesn't exist")

I tried to migrate the model another time, used syncdb command with no success.

This is the model

from django.db import models

class Keywords(models.Model):
    keyword_name = models.CharField(max_length=200)
    keyword_tags = models.ManyToManyField('Tags')
    keyword_urls = models.ManyToManyField('Urls', through='Rankings')
    avg_volume = models.IntegerField(default=0)
    jan_volume = models.IntegerField(default=0)
    feb_volume = models.IntegerField(default=0)
    mar_volume = models.IntegerField(default=0)
    apr_volume = models.IntegerField(default=0)
    may_volume = models.IntegerField(default=0)
    jun_volume = models.IntegerField(default=0)
    jul_volume = models.IntegerField(default=0)
    aug_volume = models.IntegerField(default=0)
    sep_volume = models.IntegerField(default=0)
    oct_volume = models.IntegerField(default=0)
    nov_volume = models.IntegerField(default=0)
    dec_volume = models.IntegerField(default=0)
    intent = models.CharField(max_length=200)
    micromoment = models.CharField(max_length=200)
    language = models.CharField(max_length=200)
    addedby = models.CharField(max_length=200)

    def __str__(self):
        return self.keyword_name

class Tags(models.Model):
    tag_name = models.CharField(max_length=200)
    addedby = models.CharField(max_length=200)

    def __str__(self):
        return self.tag_name

class Urls(models.Model):
    url_name = models.CharField(max_length=300)
    domain = models.CharField(max_length=200)

    def __str__(self):
        return self.url_name

class Rankings(models.Model):
    keyword = models.ForeignKey(Keywords, on_delete=models.CASCADE)
    url = models.ForeignKey(Urls, on_delete=models.CASCADE)
    date_ranking = models.DateTimeField()
    ranking = models.IntegerField(default=0)

    def __str__(self):
        return self.ranking'''

This is the view

from django.views import generic

from .models import Keywords

class IndexView(generic.ListView):
    template_name = 'keywords/index.html'
    context_object_name = 'keywords_list'

    def get_queryset(self):
        """Return the first ten keywords."""
        return Keywords.objects.order_by('keyword_name')[:10]

And this is the template for index.html

{% if keywords_list %}

{% for keyword in keywords_list %}

{{ keyword.keyword_name }}

{% endfor %}

{% else %}

No keywords are available.

{% endif %}

I retrieve this error:

ProgrammingError at /
(1146, "Table 'djangoseo.keywords_keywords' doesn't exist")
Request Method: GET
Request URL:    http://localhost:8000/

How can I fix it? Why do I get it?

Body:
If you haven't done an initial migration yet, that could be the issue. Follow the linked initial migration docs first to ensure that that has been done.

If you have done an initial migration, you'll need to check to ensure that when you ran

python manage.py makemigrations

you received a migration file in your module's yourmodule/migrations/ directory. If that file does not exist, you need to double-check your syntax for makemigrations and ensure you are running the command from the same directory that your manage.py file is in.

If you have a migration file, you need to run migrate:

python manage.py migrate

to apply it to the database. To ensure that it applied, check your database for a table named djangomigrations and run select * from djangomigrations order by id desc;. If you see your filename in the table, you should be good to go.


问:
Effective Unit Test Coverage (and what should actually be tested?)
I see there's been several questions based off this topic, but I have some specific examples that I'm struggling with. I hope someone can help me here, as I'm new to test driven development and unit testing in general.

(I'm not sure if it matters but I am using C# with .NET framework 4.0 and using Microsoft's built in testing framework)

First off, is it worth testing very simple blocks of code? For example, for one of my classes I have a Fill method which accepts 10 parameters, and sets the values for 10 properties in the class based off of those parameters. The fill code really is just a series of value setting statements. I've read that a good unit test is supposed to only assert one thing, but it seems to me in order to check that all those values have been set correctly I would have to assert 10 things. So either I can not test it at all, trusting that the code is simple enough, or write 10 different unit tests to check each property. Are any of these correct?

Second example. I have a block of code that makes several calls to a class's private methods and finally calls a web service to fire off an email to a user. I understand that I should inject a mock web service for the email service so that I'm not testing multiple classes, but how should I test that all those private methods and that email call have been made?

Third example is similar to the last. My class structure looks something likes:

Controller --- depends on --->  IWidget(some business object)  && IDataProvider
DataProvider(Implements IDataProvider) --- depends on ---> WebService
WebService --- directly makes calls ---> Database

Right now I have unit tests for the controller (injecting mock Widgets and DataProviders).
So that's all good. I also have unit tests for Widget with no problems.

The trouble  comes down to the DataProvider and the WebService. The WebService in this particular instance does nothing but passes through the requests of the dataprovider and passes back the data (due to physical architecture restraints).

I have trouble unit testing the DataProvider because I'm not sure how to go about injecting a mock web service. I'm also unsure if unit testing the DataProvider is worth while, because I'd wind up having to code in a lot of mocked up datasets just to test values. Similarly I'm unsure how to go about unit testing the web service because in this instance the WebService's main function depends on the database. Once again, is this worth testing? What if the WebService did more besides just serve as a pass through but was still dependent on the database?

I'd greatly appreciate any advice that anyone can offer in this regard. Thanks very much.

答:
I've read that a good unit test is supposed to only assert one thing, but it seems to me in order to check that all those values have been set correctly I would have to assert 10 things. So either I can not test it at all, trusting that the code is simple enough, or write 10 different unit tests to check each property.

I would say a good unit test should test one story or use case scenario, which can indeed involve multiple assertions.

If the method involves 10 assignments, there is indeed a chance that some are messed up, names are misspelled etc., so a unit test provides value for its (small) price.

I have a block of code that makes several calls to a class's private methods and finally calls a web service to fire off an email to a user. I understand that I should inject a mock web service for the email service so that I'm not testing multiple classes, but how should I test that all those private methods and that email call have been made?

This is called sensing, i.e. sensing the results / side effects of the call you made. The answer depends on what those private methods actually do. If they assemble some data which in the end goes into the mail message, it can be tested via the message contents. If they change the internal state of the object in a way that can be detected from outside, you can verify it. If none of these is true, it might even be the case that those private methods would be better moved into a separate class' public interface where they can be properly unit tested.

I have trouble unit testing the DataProvider because I'm not sure how to go about injecting a mock web service. I'm also unsure if unit testing the DataProvider is worth while, because I'd wind up having to code in a lot of mocked up datasets just to test values.

I would not necessarily want to unit test such classes which are in fact wrappers to external components. If there is only the absolute minimal amount of logic there, i.e. all (or the most possible) code worth testing was moved out to other, unit testable, classes, IMO it can be OK to leave the testing of these classes to the integration/functional tests, which exercise the whole (sub)system connected to a real DB, web service etc.


问:
Converting milliseconds to minutes and seconds with Javascript
Soundcloud's API gives the duration of it's tracks as milliseconds. JSON looks like this:

```<code>"duration": 298999
</code>```

I've tried many functions I found on here to no avail. I'm just looking for something to convert that number to something like looks like this:

```<code>4:59
</code>```

Here's one that got close, but doesn't work. It doesn't stop the seconds at 60. It goes all the way to 99 which makes no sense. Try entering "187810" as a value of ms, for example.

```<code>var ms = 298999,
min = Math.floor((ms/1000/60) << 0),
sec = Math.floor((ms/1000) % 60);

console.log(min + ':' + sec);
</code>```

Thanks for your help!

If you could add in support for hours, too, I would be grateful.

答:
Here's my contribution if looking for

h:mm:ss

instead like I was:

```<code>function msConversion(millis) {
  let sec = Math.floor(millis / 1000);
  let hrs = Math.floor(sec / 3600);
  sec -= hrs * 3600;
  let min = Math.floor(sec / 60);
  sec -= min * 60;

  sec = '' + sec;
  sec = ('00' + sec).substring(sec.length);

  if (hrs > 0) {
    min = '' + min;
    min = ('00' + min).substring(min.length);
    return hrs + ":" + min + ":" + sec;
  }
  else {
    return min + ":" + sec;
  }
}
</code>```

Body:
Soundcloud's API gives the duration of it's tracks as milliseconds. JSON looks like this:

"duration": 298999

I've tried many functions I found on here to no avail. I'm just looking for something to convert that number to something like looks like this:

4:59

Here's one that got close, but doesn't work. It doesn't stop the seconds at 60. It goes all the way to 99 which makes no sense. Try entering "187810" as a value of ms, for example.

var ms = 298999,
min = Math.floor((ms/1000/60) << 0),
sec = Math.floor((ms/1000) % 60);

console.log(min + ':' + sec);

Thanks for your help!

If you could add in support for hours, too, I would be grateful.

Body:
Here's my contribution if looking for

h:mm:ss

instead like I was:

function msConversion(millis) {
  let sec = Math.floor(millis / 1000);
  let hrs = Math.floor(sec / 3600);
  sec -= hrs * 3600;
  let min = Math.floor(sec / 60);
  sec -= min * 60;

  sec = '' + sec;
  sec = ('00' + sec).substring(sec.length);

  if (hrs > 0) {
    min = '' + min;
    min = ('00' + min).substring(min.length);
    return hrs + ":" + min + ":" + sec;
  }
  else {
    return min + ":" + sec;
  }
}


问:
Files transfer to HDFS
I need to bring the files (zip, csv, xml etc) from windows share location to HDFS. Which is the best approach ? I have kafka - flume - hdfs in mind. Please suggest the efficient way.

I tried getting the files to Kafka consumer.

producer.send(
                    new ProducerRecord(topicName,key,value),

Expect an efficient approach

答:
Kafka is not designed to send files, only individual messages of up to 1MB, by default.

You can install NFS Gateway in Hadoop, then you should be able to copy directly from the windows share to HDFS without any streaming technology, only a scheduled script on the windows machine, or externally ran

Or you can mount the windows share on some Hadoop node, and schedule a Cron job if you need continuous file delivery - https://superuser.com/a/1439984/475508

Other solutions I've seen use tools like Nifi / Streamsets which can be used to read/move files

https://community.hortonworks.com/articles/26089/windows-share-nifi-hdfs-a-practical-guide.html

Title: Files transfer to HDFS


问:
How to install react-navigation in an ejected expo project?
I am trying to install react-navigation in my ejected expo app by following the official install instructions on this page. Within the instructions below the typical addition of the package and linking via react-native link there is additional code to be added into the file MainActivity.java.

Now my problem is that in the install instructions the class MainActivity extends the class ReactActivity, but since I use an ejected expo app in my code it extends the class DetachActivity, which seems to be incompatible with the given code of the install instruction and therefore I am really clueless how to approach that incompatibility problem (especially since I am not even able to find anything via google about that - is it even a dark secret nobody talks about?).

Some approaches I tried but did not work:

Including code anyways produces error [compiling error] error: method does not override or implement a method from a supertype.

Including code, replacing DetachActivity with ReactActivity and removing all methods overriding methods of DetachActivity results in crash of the app.

Not including anything produces error [red screen on phone] Native module com.swmansion.gesturehandler.react.RNGestureHandlerModule tried to override versioned.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerModule for module name RNGestureHandlerModule. Check the getPackages() method in MainApplication.java, it might be that module is being created twice. If this was your intention, set canOverrideExistingModule=true.

I would really appreciate some wise tips! Also, I am not very familiar with java but am totally willing to learn some new stuff!

答:
Update in Dec. 2019

Ignore below.
Expo is separating their built in dependencies as react-native-gesture-handler nowadays. So we need to install it.
Ref

Solution

To summarize,

Go back to a commit you ejected a project from expo. And install react-navigation.
Do not install others as react-native-gesture-handler.

That's all.

Why

If you ejected your project from expo, those projects will have dependencies on ExpoKit, so do not need to install modules again already built. And react-native-gesture-handler is the one of those modules.
Thus, do not need react-native link also.

Native module com.swmansion.gesturehandler.react.RNGestureHandlerModule tried to override versioned.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerModule for module name RNGestureHandlerModule. Check the getPackages() method in MainApplication.java, it might be that module is being created twice. If this was your intention, set canOverrideExistingModule=true.

And this message may caused by RNGestureHandlerModule you installed again.


问:
Tick symbol in HTML/XHTML
We need to display a tick symbol (✓ or ✔) within an internal web app and would ideally like to avoid using an image.

Has to work starting with IE 6.0.2900 on a XP box, ideally we need it be cross-browser (IE + recent versions of FF).

The following displays boxes although sets browser encoding to UTF-8 (META works nicely and not the issue). The default font is Times New Roman (might be an issue, but trying Lucida Sans Unicode doesn't help and I don't have neither Arial Unicode MS, nor Lucida Grande installed).

```<code><html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
 ✓ ✔
</body>
</html>
</code>```

Any help appreciated.

The following works under IE 6.0 and IE 7:

```<code><html>
<head>

</head>
<body>
 <span style="font-family: wingdings; font-size: 200%;">ü</span>
</body>
</html>
</code>```

I would appreciate if someone could check under FF on Windows. I am pretty sure it won't work on a non Windows box.

答:
You can add a little white one with a Base64 Encoded GIF (online generator here):

```<code>url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==")
</code>```

With Chrome, for instance, I use it to style the checkbox control:

```<code>INPUT[type=checkbox]:focus
{
outline:1px solid rgba(0,0,0,0.2);
}

INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
-webkit-appearance: button;
width: 17px;
height: 17px;
margin-top: 1px;
cursor:pointer;
}

INPUT[type=checkbox]:checked
{
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
</code>```

If you just wanted it in an IMG tag, you would do the checkmark/tickmark as:

```<code><img alt="" src="data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==" width="11" height="10">
</code>```

OwnerDisplayName: Totophil

Title: Tick symbol in HTML/XHTML

Body:
We need to display a tick symbol (✓ or ✔) within an internal web app and would ideally like to avoid using an image.

Has to work starting with IE 6.0.2900 on a XP box, ideally we need it be cross-browser (IE + recent versions of FF).

The following displays boxes although sets browser encoding to UTF-8 (META works nicely and not the issue). The default font is Times New Roman (might be an issue, but trying Lucida Sans Unicode doesn't help and I don't have neither Arial Unicode MS, nor Lucida Grande installed).

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

 ✓ ✔

Any help appreciated.

The following works under IE 6.0 and IE 7:

 ü

I would appreciate if someone could check under FF on Windows. I am pretty sure it won't work on a non Windows box.

LastEditorDisplayName: Totophil

Body:
You can add a little white one with a Base64 Encoded GIF (online generator here):

url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==")

With Chrome, for instance, I use it to style the checkbox control:

INPUT[type=checkbox]:focus
{
outline:1px solid rgba(0,0,0,0.2);
}

INPUT[type=checkbox]
{
background-color: #DDD;
border-radius: 2px;
-webkit-appearance: button;
width: 17px;
height: 17px;
margin-top: 1px;
cursor:pointer;
}

INPUT[type=checkbox]:checked
{
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}

If you just wanted it in an IMG tag, you would do the checkmark/tickmark as:

<img alt="" src="data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==" width="11" height="10">


问:
"Signature not valid" when getting API data (VBA-Excel)
I have an issue when I try to retrieve some data in excel through VBA code.
I used the following as basis: https://github.com/BitMEX/api-connectors/tree/master/official-http/vba
and it works, I was able to update it according to my need and place an order (testnet)

I now try to retrieve the book but I always get "Signature not valid" as response.
Can you please help understand what's I am doing wrong?

The data I want to receive is the following:
https://testnet.bitmex.com/api/explorer/#!/OrderBook/OrderBook_getL2

As Hash function, I use the HexHash function available in the link provided above (and it works for the 'Post' instruction but can't make it works for the "GET" instruction.

Thanks in advance

Bellow a working code (POST function):

```<code>Sub placeorder()
Dim Json, httpObject As Object
Dim nonce As Double
Dim verb, apiKey, apiSecret, signature, symbol, price, qty, url, postdata, replytext, nonceStr As String

' Set monotonically (w time) increasing nonce
nonce = DateDiff("s", "1/1/1970", Now)

' Set api key and secret
apiKey = "aaa"
apiSecret = "bbb"

' Build query
symbol = "XBTUSD"
price = 8000
qty = 1

verb = "POST"
url = "/api/v1/order"
postdata = "symbol=" & symbol & "&price=" & price & "&quantity=" & qty

' Stringize nonce
nonceStr = nonce

' Compute signature using hexhash script
signature = HexHash.HexHash(verb + url + nonceStr + postdata, apiSecret, "SHA256")

' Set up HTTP req with headers
Set httpObject = CreateObject("MSXML2.XMLHTTP")
httpObject.Open "POST", "https://testnet.bitmex.com" & url, False
httpObject.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpObject.setRequestHeader "api-nonce", nonceStr
httpObject.setRequestHeader "api-key", apiKey
httpObject.setRequestHeader "api-signature", signature
httpObject.Send (postdata)

' Catch response
replytext = httpObject.ResponseText

end sub()
</code>```

Bellow a NON-working code (GET function):

```<code>Sub getorderbook2()
Dim Json, httpObject As Object
Dim nonce As Double
Dim verb, apiKey, apiSecret, signature, symbol, url, getdata, replytext,
depth As String
Dim nonceStr As String

' Set monotonically (w time) increasing nonce
nonce = DateDiff("s", "1/1/1970", Now)

' Set api key and secret
apiKey = "aaa"
apiSecret = "bbb"

' Build query
symbol = "XBTUSD"
depth = 3

verb = "GET"
url = "/api/v1/orderBook/L2"
getdata = "symbol=" & symbol & "&depth=" & depth

' Stringize nonce
nonceStr = nonce

' Compute signature using hexhash script
signature = HexHash.HexHash(verb + url + nonceStr + getdata, apiSecret, "SHA256")

' Set up HTTP req with headers
Set httpObject = CreateObject("MSXML2.XMLHTTP")
httpObject.Open "GET", "https://testnet.bitmex.com" & url, False
httpObject.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpObject.setRequestHeader "api-nonce", nonceStr
httpObject.setRequestHeader "api-key", apiKey
httpObject.setRequestHeader "api-signature", signature
httpObject.Send (getdata)

' Catch response
replytext = httpObject.ResponseText
end sub ()
</code>```

In the second section, I always get an error message in return "Signature not valid"

答:
Switching between GET and POST requires more than just changing the verb in the request. A GET request needs to have the data as part of the URL string so try:

```<code>url = url & "?" & getdata
getdata = ""
httpObject.Open "GET", "https://testnet.bitmex.com" & url, False
</code>```

You also need to change this line from:

```<code>httpObject.Send (getdata)
</code>```

to:

```<code>httpObject.Send
</code>```

The way in which you construct the api-signature value is also different for GET requests to this API - see here for details. The changes I have suggested should lead to the correct signature being generated. If you need to URL encode data in VBA then this answer might help.

Other issues:

Dim a, b As String is equivalent to Dim a As Variant, b As String. To declare multiple String variables you need to write Dim a As String, b As String

CreateObject("MSXML2.XMLHTTP") accesses the older version 3.0 of MSXML2. To access the most recent version 6.0, you need CreateObject("MSXML2.XMLHTTP.6.0")

Body:
I have an issue when I try to retrieve some data in excel through VBA code.
I used the following as basis: https://github.com/BitMEX/api-connectors/tree/master/official-http/vba
and it works, I was able to update it according to my need and place an order (testnet)

I now try to retrieve the book but I always get "Signature not valid" as response.
Can you please help understand what's I am doing wrong?

The data I want to receive is the following:
https://testnet.bitmex.com/api/explorer/#!/OrderBook/OrderBook_getL2

As Hash function, I use the HexHash function available in the link provided above (and it works for the 'Post' instruction but can't make it works for the "GET" instruction.

Thanks in advance

Bellow a working code (POST function):

Sub placeorder()
Dim Json, httpObject As Object
Dim nonce As Double
Dim verb, apiKey, apiSecret, signature, symbol, price, qty, url, postdata, replytext, nonceStr As String

' Set monotonically (w time) increasing nonce
nonce = DateDiff("s", "1/1/1970", Now)

' Set api key and secret
apiKey = "aaa"
apiSecret = "bbb"

' Build query
symbol = "XBTUSD"
price = 8000
qty = 1

verb = "POST"
url = "/api/v1/order"
postdata = "symbol=" & symbol & "&price=" & price & "&quantity=" & qty

' Stringize nonce
nonceStr = nonce

' Compute signature using hexhash script
signature = HexHash.HexHash(verb + url + nonceStr + postdata, apiSecret, "SHA256")

' Set up HTTP req with headers
Set httpObject = CreateObject("MSXML2.XMLHTTP")
httpObject.Open "POST", "https://testnet.bitmex.com" & url, False
httpObject.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpObject.setRequestHeader "api-nonce", nonceStr
httpObject.setRequestHeader "api-key", apiKey
httpObject.setRequestHeader "api-signature", signature
httpObject.Send (postdata)

' Catch response
replytext = httpObject.ResponseText

end sub()

Bellow a NON-working code (GET function):

Sub getorderbook2()
Dim Json, httpObject As Object
Dim nonce As Double
Dim verb, apiKey, apiSecret, signature, symbol, url, getdata, replytext,
depth As String
Dim nonceStr As String

' Set monotonically (w time) increasing nonce
nonce = DateDiff("s", "1/1/1970", Now)

' Set api key and secret
apiKey = "aaa"
apiSecret = "bbb"

' Build query
symbol = "XBTUSD"
depth = 3

verb = "GET"
url = "/api/v1/orderBook/L2"
getdata = "symbol=" & symbol & "&depth=" & depth

' Stringize nonce
nonceStr = nonce

' Compute signature using hexhash script
signature = HexHash.HexHash(verb + url + nonceStr + getdata, apiSecret, "SHA256")

' Set up HTTP req with headers
Set httpObject = CreateObject("MSXML2.XMLHTTP")
httpObject.Open "GET", "https://testnet.bitmex.com" & url, False
httpObject.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
httpObject.setRequestHeader "api-nonce", nonceStr
httpObject.setRequestHeader "api-key", apiKey
httpObject.setRequestHeader "api-signature", signature
httpObject.Send (getdata)

' Catch response
replytext = httpObject.ResponseText
end sub ()

In the second section, I always get an error message in return "Signature not valid"

Body:
Switching between GET and POST requires more than just changing the verb in the request. A GET request needs to have the data as part of the URL string so try:

url = url & "?" & getdata
getdata = ""
httpObject.Open "GET", "https://testnet.bitmex.com" & url, False

You also need to change this line from:

httpObject.Send (getdata)

to:

httpObject.Send

The way in which you construct the api-signature value is also different for GET requests to this API - see here for details. The changes I have suggested should lead to the correct signature being generated. If you need to URL encode data in VBA then this answer might help.

Other issues:

Dim a, b As String is equivalent to Dim a As Variant, b As String. To declare multiple String variables you need to write Dim a As String, b As String

CreateObject("MSXML2.XMLHTTP") accesses the older version 3.0 of MSXML2. To access the most recent version 6.0, you need CreateObject("MSXML2.XMLHTTP.6.0")


问:
How to get file content in java?
to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

```<code>Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();
}
</code>```

Does the java api provide a way to get the content with one line of code like:

```<code>String content = FileUtils.readFileToString(new File("file.txt"))
</code>```

答:
commons-io has:</p>

```<code>IOUtils.toString(new FileReader("file.txt"), "utf-8");
</code>```

Title: How to get file content in java?

Body:
to get the content of a txt file I usually use a scanner and iterate over each line to get the content:

Scanner sc = new Scanner(new File("file.txt"));
while(sc.hasNextLine()){
    String str = sc.nextLine();
}

Does the java api provide a way to get the content with one line of code like:

String content = FileUtils.readFileToString(new File("file.txt"))

Body:
commons-io has:

IOUtils.toString(new FileReader("file.txt"), "utf-8");


问:
How do i call method from another class with parameter?
I'm a beginner Android programming. How do I call method from another class with parameter.

I tried with method()it work. but I don't know how to with parameter

@class b

```<code>public class GetUrl {
static Context context;
public GetUrl(Context c) {
    context = c;

}
public String getJSONUrl(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) { // Download OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download result..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}
}
</code>```

I want to call in Class A

In class A how to call it?

答:
You can use this site to learn the basics. </p>

```<code>public class A(){
        public A(){   //Empty constructor
        }

        public void someMethod(){
        }

        public void someMethodThatTakesString(String string){
        //do something with the string passed
        }

        public static void anotherMethod(){
        }
    }
    //You call this class and it's method
    A.anotherMethod(); //because this method is static
    A classA = new A();
    classA.someMethod();
    String someString = "I am string"
    classA.someMethodThatTakesString(someString)
</code>```

Body:
I'm a beginner Android programming. How do I call method from another class with parameter.

I tried with method()it work. but I don't know how to with parameter

@class b

public class GetUrl {
static Context context;
public GetUrl(Context c) {
    context = c;

}
public String getJSONUrl(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) { // Download OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download result..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}
}

I want to call in Class A

In class A how to call it?

Body:
You can use this site to learn the basics.

public class A(){
        public A(){   //Empty constructor
        }

        public void someMethod(){
        }

        public void someMethodThatTakesString(String string){
        //do something with the string passed
        }

        public static void anotherMethod(){
        }
    }
    //You call this class and it's method
    A.anotherMethod(); //because this method is static
    A classA = new A();
    classA.someMethod();
    String someString = "I am string"
    classA.someMethodThatTakesString(someString)


问:
How would one sum the individual indexes within a single array in PHP?
No matter how much I look at the docs, I just cannot grasp adding (+) two arrays individual indexes together. Could someone please explain how I would achieve the below result?

Sample array:

```<code>array1 = [1,0,2,3,4];
array2 = [3,5,6,7,8];
</code>```

Expected Output:

```<code>[4, 5, 8, 10, 12]
</code>```

I tried

```<code>$arrSum = $array1 + $array2;
</code>```

But alas it wasn't the result I was looking for.

```<code>$arrSum Array
(
    [0] => 1
    [1] => 0
    [2] => 2
    [3] => 3
    [4] => 4
)
</code>```

答:
```<code>$array1 = [1,0,2,3,4];
$array2 = [3,5,6,7,8];

function sum_values($a, $b) {
    return $a+$b;
}

$output = array_map('sum_values', $array1, $array2);
</code>```

If the array sizes are different it will treat the missing values as 0. So if you had these arrays:

```<code>$array1 = [1,2,3,4,5];
$array2 = [1,2];
</code>```

The output would be:

```<code>$output = [2,4,3,4,5];
</code>```

Body:
No matter how much I look at the docs, I just cannot grasp adding (+) two arrays individual indexes together. Could someone please explain how I would achieve the below result?

Sample array:

array1 = [1,0,2,3,4];
array2 = [3,5,6,7,8];

Expected Output:

[4, 5, 8, 10, 12]

I tried

$arrSum = $array1 + $array2;

But alas it wasn't the result I was looking for.

$arrSum Array
(
    [0] => 1
    [1] => 0
    [2] => 2
    [3] => 3
    [4] => 4
)

Body:
$array1 = [1,0,2,3,4];
$array2 = [3,5,6,7,8];

function sum_values($a, $b) {
    return $a+$b;
}

$output = array_map('sum_values', $array1, $array2);

If the array sizes are different it will treat the missing values as 0. So if you had these arrays:

$array1 = [1,2,3,4,5];
$array2 = [1,2];

The output would be:

$output = [2,4,3,4,5];


答:
The string.capwords won't work for this, because internally, it uses str.split() to generate tokens (docs). str.split() can only split on runs of whitespace (default behavior) or using a user-specified character/string (docs). If a string is specified, it is considered as a whole, and not as separated characters.

To achieve what you want, I would use regular expressions, for example:

```<code>import re

x = "Men's L/s button-up"
y = re.sub(r'[\w]+', lambda m: m.group(0).capitalize(), x)
print(y)
# "Men'S L/S Button-Up"
</code>```

re.sub (docs) can be used to replace substrings inside the given string. The second argument there is a function that takes a match object argument and returns the replacement string (in this case, we capitalize the full match).

If you stumble across this question, also make sure to look at @Christian answer just below this, as it provides a nice alternative way to split the string :)

Title: Capitalizing first letter of each token of a string split on punctuation and whitespace

Body:
The string.capwords won't work for this, because internally, it uses str.split() to generate tokens (docs). str.split() can only split on runs of whitespace (default behavior) or using a user-specified character/string (docs). If a string is specified, it is considered as a whole, and not as separated characters.

To achieve what you want, I would use regular expressions, for example:

import re

x = "Men's L/s button-up"
y = re.sub(r'[\w]+', lambda m: m.group(0).capitalize(), x)
print(y)
# "Men'S L/S Button-Up"

re.sub (docs) can be used to replace substrings inside the given string. The second argument there is a function that takes a match object argument and returns the replacement string (in this case, we capitalize the full match).

If you stumble across this question, also make sure to look at @Christian answer just below this, as it provides a nice alternative way to split the string :)