问:
php mail() not working windows 2003, IIS SMTP
I'm getting this problem:

```<code>PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12
</code>```

from this script:

```<code><?php
$to = "chris.mahan@gmail.com";
$subject = "test";
$body = "this is a test";

if (mail($to, $subject, $body)){
    echo "mail sent";
}
else {
    echo "problem";
}
?>
</code>```

section from php.ini on the server:

```<code>[mail function]
; For Win32 only.
SMTP = server.domain.com; for Win32 only
smtp_port = 25

; For Win32 only.
sendmail_from = support@domain.com
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =
</code>```

(note that "server" and "domain" refer accurately to the actual server and domain name)

In IIS, SMTP is running. Under "Access" tab, "Relay" button, the Select which computers may relay through this virtual server is set to checkbox "only the list below" and on the list is "127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).

Server is running Windows Server 2003 Service Pack 2, fully patched as of 5 PM Sept 1st 2008. I assume it is running IIS7 (how to check?).

Any ideas?

In reponse to Espo: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.

Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server  IP to the allowed list (using the reverse DNS button provided) and the thing started working.

Thanks to both Espo and Yaakov for helping me out.

答:
I had the same problem, php 5 on iis6, 2003 server. Php always failed when trying to use mail().
I've managed to get it accepting mail from php by changing the Relay Restrictions from 'Only the list below' (which is empty by default) to 'All except the list below' .
The relay restrictions can be found in the Access tab in the smtp servers properties screens.
Of course if the server is open to the internet then one would have to be more sensible about these relaying restrictions but in my case this is on a virtual server on a dev box.

hope that helps.

OwnerDisplayName: Christopher Mahan

Body:
I'm getting this problem:

PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12

from this script:

<?php
$to = "chris.mahan@gmail.com";
$subject = "test";
$body = "this is a test";

if (mail($to, $subject, $body)){
    echo "mail sent";
}
else {
    echo "problem";
}
?>

section from php.ini on the server:

[mail function]
; For Win32 only.
SMTP = server.domain.com; for Win32 only
smtp_port = 25

; For Win32 only.
sendmail_from = support@domain.com
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
;sendmail_path =

(note that "server" and "domain" refer accurately to the actual server and domain name)

In IIS, SMTP is running. Under "Access" tab, "Relay" button, the Select which computers may relay through this virtual server is set to checkbox "only the list below" and on the list is "127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address).

Server is running Windows Server 2003 Service Pack 2, fully patched as of 5 PM Sept 1st 2008. I assume it is running IIS7 (how to check?).

Any ideas?

In reponse to Espo: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server.

Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server  IP to the allowed list (using the reverse DNS button provided) and the thing started working.

Thanks to both Espo and Yaakov for helping me out.

LastEditorDisplayName: Christopher Mahan

OwnerDisplayName: Paul


来源: stackexchange

问:
VB.NET - For each checked item in listview
This is probably easy as well. But I have this listview which contains exe files I've listed up. Now, I want to execute these exe files in turn from which items are checked or not.

So, I've tried this:

```<code>For each item in listView1.CheckedItems
    Msgbox item.ToString
Next
</code>```

Cause I noticed that the item in checkedItems doesn't contain much. And if I convert it to a string, it ends up in the msgbox looking like this: ListViewItem: {Filename.exe}

