问:
Stop foreach loop when curl return 200
I try to communicate with my Proxmox cluster which contain 3 servers, from API. Goal is to connect to at least 1 of these servers in case of failure then execute other code (not visible here).

With the below code, I connect to these servers 1 by 1 using "foreach" and I want this loop stop when one server return "200" from Curl (so I can continue with this online server). For the test, I stopped the first server and let online the others 2 but the "foreach" loop keep connect the third server.

Any idea ? Thank you and sorry for my english.

```<code><?php

$datas = array(
    array(
        "apiurl" => "192.168.1.34:8006",
        "node" => "pve1",
        "user" => "root",
        "userpass" => "pass",
    ),
    array(
        "apiurl" => "192.168.1.35:8006",
        "node" => "pve2",
        "user" => "root",
        "userpass" => "pass",
    ),
    array(
        "apiurl" => "192.168.1.36:8006",
        "node" => "pve3",
        "user" => "root",
        "userpass" => "pass",
    )
);

do {
    foreach ($datas as $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'@pam&password='.$data['userpass']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        $headers = array();
        $headers[] = 'Content-Type: application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
        }
        else {
            $myArray = json_decode($result, true);
            $cookie = $myArray['data']['ticket'];
            $info = curl_getinfo($ch);
            echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
        }
    curl_close($ch);
    }
} while ($info['http_code'] !== 200);
?>
</code>```

答:
You can break out of an outer loop by giving an argument to break. break 2 means to break out of the second containing loop.

```<code>while (true) {
    foreach ($datas as $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'@pam&password='.$data['userpass']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        $headers = array();
        $headers[] = 'Content-Type: application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
        }
        else {
            $myArray = json_decode($result, true);
            $cookie = $myArray['data']['ticket'];
            $info = curl_getinfo($ch);
            echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
            if ($info['http_code'] == 200) {
                break 2;
            }
        }
        curl_close($ch);
    }
}
</code>```

Title: Stop foreach loop when curl return 200

Body:
I try to communicate with my Proxmox cluster which contain 3 servers, from API. Goal is to connect to at least 1 of these servers in case of failure then execute other code (not visible here).

With the below code, I connect to these servers 1 by 1 using "foreach" and I want this loop stop when one server return "200" from Curl (so I can continue with this online server). For the test, I stopped the first server and let online the others 2 but the "foreach" loop keep connect the third server.

Any idea ? Thank you and sorry for my english.

<?php

$datas = array(
    array(
        "apiurl" => "192.168.1.34:8006",
        "node" => "pve1",
        "user" => "root",
        "userpass" => "pass",
    ),
    array(
        "apiurl" => "192.168.1.35:8006",
        "node" => "pve2",
        "user" => "root",
        "userpass" => "pass",
    ),
    array(
        "apiurl" => "192.168.1.36:8006",
        "node" => "pve3",
        "user" => "root",
        "userpass" => "pass",
    )
);

do {
    foreach ($datas as $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'@pam&password='.$data['userpass']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        $headers = array();
        $headers[] = 'Content-Type: application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')
';
        }
        else {
            $myArray = json_decode($result, true);
            $cookie = $myArray['data']['ticket'];
            $info = curl_getinfo($ch);
            echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")
";
        }
    curl_close($ch);
    }
} while ($info['http_code'] !== 200);
?>

Body:
You can break out of an outer loop by giving an argument to break. break 2 means to break out of the second containing loop.

while (true) {
    foreach ($datas as $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'@pam&password='.$data['userpass']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        $headers = array();
        $headers[] = 'Content-Type: application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
        }
        else {
            $myArray = json_decode($result, true);
            $cookie = $myArray['data']['ticket'];
            $info = curl_getinfo($ch);
            echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
            if ($info['http_code'] == 200) {
                break 2;
            }
        }
        curl_close($ch);
    }
}


来源: stackexchange

问:
How do I debounce one function, will immediately invoking another function when using onChange in React?

Problem

When a user checks/un-checks a checkbox, a post request is made via the onChange event. In order to avoid hammering the API, I am using _.debounce. However, I want to immediately update state when the onChange event is fired.

I understand that my current code wont't allow for that, since I am updating state in updateTodoItem(), which is run in the debounced handleChange() function.

Question.

How do I continue to debounce the post request, while immediacy invoking this.setState()?

Simplified Code

```<code>...
import _ from "lodash";
import axios from "axios";
import setAxiosHeaders from "./AxiosHeaders";
class TodoItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      complete: this.props.todoItem.complete
    };
    this.handleChange = this.handleChange.bind(this);
    this.updateTodoItem = this.updateTodoItem.bind(this);
    this.inputRef = React.createRef();
    this.completedRef = React.createRef();
    this.path = `/api/v1/todo_items/${this.props.todoItem.id}`;
  }
  handleChange() {
    this.updateTodoItem();
  }
  updateTodoItem() {
    this.setState({
      complete: this.completedRef.current.checked
    });
    setAxiosHeaders();
    axios
      .put(this.path, {
        todo_item: {
          title: this.inputRef.current.value,
          complete: this.completedRef.current.checked
        }
      })
      .then(response => {})
      .catch(error => {
        console.log(error);
      });
  }
  render() {
    const { todoItem } = this.props;
    return (
      <tr className={`${this.state.complete ? "table-light" : ""}`}>
        <td>
          ...
        </td>
        <td className="text-right">
          <div className="form-check form-check-inline">
            <input
              type="boolean"
              defaultChecked={this.state.complete}
              type="checkbox"
              onChange={_.debounce(this.handleChange, 1000)}
              ref={this.completedRef}
              className="form-check-input"
              id={`complete-${todoItem.id}`}
            />
            <label
              className="form-check-label"
              htmlFor={`complete-${todoItem.id}`}
            >
              Complete?
            </label>
          </div>
        </td>
      </tr>
    );
  }
}

export default TodoItem;
</code>```

答:
I just needed to call _.debounce() on updateTodoItem.

```<code>handleChange() {
  this.setState({
    complete: this.completedRef.current.checked
  });
  this.updateTodoItem();
}
updateTodoItem = _.debounce(() => {
  setAxiosHeaders();
  axios
    .put(this.path, {
      todo_item: {
        title: this.inputRef.current.value,
        complete: this.completedRef.current.checked
      }
    })
    .then(response => {})
    .catch(error => {
      console.log(error);
    });
}, 1000);
</code>```

```<code><input
  type="boolean"
  defaultChecked={this.state.complete}
  type="checkbox"
  onChange={this.handleChange}
  ref={this.completedRef}
  className="form-check-input"
  id={`complete-${todoItem.id}`}
/>;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Problem

When a user checks/un-checks a checkbox, a post request is made via the onChange event. In order to avoid hammering the API, I am using _.debounce. However, I want to immediately update state when the onChange event is fired.

I understand that my current code wont't allow for that, since I am updating state in updateTodoItem(), which is run in the debounced handleChange() function.

Question.

How do I continue to debounce the post request, while immediacy invoking this.setState()?

Simplified Code

...
import _ from "lodash";
import axios from "axios";
import setAxiosHeaders from "./AxiosHeaders";
class TodoItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      complete: this.props.todoItem.complete
    };
    this.handleChange = this.handleChange.bind(this);
    this.updateTodoItem = this.updateTodoItem.bind(this);
    this.inputRef = React.createRef();
    this.completedRef = React.createRef();
    this.path = `/api/v1/todo_items/${this.props.todoItem.id}`;
  }
  handleChange() {
    this.updateTodoItem();
  }
  updateTodoItem() {
    this.setState({
      complete: this.completedRef.current.checked
    });
    setAxiosHeaders();
    axios
      .put(this.path, {
        todo_item: {
          title: this.inputRef.current.value,
          complete: this.completedRef.current.checked
        }
      })
      .then(response => {})
      .catch(error => {
        console.log(error);
      });
  }
  render() {
    const { todoItem } = this.props;
    return (
      <tr className={`${this.state.complete ? "table-light" : ""}`}>

          ...

            <input
              type="boolean"
              defaultChecked={this.state.complete}
              type="checkbox"
              onChange={_.debounce(this.handleChange, 1000)}
              ref={this.completedRef}
              className="form-check-input"
              id={`complete-${todoItem.id}`}
            />
            <label
              className="form-check-label"
              htmlFor={`complete-${todoItem.id}`}
            >
              Complete?

    );
  }
}

export default TodoItem;

Body:
I just needed to call _.debounce() on updateTodoItem.

handleChange() {
  this.setState({
    complete: this.completedRef.current.checked
  });
  this.updateTodoItem();
}
updateTodoItem = _.debounce(() => {
  setAxiosHeaders();
  axios
    .put(this.path, {
      todo_item: {
        title: this.inputRef.current.value,
        complete: this.completedRef.current.checked
      }
    })
    .then(response => {})
    .catch(error => {
      console.log(error);
    });
}, 1000);

<input
  type="boolean"
  defaultChecked={this.state.complete}
  type="checkbox"
  onChange={this.handleChange}
  ref={this.completedRef}
  className="form-check-input"
  id={`complete-${todoItem.id}`}
/>;


问:
Cannot control legend.position in ggplot2 when using facet_wrap()
In the following code and graphs using mtcars data as example, I try to put the legend at bottom. It works fine without using theme_bw() in the first graph. Once I add theme_bw(), the legend moves to the right. What have I done wrong, and how to fix this? Thanks.

library(tidyverse)
mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am)
             )
         ) +
  geom_boxplot() +
  facet_wrap(vars(vs)) +
  theme(legend.position = "bottom",
        legend.title = element_blank())
```

<p><img src="https://i.imgur.com/I6luNJo.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am))) +
  geom_boxplot() +
  facet_wrap(vars(vs)) +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  theme_bw()
</code>```

Created on 2020-02-20 by the reprex package (v0.3.0)

答:
You need to reverse the order of theme and theme_bw because theme_bw would override the setting in theme if theme_bw is at the end.

```<code>library(ggplot2)
library(magrittr)

mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am))) +
  geom_boxplot() +
  facet_wrap(vars(mtcars$vs)) +
  theme_bw() +
  theme(legend.position = "bottom",
        legend.title = element_blank())
</code>```

Body:
In the following code and graphs using mtcars data as example, I try to put the legend at bottom. It works fine without using theme_bw() in the first graph. Once I add theme_bw(), the legend moves to the right. What have I done wrong, and how to fix this? Thanks.

library(tidyverse)
mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am)
             )
         ) +
  geom_boxplot() +
  facet_wrap(vars(vs)) +
  theme(legend.position = "bottom",
        legend.title = element_blank())

mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am))) +
  geom_boxplot() +
  facet_wrap(vars(vs)) +
  theme(legend.position = "bottom",
        legend.title = element_blank()) +
  theme_bw()

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
You need to reverse the order of theme and theme_bw because theme_bw would override the setting in theme if theme_bw is at the end.

library(ggplot2)
library(magrittr)

mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am))) +
  geom_boxplot() +
  facet_wrap(vars(mtcars$vs)) +
  theme_bw() +
  theme(legend.position = "bottom",
        legend.title = element_blank())


问:
NoClassDefFoundError Being Encountered Intermittently When Using ZoneRulesProvider
I know that this is somehow similar to this question, but the answer there doesn't seem to help me. But I am also encountering the same issue.. here's a snippet of the logs,

```<code>java.lang.NoClassDefFoundError: Could not initialize class
java.time.zone.ZoneRulesProvider
java.time.ZoneRegion.ofId(ZoneRegion.java:120)
java.time.ZoneId.of(ZoneId.java:411)
java.time.ZoneId.of(ZoneId.java:359)
java.time.ZoneId.of(ZoneId.java:315)
java.util.TimeZone.toZoneId(TimeZone.java:556)
java.time.ZoneId.systemDefault(ZoneId.java:274)
</code>```

And it seems like it's coming from using ZoneId.systemDefault() in my utility method,

    public  static String formatDate(Date date) {
        if(Objects.nonNull(date)) {
            LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            return localDate.format(<some_formats_here>);
        }

        return null;
    }
```

<p>The environment is using,</p>

```openjdk version "1.8.0_242"
OpenJDK Runtime Environment (build 1.8.0_242-b08)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)
```

Any help would be appreciated!

By the way, this occurs intermittently and happens after deploying the latest codes to the server. I have not encountered it in my local machine's build even though the environment set up are the same with production environment.

Thanks!

答:
Turns out that JVM_HOME must be declared on a system level according to my colleague. This part of code was the one spitting up the problem:

```<code>try {
            String libDir = System.getProperty("java.home") + File.separator + "lib";
            try (DataInputStream dis = new DataInputStream(
                     new BufferedInputStream(new FileInputStream(
                         new File(libDir, "tzdb.dat"))))) {
                load(dis);
            }
        } catch (Exception ex) {
            throw new ZoneRulesException("Unable to load TZDB time-zone rules", ex);
        }
</code>```

Unfortunately I can't really elaborate on how it was really solved but so far it worked for us. Might help others.

Body:
I know that this is somehow similar to this question, but the answer there doesn't seem to help me. But I am also encountering the same issue.. here's a snippet of the logs,

java.lang.NoClassDefFoundError: Could not initialize class
java.time.zone.ZoneRulesProvider
java.time.ZoneRegion.ofId(ZoneRegion.java:120)
java.time.ZoneId.of(ZoneId.java:411)
java.time.ZoneId.of(ZoneId.java:359)
java.time.ZoneId.of(ZoneId.java:315)
java.util.TimeZone.toZoneId(TimeZone.java:556)
java.time.ZoneId.systemDefault(ZoneId.java:274)

And it seems like it's coming from using ZoneId.systemDefault() in my utility method,

    public  static String formatDate(Date date) {
        if(Objects.nonNull(date)) {
            LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            return localDate.format(<some_formats_here>);
        }

        return null;
    }

The environment is using,

openjdk version "1.8.0_242"
OpenJDK Runtime Environment (build 1.8.0_242-b08)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)

Any help would be appreciated!

By the way, this occurs intermittently and happens after deploying the latest codes to the server. I have not encountered it in my local machine's build even though the environment set up are the same with production environment.

Thanks!

Body:
Turns out that JVM_HOME must be declared on a system level according to my colleague. This part of code was the one spitting up the problem:

try {
            String libDir = System.getProperty("java.home") + File.separator + "lib";
            try (DataInputStream dis = new DataInputStream(
                     new BufferedInputStream(new FileInputStream(
                         new File(libDir, "tzdb.dat"))))) {
                load(dis);
            }
        } catch (Exception ex) {
            throw new ZoneRulesException("Unable to load TZDB time-zone rules", ex);
        }

Unfortunately I can't really elaborate on how it was really solved but so far it worked for us. Might help others.


问:
jquery dialog button to do the same as asp.net mvc submit button
I have tried to figure out a way of letting a jquery dialog button called Create do the same as an asp.net submit button.

```<code><input type="submit" value="Create" />
</code>```

I am using jquery 1.3.2

I have come up with the following to let the dialog use the correct controller method.

```<code>       var url = '<%= Url.Action("Create1", "Home") %>';
       $.post(url,data,
                            function(data) {
                                alert("Successful. Id for this client is " + data.ClientNo);
                                $("#CreateForm input").attr("value", ""); // Success
                            },
                            "json"); // DataType
</code>```

However, the method requires a model parameter

```<code>    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create1(ClientDetail client)
</code>```

Looking at http://api.jquery.com/jQuery.post/ data parameter is a map or string sent to the server

I am wondering is it possible to convert a model into a map or string possibly using the .attr method?

Thank you

答:
What I can suggest you to do is : let the signature accept all your parameters, and you on the  server side will construct your object, and save it to your data store.

consider the following one:

```<code>    [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create1(string clientName, string clientTitle, int clientAge)
    {
           var client = new Client()
                         {
                           name = clientName,
                           title = clientTitle,
                           age = clientAge,
                           ..,
                           .., etc
                         }
    }
</code>```

let me know if this works for you, and don't forget to mark as answer if it really helped you

Thanks.

ContentLicense: CC BY-SA 3.0

Body:
I have tried to figure out a way of letting a jquery dialog button called Create do the same as an asp.net submit button.

<input type="submit" value="Create" />

I am using jquery 1.3.2

I have come up with the following to let the dialog use the correct controller method.

       var url = '<%= Url.Action("Create1", "Home") %>';
       $.post(url,data,
                            function(data) {
                                alert("Successful. Id for this client is " + data.ClientNo);
                                $("#CreateForm input").attr("value", ""); // Success
                            },
                            "json"); // DataType

However, the method requires a model parameter

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create1(ClientDetail client)

Looking at http://api.jquery.com/jQuery.post/ data parameter is a map or string sent to the server

I am wondering is it possible to convert a model into a map or string possibly using the .attr method?

Thank you

Body:
What I can suggest you to do is : let the signature accept all your parameters, and you on the  server side will construct your object, and save it to your data store.

consider the following one:

    [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create1(string clientName, string clientTitle, int clientAge)
    {
           var client = new Client()
                         {
                           name = clientName,
                           title = clientTitle,
                           age = clientAge,
                           ..,
                           .., etc
                         }
    }

let me know if this works for you, and don't forget to mark as answer if it really helped you

Thanks.


答:
What you have here is an infinite loop, because as you stated you already know the last 2 servers in the array won't respond successfully, yet your foreach loop will try all 3 regardless of success or failure. So by the time you get to the 3rd iteration of the foreach loop you get a failed response and then you reach the end of the while loop which determines the condition is still true and continues. To prevent this simply break from the foreach loop once success is determined. Because only then will the condition of the while loop become false. You can also break out of both loops if you'd like (using break 2). Either one is correct. The only difference is if you wanted any remaining logic inside the outter (while) loop to happen regardless of success or failure.

```<code>foreach ($datas as $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'@pam&password='.$data['userpass']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        $headers = array();
        $headers[] = 'Content-Type: application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
        }
        else {
            $myArray = json_decode($result, true);
            $cookie = $myArray['data']['ticket'];
            $info = curl_getinfo($ch);
            echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
            if (!empty($info['http_code']) && $info['http_code'] == 200) {
                break; // break out of either or both loops since we got a valid response
            }
        }
    curl_close($ch);
}
</code>```

Title: Stop foreach loop when curl return 200

Body:
What you have here is an infinite loop, because as you stated you already know the last 2 servers in the array won't respond successfully, yet your foreach loop will try all 3 regardless of success or failure. So by the time you get to the 3rd iteration of the foreach loop you get a failed response and then you reach the end of the while loop which determines the condition is still true and continues. To prevent this simply break from the foreach loop once success is determined. Because only then will the condition of the while loop become false. You can also break out of both loops if you'd like (using break 2). Either one is correct. The only difference is if you wanted any remaining logic inside the outter (while) loop to happen regardless of success or failure.

foreach ($datas as $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://'.$data['apiurl'].'/api2/json/access/ticket');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.$data['user'].'@pam&password='.$data['userpass']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);

        $headers = array();
        $headers[] = 'Content-Type: application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            echo 'Server ' .$data['node']. ' is not reachable (error : ' .curl_error($ch). ')<br>';
        }
        else {
            $myArray = json_decode($result, true);
            $cookie = $myArray['data']['ticket'];
            $info = curl_getinfo($ch);
            echo "Server " .$data['node']. " is reachable (code is : " .$info['http_code']. ")<br>";
            if (!empty($info['http_code']) && $info['http_code'] == 200) {
                break; // break out of either or both loops since we got a valid response
            }
        }
    curl_close($ch);
}


问:
Is EASTL vector<vector<int>> contiguous
As per this answer:

std::vector of std::vectors contiguity