Now, I want the filename obviously. But is there any other way of extracting the name only? Or do I have to strip the string to remove the ListViewItem: { part away?

答:
Your probably lookin for more of something like this. This will have the item and the subitems. You will need a loop with in a loop to accomplish this. Hopes this helps</p>

```<code>     Dim x As Integer = 0
     Dim y As Integer = 0
     For Each item In listView1.CheckedItems
         For Each subitem In listView1.CheckedItems(y).SubItems
            MsgBox(subitem.Text)
            x = x + 1
         Next
      y = y + 1
    Next
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is probably easy as well. But I have this listview which contains exe files I've listed up. Now, I want to execute these exe files in turn from which items are checked or not.

So, I've tried this:

For each item in listView1.CheckedItems
    Msgbox item.ToString
Next

Cause I noticed that the item in checkedItems doesn't contain much. And if I convert it to a string, it ends up in the msgbox looking like this: ListViewItem: {Filename.exe}

Now, I want the filename obviously. But is there any other way of extracting the name only? Or do I have to strip the string to remove the ListViewItem: { part away?

Body:
Your probably lookin for more of something like this. This will have the item and the subitems. You will need a loop with in a loop to accomplish this. Hopes this helps

     Dim x As Integer = 0
     Dim y As Integer = 0
     For Each item In listView1.CheckedItems
         For Each subitem In listView1.CheckedItems(y).SubItems
            MsgBox(subitem.Text)
            x = x + 1
         Next
      y = y + 1
    Next


问:
Redux: Notify parent React component when the child component dispatches a Redux action
My parent component is a React class that has a method in it which does a setInterval (amongst other things). This interval is cleared when some conditions are met.

However I want this method on the parent React class to be called once again when one of it's children dispatches a specific action (thereby re-setting the setInterval).

How do I notify the parent that the child had dispatched a certain (Redux) action? I'm using connect to pass the state down. So the parent and the children share the same dispatch method.

答:
Actually you can pass send action method from parent to child, call it in child component like this.props.someMethodToDispatch() and do something with it in parent component before you dispatch action.
For example:

const dispatch = (action) => console.info("Action dispatched", action);

class Parent extends React.Component {

  constructor(props) {
    super(props);
    this._handleChildClick = this._handleChildClick.bind(this);
  }

  _handleChildClick(action) {
    // You can do something here
    console.info("Child pass action", action);
    // And after that dispatch action
    dispatch(action);
  }

  render() {
    return (

Simulate handle action from child

        <Child handleClick={this._handleChildClick} />

    );
  }
}

class Child extends React.Component {

  _generateAction() {
    // This is action creator mock
    return {type: "SOME_ACTION", payload: "someting"};
  }

  render() {
    return (<button onClick={() => this.props.handleClick(this._generateAction())}>Click me</button>);
  }
}

ReactDOM.render(<Parent />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Body:
Actually you can pass send action method from parent to child, call it in child component like this.props.someMethodToDispatch() and do something with it in parent component before you dispatch action.
For example:

const dispatch = (action) => console.info("Action dispatched", action);

class Parent extends React.Component {

  constructor(props) {
    super(props);
    this._handleChildClick = this._handleChildClick.bind(this);
  }

  _handleChildClick(action) {
    // You can do something here
    console.info("Child pass action", action);
    // And after that dispatch action
    dispatch(action);
  }

  render() {
    return (
      <div>
        <h2>Simulate handle action from child</h2>
        <Child handleClick={this._handleChildClick} />
      </div>
    );
  }
}

class Child extends React.Component {

  _generateAction() {
    // This is action creator mock
    return {type: "SOME_ACTION", payload: "someting"};
  }

  render() {
    return (<button onClick={() => this.props.handleClick(this._generateAction())}>Click me</button>);
  }
}

ReactDOM.render(<Parent />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>


问:
How to make sure only a single checkbox remains checked out of many?
I have some HTML with checkboxes (using radio buttons is not convenient due to the library that generates the HTML - to add detail, I'd need to either hack one myself outside of the library or find an unconventional way to make the library work for me).

I need to simulate radio button functionality, in particular - when checking a single box out of many, all other boxes should be unchecked.

I am trying to uncheck all boxes, and then check the one that I clicked.  My jQuery/JS is failing.  Can you help?

$(function() {
  //check first box
  $("input.duty:first").attr("checked", "true");

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").attr("checked", "false");
    $(this).prop("checked", true);
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="casePointsFieldset">
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">

    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
</div></code>```

答:
Use .prop in all cases rather than mix .prop/.attr.

use true and false rather than strings.

Updated snippet:

$(function() {
  //check first box
  $("input.duty:first").prop("checked", true);

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").prop("checked", false);
    $(this).prop("checked", true);
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="casePointsFieldset">
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">

    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
</div></code>```

Body:
I have some HTML with checkboxes (using radio buttons is not convenient due to the library that generates the HTML - to add detail, I'd need to either hack one myself outside of the library or find an unconventional way to make the library work for me).

I need to simulate radio button functionality, in particular - when checking a single box out of many, all other boxes should be unchecked.

I am trying to uncheck all boxes, and then check the one that I clicked.  My jQuery/JS is failing.  Can you help?

$(function() {
  //check first box
  $("input.duty:first").attr("checked", "true");

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").attr("checked", "false");
    $(this).prop("checked", true);
  });
})

  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0">

  </fieldset>
  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0">

  </fieldset>
  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0">

  </fieldset>

Body:
Use .prop in all cases rather than mix .prop/.attr.

use true and false rather than strings.

Updated snippet:

$(function() {
  //check first box
  $("input.duty:first").prop("checked", true);

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").prop("checked", false);
    $(this).prop("checked", true);
  });
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="casePointsFieldset">
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">

    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
</div>


问:
std::byte on odd platforms
Reading Herb Sutter's blog post about the most recent C++ standard meeting, it noticed that std::byte was added to C++17.  As an initial reading, I have some concerns since it uses unsigned char so that it can avoid complications with strict aliasing rules.

My biggest concern is, how does it work on platforms where CHAR_BIT is not 8?  I have worked on/with platforms where CHAR_BIT is 16 or 32 (generally DSPs).  Given that std::byte is for dealing with "byte-oriented access to memory", and most people understand byte to indicate an octet (not the size of the underlying character type), how will this work for individuals who expect that this will address contiguous 8-bit chunks of memory?

I already see people who just assume that CHAR_BIT is 8 (not evening knowing that CHAR_BIT exists...).  A type called std::byte is likely to introduce even more confusion to individuals.

I guess that what I expected was that they were introducing a type to permit consistent addressing/access to sequential octets for all cases.  There are many octet-oriented protocols where it would be useful to have a library or type that is guaranteed to access memory one octet at a time on all platforms, no matter what CHAR_BIT is equal to on the given platform.

I can definitely understand wanting to have it well specified that something is being used as a sequence of bytes rather than a sequence of characters, but it doesn't seem like being as useful as many other things might be.

答:
Given that std::byte is for dealing with "byte-oriented access to memory", and most people understand byte to indicate an octet (not the size of the underlying character type), how will this work for individuals who expect that this will address contiguous 8-bit chunks of memory?

You can't understand something wrong and then expect the world to rearrange itself to fit your expectations.

The reason why most people think a byte and an octet are the same thing is because in most cases it is true. The vast majority of your typical computer has CHAR_BIT == 8. That doesn't mean it is true all the time.

A byte is not an octet.

char, signed char and unsigned char have a size of one byte.

The good side though is that, people who don't know that, are actually people who don't need to know. If you're working on a machine where a byte is made of more than an octet you are the kind of developer who needs to know that more than any other one.

If we're talking theory here, then the answer is simple: just learn that a byte is different than an octet. If we're talking concrete stuff, then the answer is that you either know the difference already or you won't need to know it (hopefully :)). The worst case is you learning this painfully, but that's the third minority group of developers working on exotic platforms without exotic knowledge.

If you want an equivalent for octets, it already exists:

int8_t

uint8_t

Note that they are "provided only if the implementation directly supports the type".

Title: std::byte on odd platforms


问:
Tablesorter changes row position when editing row item, even if disabled
I've got a weird bug going on in my App and hope someone might know a solution.

My Problem: I've a movie table with different rows, I use the jquery tablesorter plugin from Mottie to sort my items and filter them. Each row also has it's own Edit button, where when you click on it the the td's get editable, now the problem is that when I edit lets say the movie title, then click on the movie director to change his name, the whole row jumps down and it does that all the time until the row is at the bottom. When I remove the tablesorter function everything works correctly, but when it's active, it does this weird bug. Now I tried to just disable the tablesorter on click (following this solution), but that also didn't help me. The sorting and the filter got disabled, but it still pushed my whole row down. Here's a gif to visualize the problem:

Note: The movie title, date, director and runtime are all
 and < input > tags, on click on the edit button the
 tags get hidden and the < input >'s get visible. I used this method because I need to give my new data to my django model somehow, maybe thats part of the problem.

Also I have a hidden row, that shows up when I click on the Description, don't know if thats important as well.

I'd like to provide a jsfiddle, but I didn't manage to reproduce this bug in jsfiddle, it only appears in my app :/

Here's the important code of the app:

HTML

```<code><table id="movieTable" class="table-hover tablesorter">
<thead class="table-head">
          <tr>
               <th data-sorter="false"></th>
               <th>TITLE</th>
               <th class="gen">GENRE</th>
               <th>RELEASE DATE</th>
               <th>DIRECTOR</th>
               <th>DESCRIPTION</th>
               <th>RUNTIME</th>
               <th>STATUS</th>
               <th>IMDB</th>
               <th data-sorter="false" id="buttons-head-bottom"></th>
          </tr>
</thead>
<tbody>
<td>
    <a href=“/myapp/evil-dead/">
        <input class="input-title hide" value="Evil Dead" form="movie1" name="title"/> <!— hidden on default —>
        <p class="movie-title">Evil Dead</p>
    </a>
</td>
<td>
    <select class="hide input-genre-select" form="movie1" name="genre"> <!— hidden on default —>
    <!— options code —>
    </select>
    <p class="movie-genre">Horror</p>
</td>
<td>
    <input class="hide input-release" value="25.04.2013" form="movie1" name="date" size="10"/> <!— hidden on default —>
    <p class="movie-release">25.04.2013</p>
</td>
<td>
    <input class="hide input-director" value="Fede Alvarez" form="movie1" name="director"/> <!— hidden on default —>
    <p class="movie-director">Fede Alvarez</p>
</td>
<td class="desc-pointer toggle" data-toggle="collapse" data-target=".description1"> <!— collapse and shows a hidden table row when clicked —>
    Description <i class="fa fa-caret-right"></i>
</td>
<td>
    <input class="hide input-runtime" value="91" form="movie1" name="runtime" maxlength="4" size="4"/> <!— hidden on default —>
    <p class="movie-runtime">91 min</p>
</td>
<td>
    <select class="hide input-status-select" form="movie1" name="status"> <!— hidden on default —>
    <!— options code —>
    </select>
    <p class="movie-status">Bought and watched</p>
</td>
<td>6,5</td>
<td>
    <!— edit button, is hidden when clicked on it —>
    <button type="button" class="edit-btn">
        <i class="fa fa-pencil-square"></i>
    </button>
    <!— hidden on default, shows up when clicked on edit-btn —>
    <button type="submit" form="movie1" class="save-btn">
        <i class="save-btn fa fa-save"></i>
    </button>
    <!-- delete button -->
    <button id="del-btn1" type="button" class="delete-btn btn btn-default" data-toggle="modal" data-target="#deleteModal1">
        <i class="fa fa-remove"></i>
    </button>
</td>
</tbody>
</table>
</code>```

I only provided one table row here, but every other row is build the same.

Javascript

```<code>// table sorter

$(function(){
    const $table = $("#movieTable").tablesorter({
        dateFormat: "ddmmyyyy",
        headers: {
            2: { sorter: "select" },
            3: { sorter: "shortDate" },
            7: { sorter: "select" },
        },
        widgets: ["filter"],
        widgetOptions : {
            filter_columnFilters: false,
        }
    });

    $.tablesorter.filter.bindSearch( $table, $('.search') );

});

 // edit button

$(".edit-btn").click(function() {

    $('table')
    .unbind('appendCache applyWidgetId applyWidgets sorton update updateCell')
    .removeClass('tablesorter')
    .find('thead th')
    .unbind('click mousedown')
    .removeClass('header headerSortDown headerSortUp');

    const parent = $(this).parent().parent()
    parent.find(".input-director, .input-runtime, .input-release, .input-title").addClass("highlight");
    parent.find(".movie-title, .movie-genre, .movie-release, .movie-director, .movie-runtime, .movie-status").addClass("hide");
    parent.find(".input-title, .input-genre-select, .input-release, .input-director, .input-runtime, .input-status-select").removeClass("hide");
    parent.find(".edit-btn").hide();
    parent.find(".save-btn").show();

    $(".gen").addClass("genre-padding");
    $(".title-link").bind("click", function(e) {
        e.preventDefault();
    })
})
</code>```

If needed I can provide more code, but I hope this is enough for someone to find a solution to this bug. Like I said before, the only solution I had found was to remove the tablesorter plugin, disabling it didn't help.

Thanks to anyone who is trying!

答:
It's not a bug, it's a feature! :D

Internally the plugin is set up to automatically resort when an update is triggered; although, I don't see it being used in the code that was shared. To get around this "feature", set the resort option to false.

Body:
I've got a weird bug going on in my App and hope someone might know a solution.

My Problem: I've a movie table with different rows, I use the jquery tablesorter plugin from Mottie to sort my items and filter them. Each row also has it's own Edit button, where when you click on it the the td's get editable, now the problem is that when I edit lets say the movie title, then click on the movie director to change his name, the whole row jumps down and it does that all the time until the row is at the bottom. When I remove the tablesorter function everything works correctly, but when it's active, it does this weird bug. Now I tried to just disable the tablesorter on click (following this solution), but that also didn't help me. The sorting and the filter got disabled, but it still pushed my whole row down. Here's a gif to visualize the problem:

Note: The movie title, date, director and runtime are all
 and < input > tags, on click on the edit button the
 tags get hidden and the < input >'s get visible. I used this method because I need to give my new data to my django model somehow, maybe thats part of the problem.

Also I have a hidden row, that shows up when I click on the Description, don't know if thats important as well.

I'd like to provide a jsfiddle, but I didn't manage to reproduce this bug in jsfiddle, it only appears in my app :/

Here's the important code of the app:

HTML

               TITLE
               GENRE
               RELEASE DATE
               DIRECTOR
               DESCRIPTION
               RUNTIME
               STATUS
               IMDB

        <input class="input-title hide" value="Evil Dead" form="movie1" name="title"/> <!— hidden on default —>

Evil Dead

    <select class="hide input-genre-select" form="movie1" name="genre"> <!— hidden on default —>
    <!— options code —>
    </select>

Horror

    <input class="hide input-release" value="25.04.2013" form="movie1" name="date" size="10"/> <!— hidden on default —>

25.04.2013

    <input class="hide input-director" value="Fede Alvarez" form="movie1" name="director"/> <!— hidden on default —>

Fede Alvarez

 <!— collapse and shows a hidden table row when clicked —>
    Description

    <input class="hide input-runtime" value="91" form="movie1" name="runtime" maxlength="4" size="4"/> <!— hidden on default —>

91 min

    <select class="hide input-status-select" form="movie1" name="status"> <!— hidden on default —>
    <!— options code —>
    </select>

Bought and watched

6,5

    <!— edit button, is hidden when clicked on it —>
    <button type="button" class="edit-btn">

    </button>
    <!— hidden on default, shows up when clicked on edit-btn —>
    <button type="submit" form="movie1" class="save-btn">

    </button>

    <button id="del-btn1" type="button" class="delete-btn btn btn-default" data-toggle="modal" data-target="#deleteModal1">

    </button>

I only provided one table row here, but every other row is build the same.

Javascript

// table sorter

$(function(){
    const $table = $("#movieTable").tablesorter({
        dateFormat: "ddmmyyyy",
        headers: {
            2: { sorter: "select" },
            3: { sorter: "shortDate" },
            7: { sorter: "select" },
        },
        widgets: ["filter"],
        widgetOptions : {
            filter_columnFilters: false,
        }
    });

    $.tablesorter.filter.bindSearch( $table, $('.search') );

});

 // edit button

$(".edit-btn").click(function() {

    $('table')
    .unbind('appendCache applyWidgetId applyWidgets sorton update updateCell')
    .removeClass('tablesorter')
    .find('thead th')
    .unbind('click mousedown')
    .removeClass('header headerSortDown headerSortUp');

    const parent = $(this).parent().parent()
    parent.find(".input-director, .input-runtime, .input-release, .input-title").addClass("highlight");
    parent.find(".movie-title, .movie-genre, .movie-release, .movie-director, .movie-runtime, .movie-status").addClass("hide");
    parent.find(".input-title, .input-genre-select, .input-release, .input-director, .input-runtime, .input-status-select").removeClass("hide");
    parent.find(".edit-btn").hide();
    parent.find(".save-btn").show();

    $(".gen").addClass("genre-padding");
    $(".title-link").bind("click", function(e) {
        e.preventDefault();
    })
})

If needed I can provide more code, but I hope this is enough for someone to find a solution to this bug. Like I said before, the only solution I had found was to remove the tablesorter plugin, disabling it didn't help.

Thanks to anyone who is trying!


问:
prevent creation new line in xslt transformation
My sorce xml file

```<code><numbers>
    <number>
        one
    </number>
    <number>
        two
    </number>
 <numbers>
</code>```

and I have xsl file that translate into html. I want to construct text like this:

```<code>one, two
</code>```

in output.

For this purpose I use

```<code><xsl:value-of select="//numbers/number" separator=", "/>
</code>```

but in output I'll see text with new line

```<code>one
,
two
</code>```

In browser it's look like 'one , two' (with spaces around comma sign). I want to get value without left space.

I use saxon he 9.4.

答:
Your number elements have white-space in them, including new-lines before and after the actual "one" text, and this is what is getting picked up.

As you are using XSLT2.0, change your expression to this to remove the white-space either side of the text

```<code><xsl:value-of select="//numbers/number/normalize-space()" separator=", "/>
</code>```

Body:
My sorce xml file

<numbers>
    <number>
        one
    </number>
    <number>
        two
    </number>
 <numbers>

and I have xsl file that translate into html. I want to construct text like this:

one, two

in output.

For this purpose I use

<xsl:value-of select="//numbers/number" separator=", "/>

but in output I'll see text with new line

one
,
two

In browser it's look like 'one , two' (with spaces around comma sign). I want to get value without left space.

I use saxon he 9.4.

Body:
Your number elements have white-space in them, including new-lines before and after the actual "one" text, and this is what is getting picked up.

As you are using XSLT2.0, change your expression to this to remove the white-space either side of the text

<xsl:value-of select="//numbers/number/normalize-space()" separator=", "/>


问:
Relative vs. Absolute imports for Flask and nose
I have a Flask app that has the following directory structure:

```<code>    ├── README.md
    ├── __init__.py
    ├── constants.py
    ├── businesspackage
    │   ├── README.md
    │   ├── __init__.py
    │   ├── __pycache__
    │   ├── detection
    │   ├── flagging_spec.txt
    │   └── tests
    ├── requirements.txt
    ├── run.py
    └── tests
        ├── __init__.py
        ├── __pycache__
        └── test_api.py
</code>```

Within detection's __init__.py, I have imported my necessary classes, so that I can import the classes from that top-level module, rather than needing to give the full path to each of the .py files inside of the module.

I am attempting to import some classes from detection from inside run.py, but am coming across the following error: when I try to run my Flask application from the top-level directory using python3 run.py:

```<code>    Traceback (most recent call last):
    File "run.py", line 9, in <module>
        from .businesspackage.detection import AdsDetection
    SystemError: Parent module '' not loaded, cannot perform relative import
</code>```

After reading some other questions on here, it suggested that I change from a relative import to an absolute import. However, if I try the following import in run.py:

```<code>    from businesspackage.detection import AdsDetection
</code>```

Then I can run my Flask server without the import error, however, my imports break for the nose test runner. I am running the tests using the nosetests command, with nose 1.3.7 . How can I define my imports so that they work for both the Flask server, and for my nosetests?

Edit:

businesspackage.__init__.py is the following:

```<code>    from .business_detection import BusinessDetector
</code>```

答:
So for some weird reason, I managed to get the absolute imports to work after deleting the __init__.py file in the base level directory: i.e. my directory structure looks like follows:

```<code>├── README.md
├── __init__.py
├── constants.py
├── businesspackage
│   ├── README.md
│   ├── __init__.py
│   ├── __pycache__
│   ├── detection
│   ├── flagging_spec.txt
│   └── tests
├── requirements.txt
├── run.py
└── tests
    ├── __init__.py
    ├── __pycache__
    └── test_api.py
</code>```

I figured I should give it a try after seeing one of the answers on here: Python imports for tests using nose - what is best practice for imports of modules above current package . So now, all of my package is using absolute imports.

Body:
I have a Flask app that has the following directory structure:

    ├── README.md
    ├── __init__.py
    ├── constants.py
    ├── businesspackage
    │   ├── README.md
    │   ├── __init__.py
    │   ├── __pycache__
    │   ├── detection
    │   ├── flagging_spec.txt
    │   └── tests
    ├── requirements.txt
    ├── run.py
    └── tests
        ├── __init__.py
        ├── __pycache__
        └── test_api.py

Within detection's __init__.py, I have imported my necessary classes, so that I can import the classes from that top-level module, rather than needing to give the full path to each of the .py files inside of the module.

I am attempting to import some classes from detection from inside run.py, but am coming across the following error: when I try to run my Flask application from the top-level directory using python3 run.py:

    Traceback (most recent call last):
    File "run.py", line 9, in <module>
        from .businesspackage.detection import AdsDetection
    SystemError: Parent module '' not loaded, cannot perform relative import

After reading some other questions on here, it suggested that I change from a relative import to an absolute import. However, if I try the following import in run.py:

    from businesspackage.detection import AdsDetection

Then I can run my Flask server without the import error, however, my imports break for the nose test runner. I am running the tests using the nosetests command, with nose 1.3.7 . How can I define my imports so that they work for both the Flask server, and for my nosetests?

Edit:

businesspackage.__init__.py is the following:

    from .business_detection import BusinessDetector

Body:
So for some weird reason, I managed to get the absolute imports to work after deleting the __init__.py file in the base level directory: i.e. my directory structure looks like follows:

├── README.md
├── __init__.py
├── constants.py
├── businesspackage
│   ├── README.md
│   ├── __init__.py
│   ├── __pycache__
│   ├── detection
│   ├── flagging_spec.txt
│   └── tests
├── requirements.txt
├── run.py
└── tests
    ├── __init__.py
    ├── __pycache__
    └── test_api.py

I figured I should give it a try after seeing one of the answers on here: Python imports for tests using nose - what is best practice for imports of modules above current package . So now, all of my package is using absolute imports.


问:
Firebase CLI deploy functions - Error: Failed to initialize a region
I'm having trouble doing firebase deploy --only functions for an app on Blaze plan.
I have the latest firebase-tools CLI  (v 3.5.0).

I get the following error:

```<code>=== Deploying to 'myapp1234'...

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
i  runtimeconfig: ensuring necessary APIs are enabled...
✔  runtimeconfig: all necessary APIs are enabled
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (1.29 KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function myFunc...
⚠  functions[myFunc]: Deploy Error: Failed to initialize a region

Functions deploy had errors. To continue deploying other features (such as database), run:
    firebase deploy --except functions

Error: Functions did not deploy properly.
</code>```

I've retried this every half hour for the past 12 hours, thinking there's an outage. The firebase status page shows all green.

答:
Ok, here's what I found, a little weird:

firebase list shows all the firebase projects you have access to, BUT they are not already available (i.e. added as alias to your current folder project).

Even if the firebase-tools CLI allows you to do firebase deploy --project myproject1, if you do not have myproject1 declared in .firebaserc => it will fail with the weird region error above.

To fix this, I found that there are 2 options:

firebase use --add (will trigger an interactive list)

firebase use myproject1

=> and then firebase deploy --project myproject1 will work  (with or without the optional --only functions)

Body:
I'm having trouble doing firebase deploy --only functions for an app on Blaze plan.
I have the latest firebase-tools CLI  (v 3.5.0).

I get the following error:

=== Deploying to 'myapp1234'...

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
i  runtimeconfig: ensuring necessary APIs are enabled...
✔  runtimeconfig: all necessary APIs are enabled
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...
i  functions: packaged functions (1.29 KB) for uploading
✔  functions: functions folder uploaded successfully
i  starting release process (may take several minutes)...
i  functions: updating function myFunc...
⚠  functions[myFunc]: Deploy Error: Failed to initialize a region

Functions deploy had errors. To continue deploying other features (such as database), run:
    firebase deploy --except functions

Error: Functions did not deploy properly.

I've retried this every half hour for the past 12 hours, thinking there's an outage. The firebase status page shows all green.


问:
How to append value to an array keeping old value intact in Javascript?
Google visualization API requires arrays like this:

```<code>var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);
</code>```

I have separately array of columns

```<code>var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
</code>```

for values

```<code>var values = [8.94, 10.49, 19.30, 21.45];
</code>```

and for colors

```<code>var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];
</code>```

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.

答:
Sounds like you just need to immutably copy the array and then do whatever you want with it. Try this:</p>

```<code>// ES6
var myArr = [1, 2, 3]
var newArr = [ ...myArr ]

// ES5
var myArr = [1, 2, 3];
var newArr = [].concat(myArr);
</code>```

Body:
Google visualization API requires arrays like this:

var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);

I have separately array of columns

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];

for values

var values = [8.94, 10.49, 19.30, 21.45];

and for colors

var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.

Body:
Sounds like you just need to immutably copy the array and then do whatever you want with it. Try this:

// ES6
var myArr = [1, 2, 3]
var newArr = [ ...myArr ]

// ES5
var myArr = [1, 2, 3];
var newArr = [].concat(myArr);


问:
How do you use Parsley framework in Flex Hero 4.5
I was wondering if Parsley framework is compatible for Flex Hero Mobile 4.5? I seem to get a warning saying it's not compatible.
Thanks guys</p>

答:
Are you using the code?  OR a SWC you downloaded from a web site?  I assume the latter.

Download the code and recompile it against the Flex 4.5 SDK.  There are often issues when using a SWC that is compiled against a different version of the SDK than your main application.

ContentLicense: CC BY-SA 2.5


问:
Ruby - extending method with super using splat
In "Comprehensive Ruby programming course" e-book I have a case when the child class method extends parents method. I am not completely aware how it works:

```<code>class Parent
  def initialize(foo:, bar:)
   @foo = foo
   @bar = bar
  end
end

class Child < Parent
  def initialize(buzz:,**args)
   super(**args)
   @buzz = buzz
  end
end
</code>```

I cant completely understand why we use splat here - **args.
In here def initialize(buzz:,**args) we are just telling initialize to take unknown number of key-value arguments, right? But what exactly this means super(**args). To tell method to take those key-value arguments from the superclass method? Why not just like this:

```<code>class Child < Parent
  def initialize(buzz:)
   super
   @buzz = buzz
  end
end
</code>```

After all, super tells to extend method with whatever there is in the parent, so why these splat args needed?

答:
**args in the parameter list simply means "get all extra keyword arguments and put them in a hash, called args".

Conversely, **args when calling a method does the opposite - "get this hash called args and pass keyword arguments with the corresponding names and values from that hash".

super without arguments will try to pass all arguments that the child method received. Hence if you have extra that the parent didn't expect, you will get an ArgumentError.

In your example, the parent expects only foo: and bar:, while the child also has buzz:.

Body:
In "Comprehensive Ruby programming course" e-book I have a case when the child class method extends parents method. I am not completely aware how it works:

class Parent
  def initialize(foo:, bar:)
   @foo = foo
   @bar = bar
  end
end

class Child < Parent
  def initialize(buzz:,**args)
   super(**args)
   @buzz = buzz
  end
end

I cant completely understand why we use splat here - **args.
In here def initialize(buzz:,**args) we are just telling initialize to take unknown number of key-value arguments, right? But what exactly this means super(**args). To tell method to take those key-value arguments from the superclass method? Why not just like this:

class Child < Parent
  def initialize(buzz:)
   super
   @buzz = buzz
  end
end

After all, super tells to extend method with whatever there is in the parent, so why these splat args needed?


答:
If you only ever want one checkbox, you should consider radio buttons.

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/radio

This should fit the use case better. Let me know if you need any help with implementation.

I know you say radios are hard because of your use case, but you should seriously consider extending your library with functionality for radio buttons.  It is more correct from HTML standpoint as well as form a UI/UX standpoint.

Title: How to make sure only a single checkbox remains checked out of many?


问:
Assist with simple count out of a list
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

```<code>public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}
</code>```

答:
first move </p>

```<code>NewAgent newAgents = new ScoreBoardClientTest.NewAgent();
</code>```

<p>into the first loop so the newAgents will be new when you add it
second , the second foreach is on a string so it gives you list of chars </p>

Title: Assist with simple count out of a list

Body:
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}

Body:
first move

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

into the first loop so the newAgents will be new when you add it
second , the second foreach is on a string so it gives you list of chars


问:
Lottie Animation setAnimation() results IllegalStateException
I want to check Lottie lib for both iOS and Android today, I made a simple indicator animation in after effect and export it to .json file and it just works on iOS. When I test the same file on Android I got the following error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.lottietest/com.test.lottietest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setAnimation(java.lang.String)' on a null object reference
</code>```

here is my activity XML

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mtids.lottietest.MainActivity">

    <view
        class="com.airbnb.lottie.LottieAnimationView"
        id="@+id/animationView"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="133dp"
        android:layout_marginTop="20dp"
        android:onClick="animate"
        android:text="animate" />

</RelativeLayout>
</code>```

Activity code

```<code>public class MainActivity extends AppCompatActivity {
    LottieAnimationView anim;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        anim = (LottieAnimationView) findViewById(R.id.animationView);
        anim.setAnimation("indicator.json");
    }

    public void animate(View view) {
        anim.loop(true);
        anim.playAnimation();
    }
}
</code>```

答:
i'v changed the id property to android : id="@+id/animationView" instead of id="@+id/animationView" only , and the error message become java.lang.IllegalStateException: Unable to find file indicator.json

As you correctly noticed, first you should change id to android:id.

Secondly, from the sources of setAnimation(String):

Sets the animation from a file in the assets directory.

Obviously, you have no file named "indicator.json" in assets directory.

ContentLicense: CC BY-SA 4.0

Body:
I want to check Lottie lib for both iOS and Android today, I made a simple indicator animation in after effect and export it to .json file and it just works on iOS. When I test the same file on Android I got the following error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.lottietest/com.test.lottietest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.airbnb.lottie.LottieAnimationView.setAnimation(java.lang.String)' on a null object reference

here is my activity XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mtids.lottietest.MainActivity">

    <view
        class="com.airbnb.lottie.LottieAnimationView"
        id="@+id/animationView"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="133dp"
        android:layout_marginTop="20dp"
        android:onClick="animate"
        android:text="animate" />

</RelativeLayout>

Activity code

public class MainActivity extends AppCompatActivity {
    LottieAnimationView anim;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        anim = (LottieAnimationView) findViewById(R.id.animationView);
        anim.setAnimation("indicator.json");
    }

    public void animate(View view) {
        anim.loop(true);
        anim.playAnimation();
    }
}


问:
Adding a Jenkinsfile for compilation by Gradle
I have a Gradle build with the source sets configured like so:

```<code>sourceSets {
    main {
        groovy {
            srcDir 'src'
        }
    }
}
</code>```

I have a Jenkinsfile in the root project directory that I would like to have compiled so that I can detect non-valid Groovy before it gets merged to the master branch and breaks the Jenkins build.

How can I add this single file to the source sets of the Gradle project for compilation? How can I ensure that Gradle compiles it even though it's not got a .groovy extension?

答:
You can add additional sourceSet like this:

sourceSets {
    jenkins {
        groovy {
            srcDir "$projectDir"
            include "JenkinsFile"
        }
    }
    main {
        groovy {
            srcDir 'src'
        }
    }
}
```