A vector of vectors is not contiguous. EASTL claims that their vector is contgiuous (see: https://github.com/electronicarts/EASTL/blob/master/include/EASTL/vector.h it). Does this contiguity apply to a vector of vectors?

答:
What they mean is that the memory allocated by their vectors will be contiguous.  Any memory allocated by the contained elements are not a part of this.

So yes, their vectors are contiguous.  And no, that does not apply to all the contained elements as a group.

Title: Is EASTL vector<vector<int>> contiguous


问:
How do I format my output in Java for this specific instance to add spaces?
Here is what I'm trying to accomplish. When you enter numbers in this format

```<code>1 2 2 3 3 4 4 5 6
</code>```

you get

```<code>1 1 2 2 3 2 4 2 5 1 6 1
</code>```

In other words it tells you how many of each string you have. The problem is I can't figure out how to get there to be spaces in between the output. This is the code:

import java.util.Scanner;

public class RunLengthEncoding {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        String c = " ";

        char ch = 0;
        int count = 1;

        for (int x = 0; x < input.length(); x++)
            if (input.charAt(x) != ' ') {
                if (ch == input.charAt(x)) {
                    count = count + 1;

                } else {
                    c = c + ch;
                    if (count != 1) {
                        c = c + count;
                    }

                    ch = input.charAt(x);
                    count = 1;
                }
            }

        c = c + ch;

        if (count != 1) {
            c = c + count;
        }

        System.out.println("encoder output:");
        System.out.println(c);
        System.out.println("\t");
    }
}
```

答:
Everywhere, where you update the String just add a space in between the original string and the count variable.

```<code>    c = c + " " +ch;
</code>```

A few tweaks could be made to this code such as using StringBuilder or using the += operation rather than c = c + " " + ch; since that minimizes the line to only c+=" " + ch; As well as updating count using count++

Body:
Here is what I'm trying to accomplish. When you enter numbers in this format

1 2 2 3 3 4 4 5 6

you get

1 1 2 2 3 2 4 2 5 1 6 1

In other words it tells you how many of each string you have. The problem is I can't figure out how to get there to be spaces in between the output. This is the code:

import java.util.Scanner;

public class RunLengthEncoding {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a sequence of integers separated by spaces:");
        String input = scan.nextLine();
        System.out.println("Input: " + input);
        String c = " ";

        char ch = 0;
        int count = 1;

        for (int x = 0; x < input.length(); x++)
            if (input.charAt(x) != ' ') {
                if (ch == input.charAt(x)) {
                    count = count + 1;

                } else {
                    c = c + ch;
                    if (count != 1) {
                        c = c + count;
                    }

                    ch = input.charAt(x);
                    count = 1;
                }
            }

        c = c + ch;

        if (count != 1) {
            c = c + count;
        }

        System.out.println("encoder output:");
        System.out.println(c);
        System.out.println("\t");
    }
}

Body:
Everywhere, where you update the String just add a space in between the original string and the count variable.

    c = c + " " +ch;

A few tweaks could be made to this code such as using StringBuilder or using the += operation rather than c = c + " " + ch; since that minimizes the line to only c+=" " + ch; As well as updating count using count++


问:
MFC: Show or minimize (to hide) window on startup
In CWinApp::InitInstance() I have:

```<code>if (!ProcessShellCommand(cmdInfo))
  return FALSE;
m_pMainWnd->ShowWindow(m_MinimizeOnStartup ? SW_SHOWMINIMIZED : SW_SHOWNORMAL);
m_pMainWnd->UpdateWindow();
</code>```

But my ShowWindow call is not resulting in an OnSize() or OnShowWindow() callback?  During the ProcessShellCommand() those are called a few times as the first OnShowWindow() restores the window size when last shutdown via SetWindowPlacement().  That all works good, restoring to last state, but ProcessShellCommand() afterwards calls ShowWindow with SW_SHOW which causes a my hidden when minimized window to show on the taskbar.   Where is the proper place to either show the window or minimize it (to hide it).   Basically what happens is the minimize comes in (on SetWindowPlacement(), window is hidden, MFC later calls SW_SHOW which makes it minimized on the taskbar instead of hidden, my forced ShowWindow() doesn't do anything.

TIA!!

答: There is no OnSize() nor OnShowWindow() callback on ShowWindow() when already in those states.    Set m_nCmdShow=SW_HIDE in CAppWnd then at the end of the InitInstance() call the SetWindowPlacement()

Body:
In CWinApp::InitInstance() I have:

if (!ProcessShellCommand(cmdInfo))
  return FALSE;
m_pMainWnd->ShowWindow(m_MinimizeOnStartup ? SW_SHOWMINIMIZED : SW_SHOWNORMAL);
m_pMainWnd->UpdateWindow();

But my ShowWindow call is not resulting in an OnSize() or OnShowWindow() callback?  During the ProcessShellCommand() those are called a few times as the first OnShowWindow() restores the window size when last shutdown via SetWindowPlacement().  That all works good, restoring to last state, but ProcessShellCommand() afterwards calls ShowWindow with SW_SHOW which causes a my hidden when minimized window to show on the taskbar.   Where is the proper place to either show the window or minimize it (to hide it).   Basically what happens is the minimize comes in (on SetWindowPlacement(), window is hidden, MFC later calls SW_SHOW which makes it minimized on the taskbar instead of hidden, my forced ShowWindow() doesn't do anything.

TIA!!


问:
GET or POST when reading request body
Should I use the GET or POST method when sending information to a server in the body of the HTTP request?  There are no query parameters appended to the URL, the server will inspect the body of the request for what it needs.</p>

答:
A nice description and interesting discussion on the topic:

http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/

Title: GET or POST when reading request body


问:
rxjs - stop observable with a subject subscription
I created an Observable generating potentially infinite amount of data (e.g. a timer). This data is accessed through a subject, so multiple observers would receive the same values.

How to stop the Observable generating new values? (without modifying the implementation of the Observable)

```<code>// custom Observable, to visualize internal behavior
const timer$ = new rxjs.Observable(subscriber => {
  console.log("observable init");

  var counter = 0;
  const intervalId = setInterval(() => {
    ++counter;
    console.log("observable %s",counter);
    subscriber.next(counter);
  }, 1000);

  return () => {
    console.log("observable teardown");
    clearTimeout(intervalId);
  }
});

// subscribe through a subject
const subject$ = new rxjs.Subject();
timer$.subscribe(subject$);

const subscription = subject$.subscribe(value => console.log("observer %s", value));

// cancel subscription
setTimeout(() => {
  console.log("unsubscribe observer");
  subscription.unsubscribe();
  // TODO how to stop Observable generating new values?
}, 3000);
</code>```

jsfiddle: https://jsfiddle.net/gy4tfd5w/

答:
Here's my solution to stop a crazy observable mid-flow.

By using a signal Subject and the rxjs operator: takeUntil

Example

const stopSignal$ = new Subject();

infinitelyGenerating$
  .pipe(takeUntil(stopSignal$))
  .subscribe(val => {
    if (val === 'bad') {
      stopSignal$.next()
    }
  })
```

Body:
I created an Observable generating potentially infinite amount of data (e.g. a timer). This data is accessed through a subject, so multiple observers would receive the same values.

How to stop the Observable generating new values? (without modifying the implementation of the Observable)

// custom Observable, to visualize internal behavior
const timer$ = new rxjs.Observable(subscriber => {
  console.log("observable init");

  var counter = 0;
  const intervalId = setInterval(() => {
    ++counter;
    console.log("observable %s",counter);
    subscriber.next(counter);
  }, 1000);

  return () => {
    console.log("observable teardown");
    clearTimeout(intervalId);
  }
});

// subscribe through a subject
const subject$ = new rxjs.Subject();
timer$.subscribe(subject$);

const subscription = subject$.subscribe(value => console.log("observer %s", value));

// cancel subscription
setTimeout(() => {
  console.log("unsubscribe observer");
  subscription.unsubscribe();
  // TODO how to stop Observable generating new values?
}, 3000);

jsfiddle: https://jsfiddle.net/gy4tfd5w/


问:
Mean function using values from double array displaying wrong values
Very new to C, anyways been coding a program where you enter pairs of doubles which are stored in separate arrays. I have created a function to get the mean of the numbers but when I call it inside main the values are different. Any ideas?

MEAN FUNCTION:

```<code>mean(double *arr)
{
    double sum = 0.0;
    double meanValue = 0.0;
    int i;

    for (i = 0; i < arr[i]; i++)
    {
        sum += arr[i];
        meanValue = sum / i;
    }

    printf("\nmean: %.3lf", meanValue);
}
</code>```

MAIN:

```<code>double num1[1001];
mean(num1);
</code>```

And, I am getting the num1 and num2 values using:

```<code>for (k = 0; (scanf_s("%lf,%lf", &num1[k], &num2[k] ) == 2); k++)
</code>```

答:
The function needs to know how many of the array elements it should process.

```<code>mean(double *arr, int size)
{
    double sum = 0.0;
    double meanValue = 0.0;
    int i;

    for (i = 0; i < size; i++)
    {
        sum += arr[i];
    }
    meanValue = size > 0 ? sum / size : 0;

    printf("\nmean: %.3lf", meanValue);
}
</code>```

The size is the value of k after the input loop is done, so you call it:

```<code>mean(num1, k);
</code>```

Body:
Very new to C, anyways been coding a program where you enter pairs of doubles which are stored in separate arrays. I have created a function to get the mean of the numbers but when I call it inside main the values are different. Any ideas?

MEAN FUNCTION:

mean(double *arr)
{
    double sum = 0.0;
    double meanValue = 0.0;
    int i;

    for (i = 0; i < arr[i]; i++)
    {
        sum += arr[i];
        meanValue = sum / i;
    }

    printf("\nmean: %.3lf", meanValue);
}

MAIN:

double num1[1001];
mean(num1);

And, I am getting the num1 and num2 values using:

for (k = 0; (scanf_s("%lf,%lf", &num1[k], &num2[k] ) == 2); k++)

Body:
The function needs to know how many of the array elements it should process.

mean(double *arr, int size)
{
    double sum = 0.0;
    double meanValue = 0.0;
    int i;

    for (i = 0; i < size; i++)
    {
        sum += arr[i];
    }
    meanValue = size > 0 ? sum / size : 0;

    printf("\nmean: %.3lf", meanValue);
}

The size is the value of k after the input loop is done, so you call it:

mean(num1, k);


问:
Query to get the count of logins by a user within a set time interval from previous login
I want to get a count of how many times a user logs in within, let's say, 5 hours from the previous login.

So something like new_login - old_login < 5 hours.

The login table would have user_id and time_accessed.

This query is to get the count of user logins within a day. I can't figure out how to compare the different times within the same column within the same statement:

```<code>SELECT user_id, date(time_accessed), count(user_id) AS login_within_5_hour_period
FROM login
GROUP BY user_id, date(time_accessed)
ORDER BY time_accessed;
</code>```

Sample input

```<code>+---------+---------------------+
| user_id |    time_accessed    |
+---------+---------------------+
| 1       | 2020-02-19 09:00:00 |
| 1       | 2020-02-19 12:00:00 |
| 1       | 2020-02-19 13:00:00 |
| 1       | 2020-02-19 19:00:00 |
+---------+---------------------+
</code>```

Sample ouput

```<code>+---------+---------------------+----------------------------+
| user_id | date(time_accessed) | login_within_5_hour_period |
+---------+---------------------+----------------------------+
| 1       | 2020-02-19          | 3                          |
| 1       | 2020-02-19          | 1                          |
+---------+---------------------+----------------------------+
</code>```

答:
In order to compare different times, you need to join the table with itself.

The following query will find the number of logins by the user within 5 hours, excluding the current login. If you want to include the current login in the count, change this l1.time_accessed > l2.time_accessed to l1.time_accessed >= l2.time_accessed.

```<code>SELECT l1.user_id, l1.time_accessed, COUNT(l2.user_id) AS login_within_5_hour_period
FROM logins l1
LEFT JOIN logins l2
    ON l1.user_id = l2.user_id
    AND l1.time_accessed > l2.time_accessed
    AND TIME_TO_SEC(TIMEDIFF(l1.time_accessed, l2.time_accessed)) / 3600 <= 5
GROUP BY l1.user_id, l1.time_accessed;
</code>```

This second query will return a single result, showing the number of logins by the user within 5 hours of the time specified.

```<code>SELECT l1.user_id, l1.time_accessed, COUNT(l2.user_id) AS login_within_5_hour_period
FROM logins l1
LEFT JOIN logins l2
    ON l1.user_id = l2.user_id
    AND l1.time_accessed > l2.time_accessed
    AND TIME_TO_SEC(TIMEDIFF(l1.time_accessed, l2.time_accessed)) / 3600 <= 5
WHERE l1.time_accessed = '2020-02-19 19:00:00'
GROUP BY l1.user_id, l1.time_accessed;
</code>```

Working example: https://www.db-fiddle.com/f/g7jDYqoKn38iQTFuPjej9m/1

Body:
I want to get a count of how many times a user logs in within, let's say, 5 hours from the previous login.

So something like new_login - old_login < 5 hours.

The login table would have user_id and time_accessed.

This query is to get the count of user logins within a day. I can't figure out how to compare the different times within the same column within the same statement:

SELECT user_id, date(time_accessed), count(user_id) AS login_within_5_hour_period
FROM login
GROUP BY user_id, date(time_accessed)
ORDER BY time_accessed;

Sample input

+---------+---------------------+
| user_id |    time_accessed    |
+---------+---------------------+
| 1       | 2020-02-19 09:00:00 |
| 1       | 2020-02-19 12:00:00 |
| 1       | 2020-02-19 13:00:00 |
| 1       | 2020-02-19 19:00:00 |
+---------+---------------------+

Sample ouput

+---------+---------------------+----------------------------+
| user_id | date(time_accessed) | login_within_5_hour_period |
+---------+---------------------+----------------------------+
| 1       | 2020-02-19          | 3                          |
| 1       | 2020-02-19          | 1                          |
+---------+---------------------+----------------------------+

Body:
In order to compare different times, you need to join the table with itself.

The following query will find the number of logins by the user within 5 hours, excluding the current login. If you want to include the current login in the count, change this l1.time_accessed > l2.time_accessed to l1.time_accessed >= l2.time_accessed.

SELECT l1.user_id, l1.time_accessed, COUNT(l2.user_id) AS login_within_5_hour_period
FROM logins l1
LEFT JOIN logins l2
    ON l1.user_id = l2.user_id
    AND l1.time_accessed > l2.time_accessed
    AND TIME_TO_SEC(TIMEDIFF(l1.time_accessed, l2.time_accessed)) / 3600 <= 5
GROUP BY l1.user_id, l1.time_accessed;

This second query will return a single result, showing the number of logins by the user within 5 hours of the time specified.

SELECT l1.user_id, l1.time_accessed, COUNT(l2.user_id) AS login_within_5_hour_period
FROM logins l1
LEFT JOIN logins l2
    ON l1.user_id = l2.user_id
    AND l1.time_accessed > l2.time_accessed
    AND TIME_TO_SEC(TIMEDIFF(l1.time_accessed, l2.time_accessed)) / 3600 <= 5
WHERE l1.time_accessed = '2020-02-19 19:00:00'
GROUP BY l1.user_id, l1.time_accessed;

Working example: https://www.db-fiddle.com/f/g7jDYqoKn38iQTFuPjej9m/1


问:
Outcome of BehaviorSpace
I am simulating a classroom to find the total energy consumption from appliances of a classroom. Now I want to run the simulation in BehaviorSpace so that I get the energy consumption by varying the number of students in the classroom.

```<code>         globals[
        temp1 a s simulation-timer number-of-seats number-of-lights
       number-of-fans number-of-acs gap row col x-cor y-cor half half2
       student-no t-light t-fan t-ac t-energy
              ]
          breed [seats seat]
         breeed [seat-teachers seat-teacher]
         breed [lights light]
         breed [fans fan]
         breed [acs ac ]
         breed [students student ]

         to setup
         clear-all

          ask patches [ set pcolor 9 ]
          set gap floor ((max-pxcor) / (no-of-row-or-col) )
          set half ceiling (gap / 2)
          set half2 floor (gap / 2)
          place-seat-teachers
          place-seats-students
          place-lights
          place-fans
          place-acs
          ask patches with [ pxcor = 3 * gap + half2 ] [ set pcolor 4 ]
          ask patches with [ pxcor = 6 * gap + half2 ] [ set pcolor 4 ]
          create-students-classroom
          reset-ticks
          reset-timer
          end

          to go
          while [simulation-timer < time ] [

          move-students
          set simulation-timer simulation-timer + 1
          tick ]
           stop
            end

            to create-students-classroom
            create-students number-of-students [
             set entry-time random threshold + 1                         ;
              set random-entry time to each student

            let stu-no sort-on [who] students
            foreach stu-no [x -> ask x [ show (word x " -> " entry-time )
            ] ]
            set shape "person"
            set color 3
               ]
           set s sort [who] of seats
          set a first s

          end

           to move-students

           let l length s

           set temp1 simulation-timer
           tick

          ask students [ if ( entry-time = temp1 )
              [
    move-to seat a
   set color red
    appliance-on
    show (word temp1 "," l "," a)
    set s remove a s
    set a a + 1
    set l length s
  ]
]
  end

   to appliance-on

     ask lights with [not l-on? and any? students in-radius 4]
     [ switch-light-on ]
      ask fans with [not f-on? and any? students in-radius 4]
      [ switch-fan-on]
        ask acs with [ not a-on? and any? students in-radius 9]
      [ switch-ac-on]

        stop

         end
         to switch-light-on
         set color green
         set l-on? true
          set light-turned-on simulation-timer
         set light-on-duration light-on-duration + (time - light-turned-on
          )
            type "light on duration " print light-on-duration
           end

            to-report energy-calculation

           ask lights [ ifelse ( l-on? )  [ set l-energy (light-on-
            duration * light-wattage) ][ set l-energy 0 ] ]
             ask fans [ ifelse ( f-on? ) [ set f-energy ( fan-on-duration
            * fan-wattage )] [ set f-energy 0 ] ]
            ask acs [ ifelse ( a-on? ) [ set a-energy (ac-on-duration *
             ac-wattage) ] [ set a-energy 0 ] ]

             let light-e sum [l-energy] of lights
              let fan-e sum [f-energy] of fans
              let ac-e sum [a-energy] of acs

              set t-light ( light-e / (60000))
              set t-fan ( fan-e / (60000))
              set t-ac ( ac-e / ( 60000 ) )

              show (word "sum of ac energy = " ac-e )

               report ( t-light + t-fan + t-ac )

                  end
</code>```

In the BehaviorSpace: measure runs using these reporters I am putting energy-calculation but in the spreadsheet everything is showing zero. Why is this happening?

答:
Abdullah,

I can't run your code as you've provided it, but I suspect that the problem lies in your go procedure. BehaviorSpace treats the go procedure as a forever button, that is it keeps running until either the number of ticks exceeds the Time limit or until it is stopped by some other user-supplied condition.  Moreover, BS runs the reporters listed under Measure runs using these reporters only at the end of each iteration of the go procedure. It assumes each iteration takes a tick. Your go procedure, however, only runs once.  The while loop is executed time times, but that is all within the first (and only) iteration of go, after which the simulation is stopped by the stop command.  I'm not sure why you are using simulation-timer instead of ticks to keep tract of the time, but let me suggest a go procedure that will do what I suspect you want.

```<code>to go
  move-students
  tick
  if ticks > time [ stop ]
end
</code>```

In this case, go will keep going, and BS will report energy-calculation at the end of each iteration of go, until the number of iterations (ticks) exceeds time.  If you set Time limit in BS to time, the if statement will be redundant, but not if you are also running the model outside of BS. (If you are running from the interface tab, the go button should be a "forever" button.)

You also have a redundant stop at the end of your appliance-on procedure.

I may have missed something important in what you are trying to do, but perhaps this will get you started in solving your problem.

Title: Outcome of BehaviorSpace