<p>However, the problem is that you will not be able to compile a text file as Groovy. What you can do, however, is set up a task to create, compile, and delete a new <code>.groovy</code> file containing the contents of the Jenkins file before the groovy compilation. The final build file doing these things would look like this:</p>

<pre class="lang-groovy prettyprint-override"><code>apply plugin: 'groovy'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    jenkins {
        groovy {
            srcDir "$projectDir"
            include "JenkinsFile.groovy"
        }
    }
    main {
        groovy {
            srcDir 'src'
        }
    }
}

task(createGroovyFile) {
    File jenkinsFile = new File("$projectDir/JenkinsFile")
    File groovyFile = new File("$projectDir/JenkinsFile.groovy")
    if(groovyFile.exists()) groovyFile.delete()
    groovyFile.newDataOutputStream() << jenkinsFile.readBytes()
}

task(deleteGroovyFile, type: Delete) {
    File groovyFile = new File("$projectDir/JenkinsFile.groovy")
    delete(groovyFile)
}

compileGroovy.dependsOn deleteGroovyFile
deleteGroovyFile.dependsOn compileJenkinsGroovy
compileJenkinsGroovy.dependsOn createGroovyFile

configurations {
    jenkinsCompile.extendsFrom compile
}

dependencies {
    compile   "org.codehaus.groovy:groovy-all:2.4.10"
}
</code>```

Body:
I have a Gradle build with the source sets configured like so:

sourceSets {
    main {
        groovy {
            srcDir 'src'
        }
    }
}

I have a Jenkinsfile in the root project directory that I would like to have compiled so that I can detect non-valid Groovy before it gets merged to the master branch and breaks the Jenkins build.

How can I add this single file to the source sets of the Gradle project for compilation? How can I ensure that Gradle compiles it even though it's not got a .groovy extension?

Body:
You can add additional sourceSet like this:

sourceSets {
    jenkins {
        groovy {
            srcDir "$projectDir"
            include "JenkinsFile"
        }
    }
    main {
        groovy {
            srcDir 'src'
        }
    }
}

However, the problem is that you will not be able to compile a text file as Groovy. What you can do, however, is set up a task to create, compile, and delete a new .groovy file containing the contents of the Jenkins file before the groovy compilation. The final build file doing these things would look like this:

apply plugin: 'groovy'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

sourceSets {
    jenkins {
        groovy {
            srcDir "$projectDir"
            include "JenkinsFile.groovy"
        }
    }
    main {
        groovy {
            srcDir 'src'
        }
    }
}

task(createGroovyFile) {
    File jenkinsFile = new File("$projectDir/JenkinsFile")
    File groovyFile = new File("$projectDir/JenkinsFile.groovy")
    if(groovyFile.exists()) groovyFile.delete()
    groovyFile.newDataOutputStream() << jenkinsFile.readBytes()
}

task(deleteGroovyFile, type: Delete) {
    File groovyFile = new File("$projectDir/JenkinsFile.groovy")
    delete(groovyFile)
}

compileGroovy.dependsOn deleteGroovyFile
deleteGroovyFile.dependsOn compileJenkinsGroovy
compileJenkinsGroovy.dependsOn createGroovyFile

configurations {
    jenkinsCompile.extendsFrom compile
}

dependencies {
    compile   "org.codehaus.groovy:groovy-all:2.4.10"
}


问:
How can I speed up deep learning on a non-NVIDIA setup?
Since I only have an AMD A10-7850 APU, and do not have the funds to spend on a $800-$1200 NVIDIA graphics card, I am trying to make due with the resources I have in order to speed up deep learning via tensorflow/keras.

Initially, I used a pre-compiled version of Tensorflow. InceptionV3 would take about 1000-1200 seconds to compute 1 epoch. It has been painfully slow.

To speed up calculations, I first self-compiled Tensorflow with optimizers (using AVX, and SSE4 instructions). This lead to a roughly 40% decrease in computation times. The same computations performed above now only take about 600 seconds to compute. It's almost bearable - kind of like you can watch paint dry.

I am looking for ways to further decrease computation times. I only have an integrated AMD graphics card that is part of the APU. (How) (C/c)an I make use of this resource to speed up computation even more?

More generally, let's say there are other people with similar monetary restrictions and Intel setups. How can anyone WITHOUT discrete NVIDIA cards make use of their integrated graphics chips or otherwise non-NVIDIA setup to achieve faster than CPU-only performance? Is that possible? Why/Why not? What needs to be done to achieve this goal? Or will this be possible in the near future (2-6 months)? How?

答: If your platform supports opencl you can look at using it with tensorflow. There is some experimental support for it on Linux at this github repository. Some preliminary instructions are at the documentation section of of this github repository. </p>


问:
Validation Group on "NotBlank" constraint makes field have "required" attribute when not used
I have an entity field as follows:

```<code>/**
 * @ORM\Column(nullable=true)
 * @Assert\NotBlank(groups={"myGroup"})
 */
protected $field;
</code>```

Then I call an entity form without any validation groups (my configureOptions function only sets data_class). But the field is being created with the required="required" attribute in the HTML:

```<code><input id="entity_field" name="entity[field]" required="required" type="text">
</code>```

But if I fiddle with the HTML and take out the required="required", the validation works as intended in the backend (i.e., NotBlank doesn't apply for this form).

答:
The annotation @Assert\NotBlank(groups={"myGroup"}) is server side related, the input attribute required="required" is defined in the construction of your form.
If this field is not required you should defined required option to false in your form, take a look at the documentation here and here

The required Option

The most common option is the required option, which can be applied to any field. By default, the required option is set to true, meaning that HTML5-ready browsers will apply client-side validation if the field is left blank. If you don't want this behavior, either disable HTML5 validation or set the required option on your field to false:

Also note that setting the required option to true will not result in server-side validation to be applied. In other words, if a user submits a blank value for the field (either with an old browser or web service, for example), it will be accepted as a valid value unless you use Symfony's NotBlank or NotNull validation constraint.

In other words, the required option is "nice", but true server-side validation should always be used.

Body:
I have an entity field as follows:

/**
 * @ORM\Column(nullable=true)
 * @Assert\NotBlank(groups={"myGroup"})
 */
protected $field;

Then I call an entity form without any validation groups (my configureOptions function only sets data_class). But the field is being created with the required="required" attribute in the HTML:

<input id="entity_field" name="entity[field]" required="required" type="text">

But if I fiddle with the HTML and take out the required="required", the validation works as intended in the backend (i.e., NotBlank doesn't apply for this form).


问:
adding variables numical values (newb question)
Yesterday i had a look at how to set values of variables from nummbers stored in external txt files

the variables then needed to be added up so i used trial and  error first

((XVAL) + (NEWVAL))

assuming that XVAL was set to 10 and NEWVAL was set to 20 i expected to get the answer of thirty but waqs presented with the new value of 10 20

VB.net pysicaly added the two values together but i wanted the mathematical product of the two which is ((10) + (20)) = 30

yep its a newb question could anyone explain how to achieve what im affter

答:
Have you tried the Val() function?</p>

```<code>Val(XVAL) + Val(NEWVAL)
</code>```

Body:
Have you tried the Val() function?

Val(XVAL) + Val(NEWVAL)


问:
Purpose of "client_x509_cert_url" field in JSON file generated by Google Oauth 2.0 Provider
When we create a new "Client ID" on Google developers console and select the Application Type as "Web", we get the option to download a JSON file that includes a lot of key-value pairs. This JSON file is for the consumption of the Open-ID web client during the setup phase.

One of the key value pairs I see is "client_x509_cert_url:
https://www.googleapis.com/robo/v1/metadata/x509/......".

When I copy paste the above URL in a browser I see an empty JSON response {}.  I suppose the intent here is to let an OPEN-ID connect client to populate the public cert of a public-private RSA key pair for signing and encrypting JWT request objects.  But I do not see any documentation on how to upload a client certificate in the Google developers console.

Is this because Google does not support JWT request objects yet?

答:
client_x509_cert_url is the URL of the public x509 certificate, used to verify JWTs signed by the client.

i think for a web application, it use the oauth2.0 authorization code flow, which does not need to sign the JWT, actually it does not use the JWT at all.

But if you create a service account, https://developers.google.com/identity/protocols/OAuth2ServiceAccount

and the downloaded json file will include a client_x509_cert_url, which that url does work and will display the public key of the certificate.

Than's because the service account uses the oauth 2.0 JWT Bearer Token flow, which client has to use private key to sign.


问:
httprequesttask returns JSONArray, not the expected JSONObject
I try to get patient information, by sending an ID to the server. I expect the result to be a JSONObject, as only one patient corresponds with the ID. However, what i get is a JSONArray. I have tried to do getJSONObject(0), but it gives this error:
Index 0 out of range [0..0)

Why i is an Array and not an Object, and how do i deal with it?

This is my java code in the activity:

```<code>new HttpRequestTask(
            "getPatientFull",
            new String[]{"ID"},
            new String[]{PatientID}, new HttpRequestTask.ResultReceiver() {
        @Override
        public void processResult(String apiFunctionName, JSONObject result) {
            if (result != null) {
                try {
                    if (result.has("error")) {
                        shorttoast("ERROR: " + result.getString("error") + "saving patient file");
                    } else {
                        if (result.has("patient_details")) {
                            patientName = result.getJSONArray("patient_details").getJSONObject(0).getString("NAME");
                            shorttoast(patientName);
                    }
                    }
                } catch (JSONException ex) {
                    shorttoast("ERROR" + ex.getLocalizedMessage());
                }
            } else
                shorttoast("Retreiving failed");
        }
    }).execute();