Body:
I am simulating a classroom to find the total energy consumption from appliances of a classroom. Now I want to run the simulation in BehaviorSpace so that I get the energy consumption by varying the number of students in the classroom.

         globals[
        temp1 a s simulation-timer number-of-seats number-of-lights
       number-of-fans number-of-acs gap row col x-cor y-cor half half2
       student-no t-light t-fan t-ac t-energy
              ]
          breed [seats seat]
         breeed [seat-teachers seat-teacher]
         breed [lights light]
         breed [fans fan]
         breed [acs ac ]
         breed [students student ]

         to setup
         clear-all

          ask patches [ set pcolor 9 ]
          set gap floor ((max-pxcor) / (no-of-row-or-col) )
          set half ceiling (gap / 2)
          set half2 floor (gap / 2)
          place-seat-teachers
          place-seats-students
          place-lights
          place-fans
          place-acs
          ask patches with [ pxcor = 3 * gap + half2 ] [ set pcolor 4 ]
          ask patches with [ pxcor = 6 * gap + half2 ] [ set pcolor 4 ]
          create-students-classroom
          reset-ticks
          reset-timer
          end

          to go
          while [simulation-timer < time ] [

          move-students
          set simulation-timer simulation-timer + 1
          tick ]
           stop
            end

            to create-students-classroom
            create-students number-of-students [
             set entry-time random threshold + 1                         ;
              set random-entry time to each student

            let stu-no sort-on [who] students
            foreach stu-no [x -> ask x [ show (word x " -> " entry-time )
            ] ]
            set shape "person"
            set color 3
               ]
           set s sort [who] of seats
          set a first s

          end

           to move-students

           let l length s

           set temp1 simulation-timer
           tick

          ask students [ if ( entry-time = temp1 )
              [
    move-to seat a
   set color red
    appliance-on
    show (word temp1 "," l "," a)
    set s remove a s
    set a a + 1
    set l length s
  ]
]
  end

   to appliance-on

     ask lights with [not l-on? and any? students in-radius 4]
     [ switch-light-on ]
      ask fans with [not f-on? and any? students in-radius 4]
      [ switch-fan-on]
        ask acs with [ not a-on? and any? students in-radius 9]
      [ switch-ac-on]

        stop

         end
         to switch-light-on
         set color green
         set l-on? true
          set light-turned-on simulation-timer
         set light-on-duration light-on-duration + (time - light-turned-on
          )
            type "light on duration " print light-on-duration
           end

            to-report energy-calculation

           ask lights [ ifelse ( l-on? )  [ set l-energy (light-on-
            duration * light-wattage) ][ set l-energy 0 ] ]
             ask fans [ ifelse ( f-on? ) [ set f-energy ( fan-on-duration
            * fan-wattage )] [ set f-energy 0 ] ]
            ask acs [ ifelse ( a-on? ) [ set a-energy (ac-on-duration *
             ac-wattage) ] [ set a-energy 0 ] ]

             let light-e sum [l-energy] of lights
              let fan-e sum [f-energy] of fans
              let ac-e sum [a-energy] of acs

              set t-light ( light-e / (60000))
              set t-fan ( fan-e / (60000))
              set t-ac ( ac-e / ( 60000 ) )

              show (word "sum of ac energy = " ac-e )

               report ( t-light + t-fan + t-ac )

                  end

In the BehaviorSpace: measure runs using these reporters I am putting energy-calculation but in the spreadsheet everything is showing zero. Why is this happening?

Body:
Abdullah,

I can't run your code as you've provided it, but I suspect that the problem lies in your go procedure. BehaviorSpace treats the go procedure as a forever button, that is it keeps running until either the number of ticks exceeds the Time limit or until it is stopped by some other user-supplied condition.  Moreover, BS runs the reporters listed under Measure runs using these reporters only at the end of each iteration of the go procedure. It assumes each iteration takes a tick. Your go procedure, however, only runs once.  The while loop is executed time times, but that is all within the first (and only) iteration of go, after which the simulation is stopped by the stop command.  I'm not sure why you are using simulation-timer instead of ticks to keep tract of the time, but let me suggest a go procedure that will do what I suspect you want.

to go
  move-students
  tick
  if ticks > time [ stop ]
end

In this case, go will keep going, and BS will report energy-calculation at the end of each iteration of go, until the number of iterations (ticks) exceeds time.  If you set Time limit in BS to time, the if statement will be redundant, but not if you are also running the model outside of BS. (If you are running from the interface tab, the go button should be a "forever" button.)

You also have a redundant stop at the end of your appliance-on procedure.

I may have missed something important in what you are trying to do, but perhaps this will get you started in solving your problem.


问:
Why a task run in OpenMP threads actually takes longer than in serial?
I have writtem this code to estimate the value of an integral.

A straightforward and simple for()-loop in parallel, using openmp.

Whatever I do, I cannot reduce the running time in parallel to be less than in serial.

What is the problem?

lenmuta, tol, cores, seed are 1, 0.01, number_of_threads, 0 respectively.

Here is the code:

```<code>// ================= Libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include <sys/time.h>

int main( int argc, char* argv[] )
{
    float lenmuta = atof( argv[1] );
    float tol     = atof( argv[2] );
    int   cores   = atoi( argv[3] );
    int   seed    = atoi( argv[4] );

#define M  1 / ( tol*tol*0.01*lenmuta*lenmuta );

    unsigned int N = M;

    printf( "%10.5f \n", tol );
    printf(     "%d \n", N );

    omp_set_num_threads( cores );

    double sum2;
    int    Threadnum;
    float  rvalue;

    Threadnum = omp_get_max_threads();
    rvalue    = lenmuta / ( 1 + lenmuta * lenmuta );

    printf( "the true value is %f \n", rvalue );
    printf( "the number of threads we use is %d \n", Threadnum );

    struct random_data* state;
    double start1 = omp_get_wtime();
    int    k, i;
    double y;
    char   statebuf[32];

    state = malloc( sizeof( struct random_data ) );

    initstate_r( seed, statebuf, 32, state );
    srandom_r(   seed, state );

    // =========Parallel Region=======================

    #pragma omp parallel for private( i, y ) reduction( +:sum2 )
    for( i = 0; i < N; i++ )
    {
         y     = -( 1 / lenmuta ) * log( (double) rand() / ( (double) RAND_MAX ) );
         sum2 +=  cos( y );
    }
    sum2 = sum2 / N;

    printf( "Time: \t %f \n", omp_get_wtime() - start1 );
    printf( "the estimate value is %1.10f \n", sum2 );

    return 0;
    }
</code>```

答:
Speaking about performance?
 Code can run way faster ~ +4x (!) for 1E6 loops

Independently of using or not the OpenMP-tools, lets start with these. The OpenMP thread-management ( instantiations, task-distribution, results-collection -( a smart reduction(+:sum2) ) **all comes at some add-on cost - see the amounts** (proportions) of the assembly instructions spent on this ).

Given your #pragma-decorated code has paid all those add-on costs ( which it did, as instructed ) you gain almost nothing in return in exchange of the burnt expenses - but a reduction sum of 1E6 doubles ( 1E6 is as tiny as almost just a syntax-sugar, if compared to add-on costs-free pure-[SERIAL] code-execution, that sums the same in a snap ~ 18 [ms] if smart ( even less than ~ 70 [ms] if not ) as not burning add-on expenses on thread-management and task-distribution/result-collection overheads ( here ~ 400 [ms] for a 2-core sandboxed demo test ),

```<code>   0.01000
1000000
the true value is 0.500000      the number of threads we use is 2

OpenMP as-is    Time:    0.467055
SERIAL as-is    Time:    0.069820 <~~+            70 [ms] @ 1E6 loops
OpenMP Re-DEF'd Time:    0.328225    |            !!
SERIAL Re-DEF'd Time:    0.017899 <~~+~ 6x FASTER 18 [ms] @ 1E6 loops
</code>```

Erratum : mea culpa - the code avoided one fDIV for the bottom case ( re-tests show ~ +10% speedup - see the code )

Testing as low number of loops as 1E6 ( @-a-few-GHz-CPU-cores ... ) produces more noise than hard facts. Anyway, we can get faster in either of the strategies :

```<code>OpenMP as-is    Time:      0.375825     the estimate value is 0.5000982178
SERIAL as-is    Time:      0.062920     the estimate value is 0.5004906150
                                |||
                               ~300 [us]FASTER--v
OpenMP Re-DEF'd Time:      0.062613     the estimate value is 0.4992401088
                              ~2    [ms]SLOWER--^
                               ||||
SERIAL Re-DEF'd Time:      0.060253     the estimate value is 0.4995912559
</code>```

It is fair to note, that for longer looping the loop-incrementing overheads will generate more of the overall computing time, even with -O3, so the re-factored code will exhibit all time fastest results, yet the speedup factor will grow smaller to ~ 1.16x for 25E6 loops

The core flaw :
the awfully bad imbalance of costs:effects
hurts efficiency of any computation

There is actually almost nothing to compute ( a few fADD-s, fMUL, fNEG, fDIV-s, fLOG ) inside the most expensive syntax-constructor ( not mentioning the random ) that could never at least justify those costs, that have been spent on building the OpenMP code-execution eco-system (yet, we will show it could be even 6x reduced for FASTER runs ).

Why to ever re-calculate, the less do it MILLION+ TIMES a constant value?

So,
lets weed out things that ought never go into any performance motivated sections :

```<code>double C_LogRAND_MAX = log( (double) RAND_MAX );
double C_1divLENMUTA = -1 / lenmuta;
double C_2sub        = C_LogRAND_MAX * C_1divLENMUTA;
</code>```

and :

```<code>#pragma omp parallel for private( i, y ) reduction( +:sum2 )
for( i = 0; i < N; i++ )
{
     sum2 +=  cos( C_1divLENMUTA           // fMUL
                 * log( (double) rand() )  // +costs of keeping the seed-state management
                 - C_2sub                  // fSUB
                   );
}
</code>```