</code>```

The PatientID is defined earlier in the code (it's an existing patient id).

and this is the php API function that was defined by my teacher:

```<code> app.post("/getPatientFull", function (req, res) {
    pool.getConnection(function (err, connection) {
        connection.query('SELECT * FROM PatientDossier WHERE PATIENT_ID=?',
            [req.query.ID],
            function (error, results, fields) {
                if (error) {
                    res.status(403).json({"error": error.code});
                } else {
                    res.status(200).json({patient_details:results});
                }
            });
        connection.release();
    });
});
</code>```

答:
The PHP function does not return a single object, it returns an array.
So, you should expect a JSONArray on the Android side.

As to why getJSONObject(0) is giving you an out-of-bounds error, I'm not sure.
Try using the debugger to look at the JSONArray, and see what's in it. It's possible that you searched for a patient id that's not in the database, and the PHP code returned an empty array. Your code should be checking that anyway.

It also looks like maybe "result" is a JSONObject containing the array, under the key "patient_details", in which case, you need to get the value of "patient_details" and index into that array. If you show us the JSON response, it would be easier to tell.

Body:
I try to get patient information, by sending an ID to the server. I expect the result to be a JSONObject, as only one patient corresponds with the ID. However, what i get is a JSONArray. I have tried to do getJSONObject(0), but it gives this error:
Index 0 out of range [0..0)

Why i is an Array and not an Object, and how do i deal with it?

This is my java code in the activity:

new HttpRequestTask(
            "getPatientFull",
            new String[]{"ID"},
            new String[]{PatientID}, new HttpRequestTask.ResultReceiver() {
        @Override
        public void processResult(String apiFunctionName, JSONObject result) {
            if (result != null) {
                try {
                    if (result.has("error")) {
                        shorttoast("ERROR: " + result.getString("error") + "saving patient file");
                    } else {
                        if (result.has("patient_details")) {
                            patientName = result.getJSONArray("patient_details").getJSONObject(0).getString("NAME");
                            shorttoast(patientName);
                    }
                    }
                } catch (JSONException ex) {
                    shorttoast("ERROR" + ex.getLocalizedMessage());
                }
            } else
                shorttoast("Retreiving failed");
        }
    }).execute();

The PatientID is defined earlier in the code (it's an existing patient id).

and this is the php API function that was defined by my teacher:

 app.post("/getPatientFull", function (req, res) {
    pool.getConnection(function (err, connection) {
        connection.query('SELECT * FROM PatientDossier WHERE PATIENT_ID=?',
            [req.query.ID],
            function (error, results, fields) {
                if (error) {
                    res.status(403).json({"error": error.code});
                } else {
                    res.status(200).json({patient_details:results});
                }
            });
        connection.release();
    });
});


问:
How to make sure only a single checkbox remains checked out of many?
I have some HTML with checkboxes (using radio buttons is not convenient due to the library that generates the HTML - to add detail, I'd need to either hack one myself outside of the library or find an unconventional way to make the library work for me).

I need to simulate radio button functionality, in particular - when checking a single box out of many, all other boxes should be unchecked.

I am trying to uncheck all boxes, and then check the one that I clicked.  My jQuery/JS is failing.  Can you help?

$(function() {
  //check first box
  $("input.duty:first").attr("checked", "true");

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").attr("checked", "false");
    $(this).prop("checked", true);
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="casePointsFieldset">
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">

    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
  <fieldset class="casePointFieldset">
    <div>
      <label><span>Duty:</span>
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0"></label>
    </div>
  </fieldset>
</div></code>```

答:
Try to set the checked-property to the boolean false, not to the string "false".

Using the string will be interpreted as true.

```<code>$("input.duty").attr("checked", false);
</code>```

Body:
I have some HTML with checkboxes (using radio buttons is not convenient due to the library that generates the HTML - to add detail, I'd need to either hack one myself outside of the library or find an unconventional way to make the library work for me).

I need to simulate radio button functionality, in particular - when checking a single box out of many, all other boxes should be unchecked.

I am trying to uncheck all boxes, and then check the one that I clicked.  My jQuery/JS is failing.  Can you help?

$(function() {
  //check first box
  $("input.duty:first").attr("checked", "true");

  //clicking unchecked box should check that box
  //unchecks all others
  $(".duty").on('click', function(event) {
    $("input.duty").attr("checked", "false");
    $(this).prop("checked", true);
  });
})

  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[0][isDutyPoint]" class="duty" value="0">

  </fieldset>
  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[1][isDutyPoint]" class="duty" value="0">

  </fieldset>
  <fieldset class="casePointFieldset">

      Duty:
                        <input type="checkbox" name="casePoints[2][isDutyPoint]" class="duty" value="0">

  </fieldset>

Body:
Try to set the checked-property to the boolean false, not to the string "false".

Using the string will be interpreted as true.

$("input.duty").attr("checked", false);


问:
Not able to make first tab active for angular2 tab component
```<code>I have tabs.component.ts file like

 //Detail class for tab details
class Detail {
    title: string; // Name of the tab
    id: string //Id for the tab
    text: string; // Tab Content
    removable: boolean; // Variable to determine whether to display delete button next to tab
}

//Component to add and delete a tab
@Component({
    selector: 'de-tabs',
    template: require('./tabs.component.html'),
})
export class TabsComponent {
    details: Detail[] = [];
    id: number = 1; //Tab id

    constructor() {
        //Add Tab1 as default tab
        this.details.push({
            title: `Calculation1`,
            id: '1',
            text: `Some detail text for ${this.id}...`,
            removable: false
        });
        //Add tab titled "+" as the last tab
        this.addNewTabOption();
    }

    //Method to add a new tab
    addDetail() {
        //Remove the last tab titled "+"
        this.details.pop();
        //Iterate the id to point to next number
        this.id++;
        //Add the new tab details
        this.details.push({
            title: `Calculation${this.id}`,
            id: `${this.id}`,
            text: `Some detail text for ${this.id}...`,
            removable: true
        });
        //Add tab titled "+" as the last tab
        this.addNewTabOption();
    }

    //Adding tab titled "+" as the last tab
    //Make removable variable as false since we don't want to display delete button for "+" tab
    addNewTabOption() {
        this.details.push({
            title: `+`,
            id: '+',
            text: ``,
            removable: false
        });
    }
} and html like

<!--Calling tab component to add and remove a tab-->
<de-tab>
    <!--Add Extra Channel section-->
    <template *ngFor="let detail of details" de-pane [title]="detail.title" [id]="detail.id">

            </div>
</template>
</de-tab>

My tab component and html are as follows.

//Directive to set the active attribute for the tab
@Directive({
    selector: '[de-pane]'
})
export class UiPane {
    @Input() title: string;
    @Input() id: string;
    @Input() removable: string;
    private _active: boolean = false;

    constructor(public viewContainer: ViewContainerRef,
        public templateRef: TemplateRef<any>) { }

    //Set the active tab and embed the tab pane template in the view container
    //If not active remove it from the view container
    @Input() set active(active: boolean) {
        if (active == this._active) return;
        this._active = active;
        if (active) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.remove(0);
        }
    }

    //Get the active attribute for a tab
    get active(): boolean {
        return this._active;
    }
}

//Component to create and delete a tab
@Component({
    selector: 'de-tab',
    template: require('./tab.component.html'),
    styles: ['a { cursor: pointer; cursor: hand; }']
})

export class TabComponent implements OnInit {
    @ContentChildren(UiPane) panes: QueryList<UiPane>; //Get the list of tab panes

    select(pane: UiPane) {
        if (pane.title == '+') {
            this.panes.toArray().forEach((p: UiPane) => p.active = p == pane);
        } else {
            this.panes.toArray().forEach((p: UiPane) => p.active = p == pane);
        }
    }

}

HTML is

<!--Display the tabs with small delete button for each tab-->
<ul class="nav nav-tabs">
    <li *ngFor="let pane of panes"
        (click)="select(pane)"
        role="presentation" [class.active]="pane.active">
        <a>{{pane.title}}
            <span [hidden]="!pane.removable">
                <span (click)="removeTab(pane);" class="glyphicon glyphicon-remove-circle"></span>
            </span>
        </a>
    </li>
</ul>
<ng-content></ng-content>
</code>```

I want to know how to make the first tab to display the content on page load. I tried using ngAfterContentInit method and pass the first pane to the select method but it did not seem working. Can you please let me know how to make first pane active and load the details of the tab.

答:
I did something similar but not using tabs, I used panels, but the concept might be the same. here is what I did.

Here is my HTML file

```<code><div class="container">
<div class="row">
    <div class="col-md-3">
        <div class="panel">
            <div class="panel-heading bg-gray-lighter text-bold">Settings</div>
            <div class="list-group">
                <a class="list-group-item" (click)="settingActive=1" [ngClass]="{'active': (settingActive == 1)}">Tab Title 1</a>
                <a class="list-group-item" (click)="settingActive=2" [ngClass]="{'active': (settingActive == 2)}">Tab Title 2</a>
                <a class="list-group-item" (click)="settingActive=3" [ngClass]="{'active': (settingActive == 3)}">Tab Title 3</a>
                <a class="list-group-item" (click)="settingActive=4" [ngClass]="{'active': (settingActive == 4)}">Tab Title 4</a>
                <a class="list-group-item" (click)="settingActive=5" [ngClass]="{'active': (settingActive == 5)}">Tab Title 5</a>
            </div>
        </div>
    </div>
    <div class="col-md-9">
        <div *ngIf="settingActive == 1">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold"> Panel Title 1</div>
                <div class="panel-body">

                  <!-- content here -->

                </div>
            </div>
        </div>
        <div *ngIf="settingActive == 2">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold"> Panel Title 2</div>
                <div class="panel-body">

                  <!-- content here -->

                </div>
            </div>
        </div>
        <div *ngIf="settingActive == 3">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold"> Panel Title 3</div>
                <div class="panel-body">

                 <!-- content here -->

                </div>
            </div>
        </div>
        <div *ngIf="settingActive == 4">
          <div class="panel panel-primary">
              <div class="panel-heading text-bold"> Panel Title 4</div>
              <div class="panel-body">

               <!-- content here -->

              </div>
          </div>
        </div>
        <div *ngIf="settingActive == 5">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold">Panel Title 5 </div>
                <div class="panel-body">

                    <!-- content here -->

                </div>
            </div>
        </div>
    </div>
</div>
</code>```

and in my Class I added this so it implements on init. What this does is sets which tab you want to be active first on load.

```<code>export class BusinessInfoComponent implements OnInit {
  settingActive = 1;
}
</code>```

I hope this can help you in some way :)