Last but not least, a parallel-sourcing of random-sequences deserves another closer look, as these tools try to maintain its internal state which can make troubles "across" the threads. Good news is, that Stack Overflow can serve a lot on solving this performance hitting subject.

```<code>w/o -O3:                                                                                =:_____________________________________________________________________:[ns]
SERIAL                     NOP       Time:     3.867352 DIV( 2000000000 ) ~   0.000000002     ~   2 [ns]:||:for(){...}loop-overhead                                           :
SERIAL                    RAND()     Time:    10.845900 DIV( 1000000000 ) ~   0.000000011     ~  +9 [ns]:  |||||||||:rand()                                                   :
SERIAL           (double) RAND()     Time:    10.923597 DIV( 1000000000 ) ~   0.000000011     ~  +0 [ns]:           :(double)                                                 :
SERIAL      LOG( (double) RAND() )   Time:    37.156017 DIV( 1000000000 ) ~   0.000000037     ~ +27 [ns]:           |||||||||||||||||||||||||||:log()                         :
SERIAL COS( LOG( (double) RAND() ) ) Time:    54.472115 DIV(  800000000 ) ~   0.000000068     ~ +31 [ns]:                                      |||||||||||||||||||||||||||||||:cos()
SERIAL COS( LOG( (double) RAND() ) ) Time:    55.320798 DIV(  800000000 ) ~   0.000000069               :                        w/o  -O3                                     :
w/-O3: :::( :::( (::::::) ::::() ) )          !!.       :::(  ::::::::: )              !!              =:____________:           :!                                           :
SERIAL COS( LOG( (double) RAND() ) ) Time:     9.305908 DIV(  800000000 ) ~   0.000000012     ~  12 [ns]:||||||||||||            with -O3                                     :
SERIAL COS( LOG( (double) RAND() ) ) Time:     2.135143 DIV(  200000000 ) ~   0.000000011               :                                                                     :
SERIAL      LOG( (double) RAND() )   Time:     2.082406 DIV(  200000000 ) ~   0.000000010               :                                                                     :
SERIAL           (double) RAND()     Time:     2.244600 DIV(  200000000 ) ~   0.000000011
SERIAL                    RAND()     Time:     2.101538 DIV(  200000000 ) ~   0.000000011
SERIAL                     NOP       Time:     0.000000 DIV(  200000000 ) ~   0.000000000
                                                                                ^^
                                                                                ||
                                                                                !||
                                                                                vvv
OpenMP COS( LOG( (double) RAND() ) ) Time:    33.336248 DIV(  100000000 ) ~   0.000000333  #pragma omp parallel num_threads(  2 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.388479 DIV(    1000000 ) ~   0.000000388  #pragma omp parallel num_threads(  2 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    37.636114 DIV(  100000000 ) ~   0.000000376  #pragma omp parallel num_threads(  2 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    38.876272 DIV(  100000000 ) ~   0.000000389  #pragma omp parallel num_threads(  2 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    44.226391 DIV(  100000000 ) ~   0.000000442  #pragma omp parallel num_threads(  2 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:     0.333573 DIV(    1000000 ) ~   0.000000334  #pragma omp parallel num_threads(  4 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    35.624111 DIV(  100000000 ) ~   0.000000356  #pragma omp parallel num_threads(  4 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    37.820558 DIV(  100000000 ) ~   0.000000378  #pragma omp parallel num_threads(  4 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    38.625498 DIV(  100000000 ) ~   0.000000386  #pragma omp parallel num_threads(  4 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    39.782386 DIV(  100000000 ) ~   0.000000398  #pragma omp parallel num_threads(  4 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:     0.317120 DIV(    1000000 ) ~   0.000000317  #pragma omp parallel num_threads(  8 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    34.692555 DIV(  100000000 ) ~   0.000000347  #pragma omp parallel num_threads(  8 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.360407 DIV(    1000000 ) ~   0.000000360  #pragma omp parallel num_threads(  8 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:     3.737517 DIV(   10000000 ) ~   0.000000374  #pragma omp parallel num_threads(  8 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.380087 DIV(    1000000 ) ~   0.000000380  #pragma omp parallel num_threads(  8 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:     0.354283 DIV(    1000000 ) ~   0.000000354  #pragma omp parallel num_threads( 16 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    35.984292 DIV(  100000000 ) ~   0.000000360  #pragma omp parallel num_threads( 16 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     3.654442 DIV(   10000000 ) ~   0.000000365  #pragma omp parallel num_threads( 16 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    37.233374 DIV(  100000000 ) ~   0.000000372  #pragma omp parallel num_threads( 16 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:     4.112637 DIV(   10000000 ) ~   0.000000411  #pragma omp parallel num_threads( 16 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:    37.813872 DIV(  100000000 ) ~   0.000000378  #pragma omp parallel num_threads( 32 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.412896 DIV(    1000000 ) ~   0.000000413  #pragma omp parallel num_threads( 32 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    34.098855 DIV(  100000000 ) ~   0.000000341  #pragma omp parallel num_threads( 32 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    35.372660 DIV(  100000000 ) ~   0.000000354  #pragma omp parallel num_threads( 32 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    39.256430 DIV(  100000000 ) ~   0.000000393  #pragma omp parallel num_threads( 32 ) with -O3

/////////////////////////////////////////////////////////////////////////////////////////////
//
// -O3
// warning: iteration 2147483647 invokes undefined behavior [-Waggressive-loop-optimizations]
//     for( i = 0; i < N; i++ )
//     ^~~
********************************************************************************************/
</code>```

Body:
I have writtem this code to estimate the value of an integral.

A straightforward and simple for()-loop in parallel, using openmp.

Whatever I do, I cannot reduce the running time in parallel to be less than in serial.

What is the problem?

lenmuta, tol, cores, seed are 1, 0.01, number_of_threads, 0 respectively.

Here is the code:

// ================= Libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include <sys/time.h>

int main( int argc, char* argv[] )
{
    float lenmuta = atof( argv[1] );
    float tol     = atof( argv[2] );
    int   cores   = atoi( argv[3] );
    int   seed    = atoi( argv[4] );

#define M  1 / ( tol*tol*0.01*lenmuta*lenmuta );

    unsigned int N = M;

    printf( "%10.5f \n", tol );
    printf(     "%d \n", N );

    omp_set_num_threads( cores );

    double sum2;
    int    Threadnum;
    float  rvalue;

    Threadnum = omp_get_max_threads();
    rvalue    = lenmuta / ( 1 + lenmuta * lenmuta );

    printf( "the true value is %f \n", rvalue );
    printf( "the number of threads we use is %d \n", Threadnum );

    struct random_data* state;
    double start1 = omp_get_wtime();
    int    k, i;
    double y;
    char   statebuf[32];

    state = malloc( sizeof( struct random_data ) );

    initstate_r( seed, statebuf, 32, state );
    srandom_r(   seed, state );

    // =========Parallel Region=======================

    #pragma omp parallel for private( i, y ) reduction( +:sum2 )
    for( i = 0; i < N; i++ )
    {
         y     = -( 1 / lenmuta ) * log( (double) rand() / ( (double) RAND_MAX ) );
         sum2 +=  cos( y );
    }
    sum2 = sum2 / N;

    printf( "Time: \t %f \n", omp_get_wtime() - start1 );
    printf( "the estimate value is %1.10f \n", sum2 );

    return 0;
    }

Body:
Speaking about performance?
 Code can run way faster ~ +4x (!) for 1E6 loops

Independently of using or not the OpenMP-tools, lets start with these. The OpenMP thread-management ( instantiations, task-distribution, results-collection -( a smart reduction(+:sum2) ) **all comes at some add-on cost - see the amounts** (proportions) of the assembly instructions spent on this ).

Given your #pragma-decorated code has paid all those add-on costs ( which it did, as instructed ) you gain almost nothing in return in exchange of the burnt expenses - but a reduction sum of 1E6 doubles ( 1E6 is as tiny as almost just a syntax-sugar, if compared to add-on costs-free pure-[SERIAL] code-execution, that sums the same in a snap ~ 18 [ms] if smart ( even less than ~ 70 [ms] if not ) as not burning add-on expenses on thread-management and task-distribution/result-collection overheads ( here ~ 400 [ms] for <a href="https://tio.run/##5VZrb9MwFP3eX3G1aiJ9pG064MO6IlVsSEhtN5UhIQGq3MRJLfKS7XRUsL9OuXacLA0VYoA2ISy1ie378jnnunXT1A5cd7fr92FcHzBlK044o6LRZLEbZh6FMyE9lvTWL/aXQrbaX4uIXO@vJFFac9uKvmQRVasNFkuICIstUG@EB24X3DXhbfW@ef8RWo0vDcDhhwmRENI4yiSBMTgjtYrlE5n4Vm7toPmoYi2TUE3QetAbDIajmvmwNFe5AdyEU6HNh5XgzFif1KwFpZ4JfsD6qbZuND3qs5jCDMCBPliqpLb6YEFO25ymeGoPFSqLBQtiDK8yzTHDzGykHFew/KNjZ9B75sOH@KirT2kqK/bVODr28v15GRepWAoql942JhFzLRgUjsVOnEVLueaUeMIyeBTOXpKtQgoii4ZVGOBam6NjFXngGxJm1LiWJngUlSnATBH5XGYyReQ@OaYFJAozBzrlvA11sEpM5JqC5BggD8MEHCNCEhEwgWsgaQcsakU5JD6YYuCGQiZydwWghvDuAEVWc/hPXWCjKjzbfKa/BCexZ@VCaVXWqz13RTgJQxrCggYsiceHxx4BknDpVJC8Uc1kVRM0U06CiCgLSIsEfsLV0TdEUmy2LmyhBZx6mSsxrwWdU8UstpsmMeFok0ubwRnM8dHpmM28H/XYmvayLS3vkhpFUxJYYOU1YyKFREuzWa4tJvPz5WzyDs1N8XroMjpj1Y6owW2xd9tQuOnNcf7oY1k1CVymNJ5dARE2E1p4iMwpagBUvzw3aqjhBnYB6SF9UIFWCFlFVE7PGZjWK@ooZYEl2vcejfLY@W2Sz39K879K0JuLxevJ9HEJumfvff2TUW3cl8tpEpSYjmsE3IE92ndyPLaZXsxnb68nisgKjTXDochWBUfjWrb2fiADxq9r7gGvFWTor6u2EOaPqj2g6IMpWnUIUZUG8t@4oBbUPr949cR7WP0/xOX03/Jc/vjW77rH4Vr/n6Iy43HB2e1u9831QxKIne0nqMMo3dmXJ@XEFizyvgM" rel="nofollow noreferrer">a 2-core sandboxed demo test ),

   0.01000