Body:
I have tabs.component.ts file like

 //Detail class for tab details
class Detail {
    title: string; // Name of the tab
    id: string //Id for the tab
    text: string; // Tab Content
    removable: boolean; // Variable to determine whether to display delete button next to tab
}

//Component to add and delete a tab
@Component({
    selector: 'de-tabs',
    template: require('./tabs.component.html'),
})
export class TabsComponent {
    details: Detail[] = [];
    id: number = 1; //Tab id

    constructor() {
        //Add Tab1 as default tab
        this.details.push({
            title: `Calculation1`,
            id: '1',
            text: `Some detail text for ${this.id}...`,
            removable: false
        });
        //Add tab titled "+" as the last tab
        this.addNewTabOption();
    }

    //Method to add a new tab
    addDetail() {
        //Remove the last tab titled "+"
        this.details.pop();
        //Iterate the id to point to next number
        this.id++;
        //Add the new tab details
        this.details.push({
            title: `Calculation${this.id}`,
            id: `${this.id}`,
            text: `Some detail text for ${this.id}...`,
            removable: true
        });
        //Add tab titled "+" as the last tab
        this.addNewTabOption();
    }

    //Adding tab titled "+" as the last tab
    //Make removable variable as false since we don't want to display delete button for "+" tab
    addNewTabOption() {
        this.details.push({
            title: `+`,
            id: '+',
            text: ``,
            removable: false
        });
    }
} and html like

<de-tab>

    <template *ngFor="let detail of details" de-pane [title]="detail.title" [id]="detail.id">

</template>
</de-tab>

My tab component and html are as follows.

//Directive to set the active attribute for the tab
@Directive({
    selector: '[de-pane]'
})
export class UiPane {
    @Input() title: string;
    @Input() id: string;
    @Input() removable: string;
    private _active: boolean = false;

    constructor(public viewContainer: ViewContainerRef,
        public templateRef: TemplateRef<any>) { }

    //Set the active tab and embed the tab pane template in the view container
    //If not active remove it from the view container
    @Input() set active(active: boolean) {
        if (active == this._active) return;
        this._active = active;
        if (active) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.remove(0);
        }
    }

    //Get the active attribute for a tab
    get active(): boolean {
        return this._active;
    }
}

//Component to create and delete a tab
@Component({
    selector: 'de-tab',
    template: require('./tab.component.html'),
    styles: ['a { cursor: pointer; cursor: hand; }']
})

export class TabComponent implements OnInit {
    @ContentChildren(UiPane) panes: QueryList<UiPane>; //Get the list of tab panes

    select(pane: UiPane) {
        if (pane.title == '+') {
            this.panes.toArray().forEach((p: UiPane) => p.active = p == pane);
        } else {
            this.panes.toArray().forEach((p: UiPane) => p.active = p == pane);
        }
    }

}

HTML is

        {{pane.title}}

<ng-content></ng-content>

I want to know how to make the first tab to display the content on page load. I tried using ngAfterContentInit method and pass the first pane to the select method but it did not seem working. Can you please let me know how to make first pane active and load the details of the tab.

Body:
I did something similar but not using tabs, I used panels, but the concept might be the same. here is what I did.

Here is my HTML file

<div class="container">
<div class="row">
    <div class="col-md-3">
        <div class="panel">
            <div class="panel-heading bg-gray-lighter text-bold">Settings</div>
            <div class="list-group">
                <a class="list-group-item" (click)="settingActive=1" [ngClass]="{'active': (settingActive == 1)}">Tab Title 1</a>
                <a class="list-group-item" (click)="settingActive=2" [ngClass]="{'active': (settingActive == 2)}">Tab Title 2</a>
                <a class="list-group-item" (click)="settingActive=3" [ngClass]="{'active': (settingActive == 3)}">Tab Title 3</a>
                <a class="list-group-item" (click)="settingActive=4" [ngClass]="{'active': (settingActive == 4)}">Tab Title 4</a>
                <a class="list-group-item" (click)="settingActive=5" [ngClass]="{'active': (settingActive == 5)}">Tab Title 5</a>
            </div>
        </div>
    </div>
    <div class="col-md-9">
        <div *ngIf="settingActive == 1">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold"> Panel Title 1</div>
                <div class="panel-body">

                  <!-- content here -->

                </div>
            </div>
        </div>
        <div *ngIf="settingActive == 2">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold"> Panel Title 2</div>
                <div class="panel-body">

                  <!-- content here -->

                </div>
            </div>
        </div>
        <div *ngIf="settingActive == 3">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold"> Panel Title 3</div>
                <div class="panel-body">

                 <!-- content here -->

                </div>
            </div>
        </div>
        <div *ngIf="settingActive == 4">
          <div class="panel panel-primary">
              <div class="panel-heading text-bold"> Panel Title 4</div>
              <div class="panel-body">

               <!-- content here -->

              </div>
          </div>
        </div>
        <div *ngIf="settingActive == 5">
            <div class="panel panel-primary">
                <div class="panel-heading text-bold">Panel Title 5 </div>
                <div class="panel-body">

                    <!-- content here -->

                </div>
            </div>
        </div>
    </div>
</div>

and in my Class I added this so it implements on init. What this does is sets which tab you want to be active first on load.

export class BusinessInfoComponent implements OnInit {
  settingActive = 1;
}

I hope this can help you in some way :)


问:
Lazy paramater evaluation for a debug macro wrapped in a function
I am currently developing a small and simple logging library that acts as a Facade for the Boost.Log v2 C++ library.

My library is almost finished and I have successfully encapsulated Boost.Log, i.e.:

the API of my library is free of Boost.Log types, i.e. users do only have to deal with my types

the ABI of my library is free of Boost.Log types, i.e. dependencies do not have to link against Boost.Log.

There is one last thing I am not able to solve at the moment: Lazy parameter evaluation

I'll give a short usage example how Boost.Log behaves:

```<code>#include <chrono>
#include <thread>

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);
  return "DONE with time_costly_function";
}

int main() {
  boost::log::core::get()->set_filter(boost::log::trivial::severity >=
                                      boost::log::trivial::warning);
  BOOST_LOG_TRIVIAL(warning) << "This is evaluated: " << time_costly_function();
  BOOST_LOG_TRIVIAL(info) << "This is NOT evaluated: "
                          << time_costly_function();
}
</code>```

If you run the example above you can see that only the arguments for the first BOOST_LOG_TRIVIAL call are evaluated, i.e. time_costly_function() is only called once in total.

That is exactly the behavior that I want in my library, but as I mentioned I do not want that users have to deal with Boost.Log directly, but with my small Facade.

The following code illustrates the problem (very simplified to tackle down the actual problem):

```<code>#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

#include <chrono>
#include <thread>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);

  return "DONE with time_costly_function";
}

// Encapsulates Boost.Log. The API of my logging library does not know anything
// about Boost.Log (e.g. the Pimpl idiom is used).
//
// In reality this is a member function of a class in my library with the
// following signature:
//
// void log(const SeverityLevel level, const std::string& message) override;
//
void log(const std::string& message) { BOOST_LOG_TRIVIAL(warning) << message; }

// A custom logging macro.
//
// In reality this is a macro taking the object of a class with the member
// function illustrated above:
//
// FW_LOG(logger, level, message)
//
#define FW_LOG(message) log(message)

int main() {
  // TODO(wolters): This does not work, since everything is evaluated outside of
  // the Boost.Log macro(s). I want to call my macro as follows.
  //     FW_LOG(logger, level) << message << time_costly_function();
  // I.e. it should work like the Boost.Log macro(s) illustrated above.
  FW_LOG("foo" + time_costly_function());
}
</code>```

I identified the following problems in my code:

The function log may not take a std::string reference, since that will
always lead to an evaluation outside of that function.

The macro FW_LOG has to be rewritten in a manner that the following syntax is supported:
FW_LOG(logger, level) << message << time_costly_function();

I've thought about using streams and/or perfect forwarding using template functions, but I was unable to come up with a working solution (yet).

Requirements: The code has to be compilable using MSVC 12.0, Boost.Log 1.59.0. C+11 is allowed.

So my actual question is:

How do I have to rewrite the code in the second example (using both the macro and the function) to get the same behavior as in the first example?

答:
After playing around with my code I've come up with a solution, thanks to @Jarod42 and @Nicolás (https://stackoverflow.com/a/2196183/891439).

I've added a member function bool isLevelEnabledForAtLeastOneHandler(const SeverityLevel level) const to my Logger class in order to check if the severity level provided with the logging macro is enabled for at least one of the Handler classes added to the Logger instance.

I've modified the solution by @Nicolás (the Logger class extends a LoggerInterface Interface Class in my library):

```<code>class LoggerStream final : public std::ostringstream {
 public:
  LoggerStream(LoggerInterface& logger, const SeverityLevel level) : logger_{logger}, level_{level} {
    // NOOP
  }

  ~LoggerStream() {
    logger_.log(level_, str());
  }

 private:
  LoggerInterface& logger_;
  SeverityLevel level_;
};
</code>```

I've modified the macro provided by @Jarod42:

```<code>#define FW_LOG(logger, level) \
  if (logger.isLevelEnabledForAtLeastOneHandler(level)) LoggerStream(logger, level)
</code>```

I've changed the FW_LOG macro calls:

```<code>FW_LOG(logger, SeverityLevel::WARNING) << "IS EVALUATED " << time_costly_function();
FW_LOG(logger, SeverityLevel::DEBUG) << "IS NOT EVALUATED " << time_costly_function();
</code>```

If I configure the handler(s) added to the Logger with the severity level
WARNING, the second call to FW_LOG leads to the following behavior:

The condition if (logger.isLevelEnabledForAtLeastOneHandler(level)) in the macro FW_LOG evaluates to false.

The "stream arguments" << "IS NOT EVALUATED << time_costly_function() inserted into the macro FW_LOG are not evaluated, since no instance of the LoggerStream class is created.

So the only overhead my current solution has, is the call to isLevelEnabledForAtLeastOneHandler.

Not a perfect solution, but much better as before. I do not even had to modify the LoggerInterface Interface Class with the log member function for this solution.

Still my original question remains: Is it possible to forward the FW_LOG macro "stream arguments" to the member function Logger.log in a manner, that the Boost.Log macro can do all the work, i.e. all arguments are lazely evaluated inside of the member function and not inside of the macro?

Using the Boost.Log macros directly does not cause the same overhead as the solution provided. Therefore it feels like I've reinvented some parts of the wheel...

Body:
I am currently developing a small and simple logging library that acts as a Facade for the Boost.Log v2 C++ library.

My library is almost finished and I have successfully encapsulated Boost.Log, i.e.:

the API of my library is free of Boost.Log types, i.e. users do only have to deal with my types

the ABI of my library is free of Boost.Log types, i.e. dependencies do not have to link against Boost.Log.

There is one last thing I am not able to solve at the moment: Lazy parameter evaluation

I'll give a short usage example how Boost.Log behaves:

#include <chrono>
#include <thread>

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);
  return "DONE with time_costly_function";
}

int main() {
  boost::log::core::get()->set_filter(boost::log::trivial::severity >=
                                      boost::log::trivial::warning);
  BOOST_LOG_TRIVIAL(warning) << "This is evaluated: " << time_costly_function();
  BOOST_LOG_TRIVIAL(info) << "This is NOT evaluated: "
                          << time_costly_function();
}

If you run the example above you can see that only the arguments for the first BOOST_LOG_TRIVIAL call are evaluated, i.e. time_costly_function() is only called once in total.

That is exactly the behavior that I want in my library, but as I mentioned I do not want that users have to deal with Boost.Log directly, but with my small Facade.

The following code illustrates the problem (very simplified to tackle down the actual problem):

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

#include <chrono>
#include <thread>

std::string time_costly_function(
    const std::chrono::seconds seconds = std::chrono::seconds{1}) {
  std::this_thread::sleep_for(seconds);

  return "DONE with time_costly_function";
}

// Encapsulates Boost.Log. The API of my logging library does not know anything
// about Boost.Log (e.g. the Pimpl idiom is used).
//
// In reality this is a member function of a class in my library with the
// following signature:
//
// void log(const SeverityLevel level, const std::string& message) override;
//
void log(const std::string& message) { BOOST_LOG_TRIVIAL(warning) << message; }

// A custom logging macro.
//
// In reality this is a macro taking the object of a class with the member
// function illustrated above:
//
// FW_LOG(logger, level, message)
//
#define FW_LOG(message) log(message)

int main() {
  // TODO(wolters): This does not work, since everything is evaluated outside of
  // the Boost.Log macro(s). I want to call my macro as follows.
  //     FW_LOG(logger, level) << message << time_costly_function();
  // I.e. it should work like the Boost.Log macro(s) illustrated above.
  FW_LOG("foo" + time_costly_function());
}

I identified the following problems in my code:

The function log may not take a std::string reference, since that will
always lead to an evaluation outside of that function.

The macro FW_LOG has to be rewritten in a manner that the following syntax is supported:
FW_LOG(logger, level) << message << time_costly_function();

I've thought about using streams and/or perfect forwarding using template functions, but I was unable to come up with a working solution (yet).

Requirements: The code has to be compilable using MSVC 12.0, Boost.Log 1.59.0. C+11 is allowed.

So my actual question is:

How do I have to rewrite the code in the second example (using both the macro and the function) to get the same behavior as in the first example?

Body:
After playing around with my code I've come up with a solution, thanks to @Jarod42 and @Nicolás (https://stackoverflow.com/a/2196183/891439).

I've added a member function bool isLevelEnabledForAtLeastOneHandler(const SeverityLevel level) const to my Logger class in order to check if the severity level provided with the logging macro is enabled for at least one of the Handler classes added to the Logger instance.

I've modified the solution by @Nicolás (the Logger class extends a LoggerInterface Interface Class in my library):

class LoggerStream final : public std::ostringstream {
 public:
  LoggerStream(LoggerInterface& logger, const SeverityLevel level) : logger_{logger}, level_{level} {
    // NOOP
  }

  ~LoggerStream() {
    logger_.log(level_, str());
  }

 private:
  LoggerInterface& logger_;
  SeverityLevel level_;
};

I've modified the macro provided by @Jarod42:

#define FW_LOG(logger, level) \
  if (logger.isLevelEnabledForAtLeastOneHandler(level)) LoggerStream(logger, level)

I've changed the FW_LOG macro calls:

FW_LOG(logger, SeverityLevel::WARNING) << "IS EVALUATED " << time_costly_function();
FW_LOG(logger, SeverityLevel::DEBUG) << "IS NOT EVALUATED " << time_costly_function();

If I configure the handler(s) added to the Logger with the severity level
WARNING, the second call to FW_LOG leads to the following behavior:

The condition if (logger.isLevelEnabledForAtLeastOneHandler(level)) in the macro FW_LOG evaluates to false.

The "stream arguments" << "IS NOT EVALUATED << time_costly_function() inserted into the macro FW_LOG are not evaluated, since no instance of the LoggerStream class is created.

So the only overhead my current solution has, is the call to isLevelEnabledForAtLeastOneHandler.

Not a perfect solution, but much better as before. I do not even had to modify the LoggerInterface Interface Class with the log member function for this solution.

Still my original question remains: Is it possible to forward the FW_LOG macro "stream arguments" to the member function Logger.log in a manner, that the Boost.Log macro can do all the work, i.e. all arguments are lazely evaluated inside of the member function and not inside of the macro?

Using the Boost.Log macros directly does not cause the same overhead as the solution provided. Therefore it feels like I've reinvented some parts of the wheel...


问:
Does the null object pattern make debugging more complicated?
I was wondering if the null object pattern could actually make debugging more difficult in certain cases. For example, if a method returns an "empty" object rather than a null then it will not throw an error. This is good in terms of reliable, clean code but couldn't it mean that there is now an empty object being used that essentially does nothing that could cause unexpected bugs. Rather than having a null exception to point the programmer to the problem there is now nothing to help locate it. </p>

答:
Yes it can because if your null object has to return a value (as in your example) you are just deferring the null issue and still need to check for null values.

I have found null object to be very helpful with two conditions are met.

You are only calling methods with no return value.

You wan't to ignore actions when there is no value.

A simple example is a callback.

```<code>class Callback {
   void onDoSomething(SomeArg someArg);
}
</code>```

Typically you would have to do a null check before using the callback

```<code>if (callback != null) {
    callback.onDoSomething(someArg);
}
</code>```

With the null object pattern you can have the default value of the callback be a null object and avoid the null checks in the rest of your code. Less boiler-plate code makes it easier to see the important parts.

Body:
Yes it can because if your null object has to return a value (as in your example) you are just deferring the null issue and still need to check for null values.

I have found null object to be very helpful with two conditions are met.

You are only calling methods with no return value.

You wan't to ignore actions when there is no value.

A simple example is a callback.

class Callback {
   void onDoSomething(SomeArg someArg);
}

Typically you would have to do a null check before using the callback

if (callback != null) {
    callback.onDoSomething(someArg);
}

With the null object pattern you can have the default value of the callback be a null object and avoid the null checks in the rest of your code. Less boiler-plate code makes it easier to see the important parts.