1000000
the true value is 0.500000      the number of threads we use is 2

OpenMP as-is    Time:    0.467055
SERIAL as-is    Time:    0.069820 <~~+            70 [ms] @ 1E6 loops
OpenMP Re-DEF'd Time:    0.328225    |            !!
SERIAL Re-DEF'd Time:    0.017899 <~~+~ 6x FASTER 18 [ms] @ 1E6 loops

Erratum : mea culpa - the code avoided one fDIV for the bottom case ( re-tests show ~ +10% speedup - see the <a href="https://tio.run/##5VZrb9MwFP3eX3G1aiJ9pG064MO6IlVsSEhtN5UhIQGq3MRJLfKS7XRUsL9OuXacLA0VYoA2ISy1ie378jnnunXT1A5cd7fr92FcHzBlK044o6LRZLEbZh6FMyE9lvTWL/aXQrbaX4uIXO@vJFFac9uKvmQRVasNFkuICIstUG@EB24X3DXhbfW@ef8RWo0vDcDhhwmRENI4yiSBMTgjtYrlE5n4Vm7toPmoYi2TUE3QetAbDIajmvmwNFe5AdyEU6HNh5XgzFif1KwFpZ4JfsD6qbZuND3qs5jCDMCBPliqpLb6YEFO25ymeGoPFSqLBQtiDK8yzTHDzGykHFew/KNjZ9B75sOH@KirT2kqK/bVODr28v15GRepWAoql942JhFzLRgUjsVOnEVLueaUeMIyeBTOXpKtQgoii4ZVGOBam6NjFXngGxJm1LiWJngUlSnATBH5XGYyReQ@OaYFJAozBzrlvA11sEpM5JqC5BggD8MEHCNCEhEwgWsgaQcsakU5JD6YYuCGQiZydwWghvDuAEVWc/hPXWCjKjzbfKa/BCexZ@VCaVXWqz13RTgJQxrCggYsiceHxx4BknDpVJC8Uc1kVRM0U06CiCgLSIsEfsLV0TdEUmy2LmyhBZx6mSsxrwWdU8UstpsmMeFok0ubwRnM8dHpmM28H/XYmvayLS3vkhpFUxJYYOU1YyKFREuzWa4tJvPz5WzyDs1N8XroMjpj1Y6owW2xd9tQuOnNcf7oY1k1CVymNJ5dARE2E1p4iMwpagBUvzw3aqjhBnYB6SF9UIFWCFlFVE7PGZjWK@ooZYEl2vcejfLY@W2Sz39K879K0JuLxevJ9HEJumfvff2TUW3cl8tpEpSYjmsE3IE92ndyPLaZXsxnb68nisgKjTXDochWBUfjWrb2fiADxq9r7gGvFWTor6u2EOaPqj2g6IMpWnUIUZUG8t@4oBbUPr949cR7WP0/xOX03/Jc/vjW77rH4Vr/n6Iy43HB2e1u9831QxKIne0nqMMo3dmXJ@XEFizyvgM" rel="nofollow noreferrer">code )

Testing as low number of loops as 1E6 ( @-a-few-GHz-CPU-cores ... ) produces more noise than hard facts. Anyway, we can get faster in either of the strategies :

OpenMP as-is    Time:      0.375825     the estimate value is 0.5000982178
SERIAL as-is    Time:      0.062920     the estimate value is 0.5004906150
                                |||
                               ~300 [us]FASTER--v
OpenMP Re-DEF'd Time:      0.062613     the estimate value is 0.4992401088
                              ~2    [ms]SLOWER--^
                               ||||
SERIAL Re-DEF'd Time:      0.060253     the estimate value is 0.4995912559

It is fair to note, that for longer looping the loop-incrementing overheads will generate more of the overall computing time, even with -O3, so the re-factored code will exhibit all time fastest results, yet the speedup factor will grow smaller to ~ 1.16x for 25E6 loops

The core flaw :
the awfully bad imbalance of costs:effects
hurts efficiency of any computation

There is actually almost nothing to compute ( a few fADD-s, fMUL, fNEG, fDIV-s, fLOG ) inside the most expensive syntax-constructor ( not mentioning the random ) that could never at least justify those costs, that have been spent on building the OpenMP code-execution eco-system (yet, we will show it could be even 6x reduced for FASTER runs ).

Why to ever re-calculate, the less do it MILLION+ TIMES a constant value?

So,
lets weed out things that ought never go into any performance motivated sections :

double C_LogRAND_MAX = log( (double) RAND_MAX );
double C_1divLENMUTA = -1 / lenmuta;
double C_2sub        = C_LogRAND_MAX * C_1divLENMUTA;

and :

#pragma omp parallel for private( i, y ) reduction( +:sum2 )
for( i = 0; i < N; i++ )
{
     sum2 +=  cos( C_1divLENMUTA           // fMUL
                 * log( (double) rand() )  // +costs of keeping the seed-state management
                 - C_2sub                  // fSUB
                   );
}

Last but not least, a parallel-sourcing of random-sequences deserves another closer look, as these tools try to maintain its internal state which can make troubles "across" the threads. Good news is, that Stack Overflow can serve a lot on solving this performance hitting subject.

w/o -O3:                                                                                =:_____________________________________________________________________:[ns]
SERIAL                     NOP       Time:     3.867352 DIV( 2000000000 ) ~   0.000000002     ~   2 [ns]:||:for(){...}loop-overhead                                           :
SERIAL                    RAND()     Time:    10.845900 DIV( 1000000000 ) ~   0.000000011     ~  +9 [ns]:  |||||||||:rand()                                                   :
SERIAL           (double) RAND()     Time:    10.923597 DIV( 1000000000 ) ~   0.000000011     ~  +0 [ns]:           :(double)                                                 :
SERIAL      LOG( (double) RAND() )   Time:    37.156017 DIV( 1000000000 ) ~   0.000000037     ~ +27 [ns]:           |||||||||||||||||||||||||||:log()                         :
SERIAL COS( LOG( (double) RAND() ) ) Time:    54.472115 DIV(  800000000 ) ~   0.000000068     ~ +31 [ns]:                                      |||||||||||||||||||||||||||||||:cos()
SERIAL COS( LOG( (double) RAND() ) ) Time:    55.320798 DIV(  800000000 ) ~   0.000000069               :                        w/o  -O3                                     :
w/-O3: :::( :::( (::::::) ::::() ) )          !!.       :::(  ::::::::: )              !!              =:____________:           :!                                           :
SERIAL COS( LOG( (double) RAND() ) ) Time:     9.305908 DIV(  800000000 ) ~   0.000000012     ~  12 [ns]:||||||||||||            with -O3                                     :
SERIAL COS( LOG( (double) RAND() ) ) Time:     2.135143 DIV(  200000000 ) ~   0.000000011               :                                                                     :
SERIAL      LOG( (double) RAND() )   Time:     2.082406 DIV(  200000000 ) ~   0.000000010               :                                                                     :
SERIAL           (double) RAND()     Time:     2.244600 DIV(  200000000 ) ~   0.000000011
SERIAL                    RAND()     Time:     2.101538 DIV(  200000000 ) ~   0.000000011
SERIAL                     NOP       Time:     0.000000 DIV(  200000000 ) ~   0.000000000
                                                                                ^^
                                                                                ||
                                                                                !||
                                                                                vvv
OpenMP COS( LOG( (double) RAND() ) ) Time:    33.336248 DIV(  100000000 ) ~   0.000000333  #pragma omp parallel num_threads(  2 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.388479 DIV(    1000000 ) ~   0.000000388  #pragma omp parallel num_threads(  2 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    37.636114 DIV(  100000000 ) ~   0.000000376  #pragma omp parallel num_threads(  2 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    38.876272 DIV(  100000000 ) ~   0.000000389  #pragma omp parallel num_threads(  2 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    44.226391 DIV(  100000000 ) ~   0.000000442  #pragma omp parallel num_threads(  2 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:     0.333573 DIV(    1000000 ) ~   0.000000334  #pragma omp parallel num_threads(  4 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    35.624111 DIV(  100000000 ) ~   0.000000356  #pragma omp parallel num_threads(  4 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    37.820558 DIV(  100000000 ) ~   0.000000378  #pragma omp parallel num_threads(  4 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    38.625498 DIV(  100000000 ) ~   0.000000386  #pragma omp parallel num_threads(  4 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    39.782386 DIV(  100000000 ) ~   0.000000398  #pragma omp parallel num_threads(  4 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:     0.317120 DIV(    1000000 ) ~   0.000000317  #pragma omp parallel num_threads(  8 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    34.692555 DIV(  100000000 ) ~   0.000000347  #pragma omp parallel num_threads(  8 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.360407 DIV(    1000000 ) ~   0.000000360  #pragma omp parallel num_threads(  8 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:     3.737517 DIV(   10000000 ) ~   0.000000374  #pragma omp parallel num_threads(  8 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.380087 DIV(    1000000 ) ~   0.000000380  #pragma omp parallel num_threads(  8 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:     0.354283 DIV(    1000000 ) ~   0.000000354  #pragma omp parallel num_threads( 16 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    35.984292 DIV(  100000000 ) ~   0.000000360  #pragma omp parallel num_threads( 16 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     3.654442 DIV(   10000000 ) ~   0.000000365  #pragma omp parallel num_threads( 16 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    37.233374 DIV(  100000000 ) ~   0.000000372  #pragma omp parallel num_threads( 16 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:     4.112637 DIV(   10000000 ) ~   0.000000411  #pragma omp parallel num_threads( 16 ) with -O3

OpenMP COS( LOG( (double) RAND() ) ) Time:    37.813872 DIV(  100000000 ) ~   0.000000378  #pragma omp parallel num_threads( 32 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:     0.412896 DIV(    1000000 ) ~   0.000000413  #pragma omp parallel num_threads( 32 ) w/o
OpenMP COS( LOG( (double) RAND() ) ) Time:    34.098855 DIV(  100000000 ) ~   0.000000341  #pragma omp parallel num_threads( 32 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    35.372660 DIV(  100000000 ) ~   0.000000354  #pragma omp parallel num_threads( 32 ) with -O3
OpenMP COS( LOG( (double) RAND() ) ) Time:    39.256430 DIV(  100000000 ) ~   0.000000393  #pragma omp parallel num_threads( 32 ) with -O3

/////////////////////////////////////////////////////////////////////////////////////////////
//
// -O3
// warning: iteration 2147483647 invokes undefined behavior [-Waggressive-loop-optimizations]
//     for( i = 0; i < N; i++ )
//     ^~~
********************************************************************************************/


问:
stackoverflow search api
I would like to use the search method of stackoverflow API to return the json structure of results based on a search keyword and then display those results (title, description and the url) in the SearchResults div.

I am new to C# and my first attempt went something like this:

```<code>    protected void searchStockOverflow(string y)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle="+y);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{ \"intitle\": \"" + y + "\"}";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();

            SearchResults.InnerHtml += "<div style='border:1px solid blue;margin:5px;'>";
            SearchResults.InnerHtml += responseText + "<br />";
            SearchResults.InnerHtml += "</div><br style='clear:both;' />";
        }
    }
</code>```

The issue is that what is returned looks like dingbats rubbish - i guess because it is serialized and need to be deserialized?

答:
I would definitely say consider using the REST client; however, to look at the issues... generally you want to deserialize the data as JSON manually, then run that data through your UI code. For example:

```<code>static void SearchStackOverflow(string y)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle=" + Uri.EscapeDataString(y));
    httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
    httpWebRequest.Method = "GET";
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    string responseText;
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        responseText = streamReader.ReadToEnd();
    }
    var result = (SearchResult)new JavaScriptSerializer().Deserialize(responseText, typeof(SearchResult));
    .... do something with result ...
}
class SearchResult
{
    public List<Question> questions { get; set; }
}
class Question
{
    public string title { get; set; }
    public int answer_count { get; set; }
}
</code>```

Which uses the JavaScriptSerializer from System.Web.Extensions.dll

Title: stackoverflow search api

Body:
I would like to use the search method of stackoverflow API to return the json structure of results based on a search keyword and then display those results (title, description and the url) in the SearchResults div.

I am new to C# and my first attempt went something like this:

    protected void searchStockOverflow(string y)
    {

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle="+y);
        httpWebRequest.ContentType = "text/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{ \"intitle\": \"" + y + "\"}";

            streamWriter.Write(json);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var responseText = streamReader.ReadToEnd();

            SearchResults.InnerHtml += "
";
            SearchResults.InnerHtml += responseText + "
";
            SearchResults.InnerHtml += "

";
        }
    }

The issue is that what is returned looks like dingbats rubbish - i guess because it is serialized and need to be deserialized?

Body:
I would definitely say consider using the REST client; however, to look at the issues... generally you want to deserialize the data as JSON manually, then run that data through your UI code. For example:

static void SearchStackOverflow(string y)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle=" + Uri.EscapeDataString(y));
    httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
    httpWebRequest.Method = "GET";
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    string responseText;
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        responseText = streamReader.ReadToEnd();
    }
    var result = (SearchResult)new JavaScriptSerializer().Deserialize(responseText, typeof(SearchResult));
    .... do something with result ...
}
class SearchResult
{
    public List<Question> questions { get; set; }
}
class Question
{
    public string title { get; set; }
    public int answer_count { get; set; }
}

Which uses the JavaScriptSerializer from System.Web.Extensions.dll


问:
Google Custom Search Does not show correct results
I'm creating an app in javascript in which I need some total number of google results. I tried using Google custom search api but it does not show all the results and the number of results are less than the number of results on google search.

Many people are facing this problem, I have tried some solutions but didn't work for me. I wonder how some sites are able to get exact results for a keyword on google.

答:
me too.
The result is 0 when searchType = image.
enter image description here</p>


问:
How to print the original stdout format of command by using spawn?
I am using the spawn to execute code-push, which sending an uploading progress to the terminal and with multiple colorful stdout messages.

const codePushProcess = spawn('code-push', [
  'release-react',
  `rrs-${platform}`,
  platform,
  `--deploymentName=${deploymentName}`,
  `--description=${desc}`,
  `--targetBinaryVersion=${version}`,
  '-m'
])
codePushProcess.stdout.on('data', chunk => {
  console.log(chunk.toString('utf8'))
})

codePushProcess.stderr.on('data', data => {
  console.error(`stderr: ${data}`)
})

codePushProcess.on('close', code => {
  if (code === 0) {
    console.log('CodePush Success!')
  } else {
    console.log(`CodePush process exited with code ${code}`)
  }
})
```

Here is a comparison:

When I am using console.log, chunks in the terminal are all white without original format, and missing the dynamic progress.

So how to sending the original format to the terminal?

答:
As Felix Kling mentioned, passing an option { stdio: 'inherit' } as third argument for spawn method will sending the stdio to parent process.

spawn(cmd, [], { stdio: 'inherit' })
```

'inherit': Pass through the corresponding stdio stream to/from the parent process. In the first three positions, this is equivalent to process.stdin, process.stdout, and process.stderr, respectively. In any other position, equivalent to 'ignore'.

Body:
I am using the spawn to execute code-push, which sending an uploading progress to the terminal and with multiple colorful stdout messages.

const codePushProcess = spawn('code-push', [
  'release-react',
  `rrs-${platform}`,
  platform,
  `--deploymentName=${deploymentName}`,
  `--description=${desc}`,
  `--targetBinaryVersion=${version}`,
  '-m'
])
codePushProcess.stdout.on('data', chunk => {
  console.log(chunk.toString('utf8'))
})

codePushProcess.stderr.on('data', data => {
  console.error(`stderr: ${data}`)
})

codePushProcess.on('close', code => {
  if (code === 0) {
    console.log('CodePush Success!')
  } else {
    console.log(`CodePush process exited with code ${code}`)
  }
})

Here is a comparison:

When I am using console.log, chunks in the terminal are all white without original format, and missing the dynamic progress.

So how to sending the original format to the terminal?

Body:
As Felix Kling mentioned, passing an option { stdio: 'inherit' } as third argument for spawn method will sending the stdio to parent process.

spawn(cmd, [], { stdio: 'inherit' })

'inherit': Pass through the corresponding stdio stream to/from the parent process. In the first three positions, this is equivalent to process.stdin, process.stdout, and process.stderr, respectively. In any other position, equivalent to 'ignore'.


问:
Truth tables in code? How to structure state machine?
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

```<code>u8 newState[] = decisionTable[input1][input2][input3][input4];
</code>```

And then I could access the output values with:

```<code>setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );
</code>```

But in order to get that, it looks like I would have to do a fairly confusing table like so:

```<code>static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};
</code>```

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

```<code>#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))
</code>```

And that will let my truth table array look like this:

```<code>static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};
</code>```

And I can then access my truth table like so:

```<code>decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]
</code>```

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

答: If the truth table is really only 4x4x4x4 then I'd use macros. If it's ever going to grow past that, I'd use Ragel. Chances are it will make smaller, faster C code than you will.</p>

OwnerDisplayName: HanClinto

ContentLicense: CC BY-SA 2.5

Body:
I have a (somewhat) large truth table / state machine that I need to implement in my code (embedded C). I anticipate the behavior specification of this state machine to change in the future, and so I'd like to keep this easily modifiable in the future.

My truth table has 4 inputs and 4 outputs. I have it all in an Excel spreadsheet, and if I could just paste that into my code with a little formatting, that would be ideal.

I was thinking I would like to access my truth table like so:

u8 newState[] = decisionTable[input1][input2][input3][input4];

And then I could access the output values with:

setOutputPin( LINE_0, newState[0] );
setOutputPin( LINE_1, newState[1] );
setOutputPin( LINE_2, newState[2] );
setOutputPin( LINE_3, newState[3] );

But in order to get that, it looks like I would have to do a fairly confusing table like so:

static u8 decisionTable[][][][][] =
 {{{{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }},
   {{ 0, 0, 0, 0 },
    { 0, 0, 0, 0 }}},
  {{{ 0, 0, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}},
 {{{{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}},
  {{{ 0, 1, 1, 1 },
    { 0, 1, 1, 1 }},
   {{ 0, 1, 0, 1 },
    { 1, 1, 1, 1 }}}};

Those nested brackets can be somewhat confusing -- does anyone have a better idea for how I can keep a pretty looking table in my code?

Thanks!

Edit based on HUAGHAGUAH's answer:

Using an amalgamation of everyone's input (thanks -- I wish I could "accept" 3 or 4 of these answers), I think I'm going to try it as a two dimensional array. I'll index into my array using a small bit-shifting macro:

#define SM_INPUTS( in0, in1, in2, in3 ) ((in0 << 0) | (in1 << 1) | (in2 << 2) | (in3 << 3))

And that will let my truth table array look like this:

static u8 decisionTable[][] = {
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 1, 1 },
{ 0, 1, 0, 1 },
{ 1, 1, 1, 1 }};

And I can then access my truth table like so:

decisionTable[ SM_INPUTS( line1, line2, line3, line4 ) ]

I'll give that a shot and see how it works out. I'll also be replacing the 0's and 1's with more helpful #defines that express what each state means, along with /**/ comments that explain the inputs for each line of outputs. Thanks for the help, everyone!

LastEditorDisplayName: Im safe against SQL injection