问:
WPF/MVVM - should view-models stay constant and just the model change?
I'm a bit in doubt as to what is 'the right way'.

I have an application with concepts like visual studio, so I'll use that to explain:

I have a 'solution' view model and a model behind. The view model is displayed in a 'explorer'.

I can change between the situations where 'no solution is loaded' to 'a solution is loaded' and back.

And finally my question :-) :

Should I keep my view model object and let it reflect that I have a new 'solution object' loaded? Or should I create a new view model object and let the view bind to the new object?

答:
What is the arrengement of the ViewModel?

In General

View Model is the localized version of actualmodel and View is updated whenever there is a change i its viewModel through DataBiding.

in your case ,you have 2 states.

1- Your View is Loaded

2- Your View is not loaded

so should I create a new view model object and let the view bind to the new object?

in my thoughts ,YES


来源: stackexchange

问:
Database Jquery - Column Headers Misalign when using ScrollY
I'm using jQuery's DataTables and Bootstrap. So the problem I have is that when I switch between tabs of "completed" and "dead", the "dead" tab's column headers get bunched up on the left until I click on them and then they align themselves correctly. This happens whenever I refresh. I tried using CSS with overflow:auto, but that makes my whole panel scrollable, which I don't want. I want the headers to stay fixed while i scroll through the table.

```<code>  <div class = 'row'>
  <div class='col-lg-11'>

  <div id="pane3" >
  <ul class="nav nav-tabs">
    <li class="active">
      <a  href="#4a" data-toggle="tab">My Completed</a>
    </li>
    <li>
      <a  href="#4b" id="deadTab"  data-toggle="tab">Dead Requests</a>
    </li>

  </ul>
  <div class="tab-content">
      <div class='tab-pane active' id ="4a">
        <!-- <div id="" style=" width: 100%; position:relative; height:200px;"> -->
          <table id='completed' class="table table-striped table-hover">
          <thead>
            <tr>
              <th>Req. #</th>
              <th>Project #</th>
              <th>Client Name</th>
              <th>Program</th>
              <th>Request Type</th>
              <th>Assignee</th>
              <th>Completed Date</th>
              <th>Clone</th>

            </tr>
          </thead>
          <tbody>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
          </tbody>
        </table>
      <!--   </div> -->
        </div>
          <div class='tab-pane' id ="4b">
         <!--  <div id="" style=" overflow:auto; position:relative; "> -->
            <table id='dead' class="table table-striped table-hover">
            <thead>
              <tr>
                <th>Req. #</th>
                <th>Project #</th>
                <th>Client Name</th>
                <th>Program</th>
                <th>Request Type</th>
                <th>Assignee</th>
                <th>Dead Date</th>
                <th>Restart</th>
              </tr>
            </thead>
            <tbody>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
            <tr>
              <td>July</td>
              <td>Dooley</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>john@e</td>
              <td>july@example.com</td>
              <td>6/12/2017</td>
              <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
            </tr>
          </tbody>
          </table>
         <!--  </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

```<code><script>

$(document).ready(function() {

   $('#completed').DataTable( {
    "paging":false,
    // "fixedHeader": true,
    "scrollY": "140px",
    "table-layout":"fixed",
    "columnDefs":[
    {"width":60, "targets":0},
    {"width":60, "targets":1},
    {"width":60, "targets":2},
    {"width":60, "targets":3},
    {"width":90, "targets":4},
    {"width":90, "targets":5},
    {"width":90, "targets":6},
    {"width":90, "targets":7},
    ]

  });

  $('#dead').DataTable( {
    "paging":false,
    "fixedHeader": true,
    "scrollY": "140px",
    "table-layout":"fixed",
     "columnDefs":[
    {"width":60, "targets":0},
    {"width":60, "targets":1},
    {"width":60, "targets":2},
    {"width":60, "targets":3},
    {"width":90, "targets":4},
    {"width":90, "targets":5},
    {"width":90, "targets":6},
    {"width":90, "targets":7},
    ]

    // "table-layout":"fixed"

  });

});

</script>
</code>```

答:
The problem is that your other tab is hidden (display: none). You can initialize your data table after dead tab is shown like this:

$('#completed').DataTable({
  "paging": false,
  // "fixedHeader": true,
  "scrollY": "140px",
  "table-layout": "fixed",
  "columnDefs": [{
      "width": 60,
      "targets": 0
    },
    {
      "width": 60,
      "targets": 1
    },
    {
      "width": 60,
      "targets": 2
    },
    {
      "width": 60,
      "targets": 3
    },
    {
      "width": 90,
      "targets": 4
    },
    {
      "width": 90,
      "targets": 5
    },
    {
      "width": 90,
      "targets": 6
    },
    {
      "width": 90,
      "targets": 7
    },
  ]

});

$('#deadTab').one('shown.bs.tab', function(e) {
  $('#dead').DataTable({
    "paging": false,
    "fixedHeader": true,
    "scrollY": "140px",
    "table-layout": "fixed",
    "columnDefs": [{
        "width": 60,
        "targets": 0
      },
      {
        "width": 60,
        "targets": 1
      },
      {
        "width": 60,
        "targets": 2
      },
      {
        "width": 60,
        "targets": 3
      },
      {
        "width": 90,
        "targets": 4
      },
      {
        "width": 90,
        "targets": 5
      },
      {
        "width": 90,
        "targets": 6
      },
      {
        "width": 90,
        "targets": 7
      },
    ]

    // "table-layout":"fixed"

  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<div class="container">
  <div class='row'>
    <div class='col-lg-11'>
      <div id="pane3">
        <ul class="nav nav-tabs">
          <li class="active">
            My Completed
          </li>
          <li>
            Dead Requests
          </li>

        </ul>
        <div class="tab-content">
          <div class='tab-pane active' id="4a">
            <!-- <div id="" style=" width: 100%; position:relative; height:200px;"> -->
            <table id='completed' class="table table-striped table-hover">
              <thead>
                <tr>
                  <th>Req. #</th>
                  <th>Project #</th>
                  <th>Client Name</th>
                  <th>Program</th>
                  <th>Request Type</th>
                  <th>Assignee</th>
                  <th>Completed Date</th>
                  <th>Clone</th>

                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
              </tbody>
            </table>
            <!--   </div> -->
          </div>
          <div class='tab-pane' id="4b">
            <!--  <div id="" style=" overflow:auto; position:relative; "> -->
            <table id='dead' class="table table-striped table-hover">
              <thead>
                <tr>
                  <th>Req. #</th>
                  <th>Project #</th>
                  <th>Client Name</th>
                  <th>Program</th>
                  <th>Request Type</th>
                  <th>Assignee</th>
                  <th>Dead Date</th>
                  <th>Restart</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
              </tbody>
            </table>
            <!--  </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using jQuery's DataTables and Bootstrap. So the problem I have is that when I switch between tabs of "completed" and "dead", the "dead" tab's column headers get bunched up on the left until I click on them and then they align themselves correctly. This happens whenever I refresh. I tried using CSS with overflow:auto, but that makes my whole panel scrollable, which I don't want. I want the headers to stay fixed while i scroll through the table.

      My Completed

      Dead Requests

              Req. #
              Project #
              Client Name
              Program
              Request Type
              Assignee
              Completed Date
              Clone

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

                Req. #
                Project #
                Client Name
                Program
                Request Type
                Assignee
                Dead Date
                Restart

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

              July
              Dooley
              john@e
              john@e
              john@e
              july@example.com
              6/12/2017
              <button type="button" class="btn btn-primary btn-xs">View Form</button>

Body:
The problem is that your other tab is hidden (display: none). You can initialize your data table after dead tab is shown like this:

$('#completed').DataTable({
  "paging": false,
  // "fixedHeader": true,
  "scrollY": "140px",
  "table-layout": "fixed",
  "columnDefs": [{
      "width": 60,
      "targets": 0
    },
    {
      "width": 60,
      "targets": 1
    },
    {
      "width": 60,
      "targets": 2
    },
    {
      "width": 60,
      "targets": 3
    },
    {
      "width": 90,
      "targets": 4
    },
    {
      "width": 90,
      "targets": 5
    },
    {
      "width": 90,
      "targets": 6
    },
    {
      "width": 90,
      "targets": 7
    },
  ]

});

$('#deadTab').one('shown.bs.tab', function(e) {
  $('#dead').DataTable({
    "paging": false,
    "fixedHeader": true,
    "scrollY": "140px",
    "table-layout": "fixed",
    "columnDefs": [{
        "width": 60,
        "targets": 0
      },
      {
        "width": 60,
        "targets": 1
      },
      {
        "width": 60,
        "targets": 2
      },
      {
        "width": 60,
        "targets": 3
      },
      {
        "width": 90,
        "targets": 4
      },
      {
        "width": 90,
        "targets": 5
      },
      {
        "width": 90,
        "targets": 6
      },
      {
        "width": 90,
        "targets": 7
      },
    ]

    // "table-layout":"fixed"

  });
})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<div class="container">
  <div class='row'>
    <div class='col-lg-11'>
      <div id="pane3">
        <ul class="nav nav-tabs">
          <li class="active">
            <a href="#4a" data-toggle="tab">My Completed</a>
          </li>
          <li>
            <a href="#4b" id="deadTab" data-toggle="tab">Dead Requests</a>
          </li>

        </ul>
        <div class="tab-content">
          <div class='tab-pane active' id="4a">
            <!-- <div id="" style=" width: 100%; position:relative; height:200px;"> -->
            <table id='completed' class="table table-striped table-hover">
              <thead>
                <tr>
                  <th>Req. #</th>
                  <th>Project #</th>
                  <th>Client Name</th>
                  <th>Program</th>
                  <th>Request Type</th>
                  <th>Assignee</th>
                  <th>Completed Date</th>
                  <th>Clone</th>

                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
              </tbody>
            </table>
            <!--   </div> -->
          </div>
          <div class='tab-pane' id="4b">
            <!--  <div id="" style=" overflow:auto; position:relative; "> -->
            <table id='dead' class="table table-striped table-hover">
              <thead>
                <tr>
                  <th>Req. #</th>
                  <th>Project #</th>
                  <th>Client Name</th>
                  <th>Program</th>
                  <th>Request Type</th>
                  <th>Assignee</th>
                  <th>Dead Date</th>
                  <th>Restart</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
                <tr>
                  <td>July</td>
                  <td>Dooley</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>john@e</td>
                  <td>july@example.com</td>
                  <td>6/12/2017</td>
                  <td><button type="button" class="btn btn-primary btn-xs">View Form</button></td>
                </tr>
              </tbody>
            </table>
            <!--  </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


问:
Excels "Refresh All" sometimes not working
I have a VBA function that opens a file, refreshes all the data connections, saves the file and the returns "true" if the refresh was successful. Here is the code:

```<code>Public Function RefreshFile(ByVal wbName As String, ByVal FilePath As String, ByVal pword As String)

Dim blTmp As Boolean
Dim wbRefresh As Workbook

blTmp = Not (IsWorkBookOpen(FilePath))

If blTmp Then
    Workbooks.Open Filename:=FilePath, ReadOnly:=False, Notify:=False, WriteResPassword:=pword, IgnoreReadOnlyRecommended:=True
Else
    RefreshFile = False
    Exit Function
End If

Set wbRefresh = Workbooks(wbName & ".xlsx")

wbRefresh.Activate
ActiveWorkbook.RefreshAll
DoEvents

'MsgBox "complete"

wbRefresh.Close savechanges:=True

RefreshFile = True

End Function
</code>```

The list opens a series of files and some are password protected and read-only suggested (hence the parameters passed). With the read-only suggested files though, files get saved with only one of the connections refreshed. Basically it refreshes the first connection and then saves the file.

I've tested this a number of times and if I stop the function after 'DoEvents' (notice the MsgBox to stop the code), then all the connections are in fact refreshed. If I don't stop the code and reopen the saved file later on, only one of the connections get refreshed. Is this an issue with 'RefreshAll' or when it goes to save the file? Perhaps I'm not opening the file with the full, appropriate permissions??

答: The solution is that 'enable background refresh' needs to be unchecked on each data table. Don't ask me what exactly this means, but after a lot of trial/error, I finally got it to work by unchecking the 'enable background refresh' option on the data connections for the data tables.</p>

Body:
I have a VBA function that opens a file, refreshes all the data connections, saves the file and the returns "true" if the refresh was successful. Here is the code:

Public Function RefreshFile(ByVal wbName As String, ByVal FilePath As String, ByVal pword As String)

Dim blTmp As Boolean
Dim wbRefresh As Workbook

blTmp = Not (IsWorkBookOpen(FilePath))

If blTmp Then
    Workbooks.Open Filename:=FilePath, ReadOnly:=False, Notify:=False, WriteResPassword:=pword, IgnoreReadOnlyRecommended:=True
Else
    RefreshFile = False
    Exit Function
End If

Set wbRefresh = Workbooks(wbName & ".xlsx")

wbRefresh.Activate
ActiveWorkbook.RefreshAll
DoEvents

'MsgBox "complete"

wbRefresh.Close savechanges:=True

RefreshFile = True

End Function

The list opens a series of files and some are password protected and read-only suggested (hence the parameters passed). With the read-only suggested files though, files get saved with only one of the connections refreshed. Basically it refreshes the first connection and then saves the file.

I've tested this a number of times and if I stop the function after 'DoEvents' (notice the MsgBox to stop the code), then all the connections are in fact refreshed. If I don't stop the code and reopen the saved file later on, only one of the connections get refreshed. Is this an issue with 'RefreshAll' or when it goes to save the file? Perhaps I'm not opening the file with the full, appropriate permissions??


问:
Lumen 5.4 hasMany relationship on two columns to same model
I have two tables: players and battles.
When a player dwells another one, a new row is inserted on the battles table where the id for challenger player is stored on player1_id column and the challenged player is stored on player2_id

My battles table looks like so:

id

player1_id (challenger player)

player2_id (challenged player)

...

What I need is to have a hasMany relationship between players to battles matching either of the columns.

I found a solution for an almost identical issue and tried what user Colling James suggested https://stackoverflow.com/a/29775608/1481559 but it didn't work for me.

Another solution I tried was using union as per Acasar's suggestion on https://laracasts.com/discuss/channels/eloquent/combining-multiple-hasmany-relationships-into-one-model-relation-query-builder

```<code>public function battles() {
    return $this->hasMany('App\Battle')->union($this->hasMany('App\Battle')->toBase());
}
</code>```

but I had no success.

答:
I think in your case it's not important to return a hasMany object because it would be impossible to add. I think there is no solution because a 1 to n relationship needs one field for the foreign key and not an or-statement.

If you just want to return the battles in an array you can do this:

```<code>public function battles() {
    return App\Battle::where('player1_id', $this->id)->orWhere('player2_id', $this->id)->get();
}
</code>```

In this case you just have one query. Otherwise you can fire up 2 has many queries where you link first to the one id, than to the other one and then merge them, but I think the solution above is the easiest one.

If you want to work with has many you can try this (maybe it does not work because the foreign key is not set in the db)

```<code>public function battlesChallenger() {
    return $this->hasMany('App\Battle', 'player1_id');
}

public function battlesChallenged() {
    return $this->hasMany('App\Battle', 'player2_id');
}

public function battles() {
    return $this->battlesChallenger()->merge($this->battlesChallengered());
}
</code>```

Body:
I have two tables: players and battles.
When a player dwells another one, a new row is inserted on the battles table where the id for challenger player is stored on player1_id column and the challenged player is stored on player2_id

My battles table looks like so:

id

player1_id (challenger player)

player2_id (challenged player)

...

What I need is to have a hasMany relationship between players to battles matching either of the columns.

I found a solution for an almost identical issue and tried what user Colling James suggested https://stackoverflow.com/a/29775608/1481559 but it didn't work for me.

Another solution I tried was using union as per Acasar's suggestion on https://laracasts.com/discuss/channels/eloquent/combining-multiple-hasmany-relationships-into-one-model-relation-query-builder

public function battles() {
    return $this->hasMany('App\Battle')->union($this->hasMany('App\Battle')->toBase());
}

but I had no success.

Body:
I think in your case it's not important to return a hasMany object because it would be impossible to add. I think there is no solution because a 1 to n relationship needs one field for the foreign key and not an or-statement.

If you just want to return the battles in an array you can do this:

public function battles() {
    return App\Battle::where('player1_id', $this->id)->orWhere('player2_id', $this->id)->get();
}

In this case you just have one query. Otherwise you can fire up 2 has many queries where you link first to the one id, than to the other one and then merge them, but I think the solution above is the easiest one.

If you want to work with has many you can try this (maybe it does not work because the foreign key is not set in the db)

public function battlesChallenger() {
    return $this->hasMany('App\Battle', 'player1_id');
}

public function battlesChallenged() {
    return $this->hasMany('App\Battle', 'player2_id');
}

public function battles() {
    return $this->battlesChallenger()->merge($this->battlesChallengered());
}


问:
Get unique values from a list in python
I want to get the unique values from the following list:

```<code>['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']
</code>```

The output which I require is:

```<code>['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']
</code>```

This code works:

```<code>output = []
for x in trends:
    if x not in output:
        output.append(x)
print(output)
</code>```

is there a better solution I should use?

答:
Maintaining order:

```<code># oneliners
# slow -> . --- 14.417 seconds ---
[x for i, x in enumerate(array) if x not in array[0:i]]

# fast -> . --- 0.0378 seconds ---
[x for i, x in enumerate(array) if array.index(x) == i]

# multiple lines
# fastest -> --- 0.012 seconds ---
uniq = []
[uniq.append(x) for x in array if x not in uniq]
uniq
</code>```

Order doesn't matter:

```<code># fastest-est -> --- 0.0035 seconds ---
list(set(array))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get unique values from a list in python

Body:
I want to get the unique values from the following list:

['nowplaying', 'PBS', 'PBS', 'nowplaying', 'job', 'debate', 'thenandnow']

The output which I require is:

['nowplaying', 'PBS', 'job', 'debate', 'thenandnow']

This code works:

output = []
for x in trends:
    if x not in output:
        output.append(x)
print(output)

is there a better solution I should use?

Body:
Maintaining order:

# oneliners
# slow -> . --- 14.417 seconds ---
[x for i, x in enumerate(array) if x not in array[0:i]]

# fast -> . --- 0.0378 seconds ---
[x for i, x in enumerate(array) if array.index(x) == i]

# multiple lines
# fastest -> --- 0.012 seconds ---
uniq = []
[uniq.append(x) for x in array if x not in uniq]
uniq

Order doesn't matter:

# fastest-est -> --- 0.0035 seconds ---
list(set(array))


问:
Swift JSON parsing and printing a specified value from an array
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?

And Hier is my code:

```<code>func apiRequest() {
    let config = URLSessionConfiguration.default
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
    let password = "G23@rE9t1#"
    let loginString = String(format: "%@:%@", username, password)
    let userPasswordData = loginString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData?.base64EncodedString()
    let authString = "Basic " + (base64EncodedCredential)!

    print(authString)
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    var running = false
    let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")

    let task = session.dataTask(with: url! as URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
            print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(array)

                    if let items = array["items"] {
                         if let description = items["Description"] as? [[String:Any]]{
                            print(description as Any)
                         }
                    }
                }
                catch {
                    print("Error: Could not get any data")
                }
            }
        }
        running = false
    }

    running = true
    task.resume()

    while running {
        print("waiting...")
        sleep(1)
    }
}
</code>```

答:
First of all the array is not an array and not AnyObject, it's a dictionary which is [String:Any] in Swift 3.

```<code>let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)
</code>```

I don't know why all tutorials suggest .mutableContainers as option. That might be useful in Objective-C but is completely meaningless in Swift. Omit the parameter.

The object for key itemsis an array of dictionaries (again, the unspecified JSON type in Swift 3 is Any). Use a repeat loop to get all description values and you have to downcast all values of a dictionary from Any to the expected type.

```<code>if let items = dictionary["items"] as? [[String:Any]] {
   for item in items {
       if let description = item["Description"] as? String {
          print(description)
       }
   }
}
</code>```

Body:
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?

And Hier is my code:

func apiRequest() {
    let config = URLSessionConfiguration.default
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
    let password = "G23@rE9t1#"
    let loginString = String(format: "%@:%@", username, password)
    let userPasswordData = loginString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData?.base64EncodedString()
    let authString = "Basic " + (base64EncodedCredential)!

    print(authString)
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    var running = false
    let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")

    let task = session.dataTask(with: url! as URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
            print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(array)

                    if let items = array["items"] {
                         if let description = items["Description"] as? [[String:Any]]{
                            print(description as Any)
                         }
                    }
                }
                catch {
                    print("Error: Could not get any data")
                }
            }
        }
        running = false
    }

    running = true
    task.resume()

    while running {
        print("waiting...")
        sleep(1)
    }
}

Body:
First of all the array is not an array and not AnyObject, it's a dictionary which is [String:Any] in Swift 3.

let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)

I don't know why all tutorials suggest .mutableContainers as option. That might be useful in Objective-C but is completely meaningless in Swift. Omit the parameter.

The object for key itemsis an array of dictionaries (again, the unspecified JSON type in Swift 3 is Any). Use a repeat loop to get all description values and you have to downcast all values of a dictionary from Any to the expected type.

if let items = dictionary["items"] as? [[String:Any]] {
   for item in items {
       if let description = item["Description"] as? String {
          print(description)
       }
   }
}


问:
add + button before a row
How can i add green + button before a row in group table see in image

答:
```<code>- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    if(indexPath.row == 1)//type your condition here

    {
        return UITableViewCellEditingStyleDelete;
    }
    else{

        return UITableViewCellEditingStyleInsert;
    }

}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        //type your code here
    }else if(editingStyle == UITableViewCellEditingStyleInsert){

           //type your code here
        }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: add + button before a row


问:
Tensorflow Enqueue operation was cancelled
I had built a convolutional neural network in tensorflow. It is trained and now I am unpacking it and performing evaluations.

```<code>import main
import Process
import Input

eval_dir = "/Users/Zanhuang/Desktop/NNP/model.ckpt-250"
checkpoint_dir = "/Users/Zanhuang/Desktop/NNP/checkpoint"

def evaluate():
  with tf.Graph().as_default() as g:
    images, labels = Process.eval_inputs()
    forward_propgation_results = Process.forward_propagation(images)
    init_op = tf.initialize_all_variables()
    saver = tf.train.Saver()
    top_k_op = tf.nn.in_top_k(forward_propgation_results, labels, 1)

  with tf.Session(graph=g) as sess:
    tf.train.start_queue_runners(sess=sess)
    sess.run(init_op)
    saver.restore(sess, eval_dir)
    print(sess.run(top_k_op))

def main(argv=None):
    evaluate()

if __name__ == '__main__':
  tf.app.run()
</code>```

Unfortunately a strange error has popped up and I have no clue why.

```<code>W tensorflow/core/kernels/queue_base.cc:2
W tensorflow/core/kernels/queue_base.cc:294] _0_input_producer: Skipping cancelled enqueue attempt with queue not closed
W tensorflow/core/kernels/queue_base.cc:294] _1_batch/fifo_queue: Skipping cancelled enqueue attempt with queue not closed
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     ....
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
W tensorflow/core/kernels/queue_base.cc:294] _1_batch/fifo_queue: Skipping cancelled enqueue attempt with queue not closed
...
W tensorflow/core/kernels/queue_base.cc:294] _1_batch/fifo_queue: Skipping cancelled enqueue attempt with queue not closed
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
</code>```

This is only a part of it.

答:
Everything works correctly and the problem happens at the very last stage when python tries to kill threads. To do this properly you should create a train.Coordinator and pass it to your queue_runner (no need to pass sess, as default session will be used

```<code>with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    // do your things
    coord.request_stop()
    coord.join(threads)
</code>```

Body:
I had built a convolutional neural network in tensorflow. It is trained and now I am unpacking it and performing evaluations.

import main
import Process
import Input

eval_dir = "/Users/Zanhuang/Desktop/NNP/model.ckpt-250"
checkpoint_dir = "/Users/Zanhuang/Desktop/NNP/checkpoint"

def evaluate():
  with tf.Graph().as_default() as g:
    images, labels = Process.eval_inputs()
    forward_propgation_results = Process.forward_propagation(images)
    init_op = tf.initialize_all_variables()
    saver = tf.train.Saver()
    top_k_op = tf.nn.in_top_k(forward_propgation_results, labels, 1)

  with tf.Session(graph=g) as sess:
    tf.train.start_queue_runners(sess=sess)
    sess.run(init_op)
    saver.restore(sess, eval_dir)
    print(sess.run(top_k_op))

def main(argv=None):
    evaluate()

if __name__ == '__main__':
  tf.app.run()

Unfortunately a strange error has popped up and I have no clue why.

W tensorflow/core/kernels/queue_base.cc:2
W tensorflow/core/kernels/queue_base.cc:294] _0_input_producer: Skipping cancelled enqueue attempt with queue not closed
W tensorflow/core/kernels/queue_base.cc:294] _1_batch/fifo_queue: Skipping cancelled enqueue attempt with queue not closed
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     ....
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled
     [[Node: batch/fifo_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], _class=["loc:@batch/fifo_queue"], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](batch/fifo_queue, Cast_1, Cast)]]
W tensorflow/core/kernels/queue_base.cc:294] _1_batch/fifo_queue: Skipping cancelled enqueue attempt with queue not closed
...
W tensorflow/core/kernels/queue_base.cc:294] _1_batch/fifo_queue: Skipping cancelled enqueue attempt with queue not closed
E tensorflow/core/client/tensor_c_api.cc:485] Enqueue operation was cancelled

This is only a part of it.

Body:
Everything works correctly and the problem happens at the very last stage when python tries to kill threads. To do this properly you should create a train.Coordinator and pass it to your queue_runner (no need to pass sess, as default session will be used

with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    // do your things
    coord.request_stop()
    coord.join(threads)


问:
Cant pass a function to a React child from parent (through a list)
Im trying to pass a simple list from a parent to a set of child components and i cant pass down a function. i have something line for line that is the exact same bloody thing that works but this does not.

Does anyone see what is going wrong?

This is the function in the parent that i cant reach (the console.log is not firing):

```<code>setClassImage(name, image){
     console.log('inside setClassImage');
     var TitleArray = this.state.TitleArray;
     TitleArray[0] = name;
     var ImageArray = this.state.ImageArray;
     ImageArray[0] = image;
     this.setState({
       characterModal: false,
       equipmentModal: false,
       TitleArray: TitleArray,
       ImageArray: ImageArray
     });
   }
</code>```

Setting the list in the parent:

```<code>   let listClasses;

           if(this.state.classResults.length!=0){
                 listClasses = this.state.classResults.map((item,i) => {
                   return (
                     <ListClass key={i} classes={item} setClassImage={this.setClassImage.bind(this)}/>
                   );
                 });
           }
</code>```

in the render of the parent:

```<code>        <SelectorBox>
          <ListBox>
            {listClasses}
            <br/>
          </ListBox>
          <SelectorButton onClick={(e)=>this.cancelChange(e)}>No Class</SelectorButton>
        </SelectorBox>
</code>```

In the child:

```<code>class ListClass extends Component{
  constructor(props){
    super(props);
    this.state={

    }
  }

  getImage(e){
    e.preventDefault();
    var self = this;
    axios.post('http://localhost:5000/post2/characterimage', {
      search: this.props.classes,
    })
      .then((response)=>{
       console.log('response from the pixabay call ', response.data);
       self.props.setClassImage(self.props.classes, response.data);
      })
     .catch(()=>{
       console.log('hello axios error');
     });
  }

    render(){
      return(
        <div>
          <ItemContainer onClick={(e)=>this.getImage(e)}>
            <p>
              {this.props.classes}
            </p>
          </ItemContainer>
        </div>
      )
    }
}
</code>```

I can see console.log('response from the pixabay call ', response.data); and it fires correctly from data on the backend. But the function is not called! The weirdly named containers are purely for styling, so just assume they all act like divs.

答:
The arrow function in your .then()  call will automatically bind this to the proper context,  so you don't need to do the var self = this;  However you do need to bind your getImage function in your constructor.  OR

Update your function definition to:

```<code>  ....
  getImage = (e) => {
    e.preventDefault();
    axios.post('http://localhost:5000/post2/characterimage', {
      search: this.props.classes,
    })
      .then((response) => {
       console.log('response from the pixabay call ', response.data);
       this.props.setClassImage(this.props.classes, response.data);
      })
     .catch(()=>{
       console.log('hello axios error');
     });
  }

  ....
}
</code>```

Otherwise,  bind getImage in your constructor:

```<code>constructor(props){
    super(props);
    this.state = {};

    this.getImage = this.getImage.bind(this);
  }
</code>```

Body:
Im trying to pass a simple list from a parent to a set of child components and i cant pass down a function. i have something line for line that is the exact same bloody thing that works but this does not.

Does anyone see what is going wrong?

This is the function in the parent that i cant reach (the console.log is not firing):

setClassImage(name, image){
     console.log('inside setClassImage');
     var TitleArray = this.state.TitleArray;
     TitleArray[0] = name;
     var ImageArray = this.state.ImageArray;
     ImageArray[0] = image;
     this.setState({
       characterModal: false,
       equipmentModal: false,
       TitleArray: TitleArray,
       ImageArray: ImageArray
     });
   }

Setting the list in the parent:

   let listClasses;

           if(this.state.classResults.length!=0){
                 listClasses = this.state.classResults.map((item,i) => {
                   return (
                     <ListClass key={i} classes={item} setClassImage={this.setClassImage.bind(this)}/>
                   );
                 });
           }

in the render of the parent:

        <SelectorBox>
          <ListBox>
            {listClasses}

          </ListBox>
          <SelectorButton onClick={(e)=>this.cancelChange(e)}>No Class</SelectorButton>
        </SelectorBox>

In the child:

class ListClass extends Component{
  constructor(props){
    super(props);
    this.state={

    }
  }

  getImage(e){
    e.preventDefault();
    var self = this;
    axios.post('http://localhost:5000/post2/characterimage', {
      search: this.props.classes,
    })
      .then((response)=>{
       console.log('response from the pixabay call ', response.data);
       self.props.setClassImage(self.props.classes, response.data);
      })
     .catch(()=>{
       console.log('hello axios error');
     });
  }

    render(){
      return(

          <ItemContainer onClick={(e)=>this.getImage(e)}>

              {this.props.classes}

          </ItemContainer>

      )
    }
}

I can see console.log('response from the pixabay call ', response.data); and it fires correctly from data on the backend. But the function is not called! The weirdly named containers are purely for styling, so just assume they all act like divs.

Body:
The arrow function in your .then()  call will automatically bind this to the proper context,  so you don't need to do the var self = this;  However you do need to bind your getImage function in your constructor.  OR

Update your function definition to:

  ....
  getImage = (e) => {
    e.preventDefault();
    axios.post('http://localhost:5000/post2/characterimage', {
      search: this.props.classes,
    })
      .then((response) => {
       console.log('response from the pixabay call ', response.data);
       this.props.setClassImage(this.props.classes, response.data);
      })
     .catch(()=>{
       console.log('hello axios error');
     });
  }

  ....
}

Otherwise,  bind getImage in your constructor:

constructor(props){
    super(props);
    this.state = {};

    this.getImage = this.getImage.bind(this);
  }


问:
Availability of BridgeConnect in Magento
One of our clients is thinking of buying an Enterprise Edition, due to his requirement of using the Exact CRM Services with Magento. But today, to my utter astonishment, I’m not finding any inclusion of ”BridgeConnect” module in either the ”Enterprise” or the ”Professional” Editions.

Can anybody from the SO please highlight, whether Magento still provides this ”BridgeConnect” module with the ”Enterprise” or the ”Professional” Editions?

If this module is not being provided, then when will Magento provide this module?
Or, is Magento planning to provide any better solution module, instead of the ”BridgeConnect” module?

This is very much urgent for us, and will be very very grateful for some quick responses.
Any help is really appreciated.

答: According to this page it is included. Even if you're not yet an enterprise licence holder you can still contact Magento's customer support and ask them directly.</p>


问:
How to notify users as soon as the ListView gets updated in Android
I want to notify users with a notification whenever the ListView is updated. In my app, an admin posts messages and the users should be notified about that message. How can I do that?

With the help of Android Docs, I was able to build the notification but not able to implement it in my app. Please guide me.

I used this code for notification in one of the activities in my app:

```<code>mBuilder =
  (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this)
  .setSmallIcon(R.drawable.bcm_logo)
  .setContentTitle("BCM")
  .setDefaults(Notification.DEFAULT_SOUND)
  .setContentText("You may have a new message")
  .setAutoCancel(true); // clear notification when clicked

mNotifyMgr =
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);

// As per my requirement, the users should get notified whenever the ListView gets updated. Where should I use this line in my Activity.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
</code>```

This is my Code for MainActivity:

```<code>public class MainActivity extends AppCompatActivity {

    ...

    // [Start of onCreate Method]
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...

        // Initialize message ListView and its adapter
        List<Message> messages = new ArrayList<>();
        mMessageAdapter = new MessageAdapter(this, R.layout.item_message_left_user, messages);
        mMessageListView.setAdapter(mMessageAdapter);

        ...

        // NOTIFICATIONS
        mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.bcm_logo)
                        .setContentTitle("BCM")
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setContentText("You may have a new message")
                        .setAutoCancel(true); // clear notification when clicked

        mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        mBuilder.setContentIntent(pi);

        //mNotifyMgr.notify(mNotificationId, mBuilder.build());

    }    // [End of onCreate Method]

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            if (resultCode == RESULT_OK) {
                Log.d(TAG, "User Signed in! "));

            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }

    // WHAT IF SIGNED IN
    private void onSignedInitialize(String userDisplayName) {
        mUserName = userDisplayName;
        Message.setSenderName(mUserName);
        attachDatabaseReadListener();
            ...
        });
    }

    // ATTACH AND DETACH THE DATABASE READ LISTENERS
    private void attachDatabaseReadListener() {
        if (childEventListener == null) {
            childEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Message message = dataSnapshot.getValue(Message.class);
                    mMessageAdapter.add(message);
                }

                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                public void onChildRemoved(DataSnapshot dataSnapshot) {
                }

                public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                }

                public void onCancelled(DatabaseError databaseError) {
                }
            };
            messagesDatabaseReference.addChildEventListener(childEventListener);
        }
    }

    private void detachDatabaseReadListener() {
        if (childEventListener != null) {
            messagesDatabaseReference.removeEventListener(childEventListener);
            childEventListener = null;
        }
    }

    ...

} // [END of Main Activity]
</code>```

答:
You can use the developer docs

void registerDataSetObserver (DataSetObserver observer)

Register an observer that is called when changes happen to the data used by this adapter.

Parameters
observer    DataSetObserver: the object that gets notified when the data set changes.
unregisterDataSetObserver

void unregisterDataSetObserver (DataSetObserver observer)

Unregister an observer that has previously been registered with this adapter via registerDataSetObserver(DataSetObserver).

Parameters
observer    DataSetObserver: the object to unregister.

Body:
I want to notify users with a notification whenever the ListView is updated. In my app, an admin posts messages and the users should be notified about that message. How can I do that?

With the help of Android Docs, I was able to build the notification but not able to implement it in my app. Please guide me.

I used this code for notification in one of the activities in my app:

mBuilder =
  (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this)
  .setSmallIcon(R.drawable.bcm_logo)
  .setContentTitle("BCM")
  .setDefaults(Notification.DEFAULT_SOUND)
  .setContentText("You may have a new message")
  .setAutoCancel(true); // clear notification when clicked

mNotifyMgr =
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
mBuilder.setContentIntent(pi);

// As per my requirement, the users should get notified whenever the ListView gets updated. Where should I use this line in my Activity.
mNotifyMgr.notify(mNotificationId, mBuilder.build());

This is my Code for MainActivity:

public class MainActivity extends AppCompatActivity {

    ...

    // [Start of onCreate Method]
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...

        // Initialize message ListView and its adapter
        List<Message> messages = new ArrayList<>();
        mMessageAdapter = new MessageAdapter(this, R.layout.item_message_left_user, messages);
        mMessageListView.setAdapter(mMessageAdapter);

        ...

        // NOTIFICATIONS
        mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.bcm_logo)
                        .setContentTitle("BCM")
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setContentText("You may have a new message")
                        .setAutoCancel(true); // clear notification when clicked

        mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        mBuilder.setContentIntent(pi);

        //mNotifyMgr.notify(mNotificationId, mBuilder.build());

    }    // [End of onCreate Method]

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            if (resultCode == RESULT_OK) {
                Log.d(TAG, "User Signed in! "));

            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }

    // WHAT IF SIGNED IN
    private void onSignedInitialize(String userDisplayName) {
        mUserName = userDisplayName;
        Message.setSenderName(mUserName);
        attachDatabaseReadListener();
            ...
        });
    }

    // ATTACH AND DETACH THE DATABASE READ LISTENERS
    private void attachDatabaseReadListener() {
        if (childEventListener == null) {
            childEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Message message = dataSnapshot.getValue(Message.class);
                    mMessageAdapter.add(message);
                }

                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                public void onChildRemoved(DataSnapshot dataSnapshot) {
                }

                public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                }

                public void onCancelled(DatabaseError databaseError) {
                }
            };
            messagesDatabaseReference.addChildEventListener(childEventListener);
        }
    }

    private void detachDatabaseReadListener() {
        if (childEventListener != null) {
            messagesDatabaseReference.removeEventListener(childEventListener);
            childEventListener = null;
        }
    }

    ...

} // [END of Main Activity]


问:
How to create two triangles with overlaying?
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.
</div>

<div class="shape">
  <div class="shape--1"></div>
  <div class="shape--2"></div>
</div>

<div class="content">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.
</div></code>```

答:
One posibility using an inner element to contain the image.

This element is rotated, and inside a pseudo there is the image, counter-rotated.

.test {
    font-size: 30px;
    width: 400px;
    height: 200px;
    border: solid blue 1px;
    background-size: 200px 200px;
    background-repeat: no-repeat;
    position: relative;
}

.inner {
    position: absolute;
    width: 140%;
    height: 140%;
    bottom: 0px;
    right: 0px;
    z-index: -1;
    transform: rotate(26.4deg);
    transform-origin: right bottom;
    overflow: hidden;
}

.inner:after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    background-image: url(http://lorempixel.com/800/400);
    background-size: cover;
    transform: rotate(-26.4deg);
    transform-origin: right bottom;

}

.triangle {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 0px;
    left: 0px;
    background-image: linear-gradient(to right bottom, red 50%, transparent 50%);
    z-index: -2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test">Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..
<div class="inner"></div>
<div class="triangle"></div>
</div></code>```

Body:
I need to create the following shape on the image. Where is the photo there will variable content as a slider. What I tried so far is create it with border-width, but the problem is that I'm not able to put the small triangle under photo because of the bigger triangle.

What I've done you can find here on live demo. Maybe I have to use other approaches? Does someone how to solve it?

    .header {
  float: left;
  width: 100%;
  background: red;
  padding-top: 50px;
  padding-bottom: 200px; }

  .content {
    float: left;
    width: 100%;
    background: blue;
    padding: 50px 0; }

    .shape {
      position: relative;
      float: left;
      width: 100%; }
      .shape--1:before {
        border-top-color: yellow;
        border-right-color: transparent;
        border-left-color: transparent;
        border-bottom-color: transparent;
        border-style: solid;
        border-width: 160px 330px 0 0;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 30; }
      .shape--2:before {
        background: transparent;
        border-bottom-color: transparent;
        border-left-color: blue;
        border-right-color: transparent;
        border-style: solid;
        border-top-color: transparent;
        border-width: 130px 0 0 100vw;
        content: " ";
        height: 0;
        position: absolute;
        top: -130px;
        width: 0;
        z-index: 20; }

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam accusamus, quis labore sapiente et ab at! Repudiandae commodi nam quod? - There will be slider with different background, same color should be also in the shape.

  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente eos maiores repellendus doloribus dignissimos iusto neque accusantium itaque. Aspernatur, cupiditate ab debitis placeat ad harum, nobis, iste deserunt impedit quaerat dicta nemo accusamus velit mollitia quis quos numquam labore distinctio eveniet. Consequatur culpa dicta harum quo quia similique, numquam tempore.

Body:
One posibility using an inner element to contain the image.

This element is rotated, and inside a pseudo there is the image, counter-rotated.

.test {
    font-size: 30px;
    width: 400px;
    height: 200px;
    border: solid blue 1px;
    background-size: 200px 200px;
    background-repeat: no-repeat;
    position: relative;
}

.inner {
    position: absolute;
    width: 140%;
    height: 140%;
    bottom: 0px;
    right: 0px;
    z-index: -1;
    transform: rotate(26.4deg);
    transform-origin: right bottom;
    overflow: hidden;
}

.inner:after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    background-image: url(http://lorempixel.com/800/400);
    background-size: cover;
    transform: rotate(-26.4deg);
    transform-origin: right bottom;

}

.triangle {
    position: absolute;
    width: 200px;
    height: 200px;
    top: 0px;
    left: 0px;
    background-image: linear-gradient(to right bottom, red 50%, transparent 50%);
    z-index: -2;
}

<div class="test">Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit..
<div class="inner"></div>
<div class="triangle"></div>
</div>


问:
Clearing the serial port's buffer
This is what my function looks like to open the serial port (using Ubuntu 12.04):

```<code>int open_port(void)
{
  int fd; /* File descriptor for the port */

  fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);

  if (fd == -1)
  {
   // Could not open the port.
   perror("open_port: Unable to open /dev/ttyUSB0 - ");
  }
  else
    fcntl(fd, F_SETFL, 0);

  struct termios options;

  tcgetattr(fd, &options);
  //setting baud rates and stuff
  cfsetispeed(&options, B19200);
  cfsetospeed(&options, B19200);
  options.c_cflag |= (CLOCAL | CREAD);
  tcsetattr(fd, TCSANOW, &options);

  tcsetattr(fd, TCSAFLUSH, &options);

  options.c_cflag &= ~PARENB;//next 4 lines setting 8N1
  options.c_cflag &= ~CSTOPB;
  options.c_cflag &= ~CSIZE;
  options.c_cflag |= CS8;

  //options.c_cflag &= ~CNEW_RTSCTS;

  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //raw input

  options.c_iflag &= ~(IXON | IXOFF | IXANY); //disable software flow control

  return (fd);
}
</code>```

What the problem is, is that when I run this program and if my serial device was already plugged in, the buffer has content in it. I need a way to clear the buffer before I start reading from it. I thought using tcsetattr(fd, TCSAFLUSH, &options); would fix this problem, by flushing the IO buffers before initializing the port, but no such luck. Any insight?

答:
I have been experiencing similar symptoms with an Arduino Uno board that resets on open(). I was receiving data after the open() call that was generated before the Arduino board had been reset and thus before open() had been called.

Tracking down the issue with ioctl() calls I learned that the data had simply not yet arrived in the input buffer by the time tcflush() was called. So the tcflush() did work but there was no data to flush. A sleep of 1000 us after the open() call seemed to solve the issue. This is becasue the delay allowed the data to arrive before tcflush() was called and therefore tcflush() did indeed flush the input buffer.

You might be experiencing the same issue.

Title: Clearing the serial port's buffer

Body:
This is what my function looks like to open the serial port (using Ubuntu 12.04):

int open_port(void)
{
  int fd; /* File descriptor for the port */

  fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);

  if (fd == -1)
  {
   // Could not open the port.
   perror("open_port: Unable to open /dev/ttyUSB0 - ");
  }
  else
    fcntl(fd, F_SETFL, 0);

  struct termios options;

  tcgetattr(fd, &options);
  //setting baud rates and stuff
  cfsetispeed(&options, B19200);
  cfsetospeed(&options, B19200);
  options.c_cflag |= (CLOCAL | CREAD);
  tcsetattr(fd, TCSANOW, &options);

  tcsetattr(fd, TCSAFLUSH, &options);

  options.c_cflag &= ~PARENB;//next 4 lines setting 8N1
  options.c_cflag &= ~CSTOPB;
  options.c_cflag &= ~CSIZE;
  options.c_cflag |= CS8;

  //options.c_cflag &= ~CNEW_RTSCTS;

  options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //raw input

  options.c_iflag &= ~(IXON | IXOFF | IXANY); //disable software flow control

  return (fd);
}

What the problem is, is that when I run this program and if my serial device was already plugged in, the buffer has content in it. I need a way to clear the buffer before I start reading from it. I thought using tcsetattr(fd, TCSAFLUSH, &options); would fix this problem, by flushing the IO buffers before initializing the port, but no such luck. Any insight?


问:
how to open popup within popup in magnific popup plugin
can anybody tell me how to open popup within popup using magnific-popup jquery plugin (using ajax).

```<code>$('.ajax-popup-link').magnificPopup({
  type: 'ajax'
});
<a href="path-to-file.html" class="ajax-popup-link"> Link 1 </a>
</code>```

on "path-to-file.html"

```<code><a href="path-to-other-file.html" class="ajax-popup-link"> next popup </a>
</code>```

Thanks

答:
I know this an old thread, but for anyone still interested, this worked for me:

```<code>$(document).on('click', '.sAjax', function(e){

        $.magnificPopup.close(); // Close existing popup

        // Open new popup
        $.magnificPopup.open({
          items: {
                src: 'new-page.html',
                type: 'ajax'
          }
        });

        e.preventDefault();

});
</code>```

Don't forget to give your link the new class of .sAjax

Body:
can anybody tell me how to open popup within popup using magnific-popup jquery plugin (using ajax).

$('.ajax-popup-link').magnificPopup({
  type: 'ajax'
});
 Link 1

on "path-to-file.html"

 next popup

Thanks

Body:
I know this an old thread, but for anyone still interested, this worked for me:

$(document).on('click', '.sAjax', function(e){

        $.magnificPopup.close(); // Close existing popup

        // Open new popup
        $.magnificPopup.open({
          items: {
                src: 'new-page.html',
                type: 'ajax'
          }
        });

        e.preventDefault();

});

Don't forget to give your link the new class of .sAjax


问:
Codeigniter : Batch Insert Array into DB
I am having multi file upload in my codeigniter. I need to store the following values inside the database. I having the file_name as an array of 0,1,2 and so on(the maximum value depends upon the user's action), folder_id, created as fixed values.

For every file_name(0,1,2....), the folder_id & created, has to be inserted in the table

```<code>array (size=4)
  'file_name' =>
    array (size=3)
      0 => string '1.jpg' (length=5)
      1 => string '2.jpg' (length=5)
      2 => string '10_deepak.jpg' (length=13)
  'folder_id' => string '5' (length=1)
  'created' => string '2017-07-03 23:42:42' (length=19)
</code>```

So Far, I have tried with the following;

```<code>$data = array(
             'file_name' => $data['file_name'] ,
             'created' => $data['created'] ,
             'folder_id' => $data['folder_id']
                );
         $this->db->insert('ins_files', $data);
</code>```

For when i tried , I also got Array to String Conversion error too.

答:
Based on your code. Here is the straightforward approach you can use like this.</p>

```<code>$array = array(
    'file_name' => array(
      '1.jpg',
      '2.jpg',
      '10_deepak.jpg',
    ),
    'folder_id' => 5,
    'created' => '2017-07-03 23:42:42'
);
// encode the files name in Json array better
// approach other you can also implode them to store

$data = array(
   'file_name' => json_encode($array['file_name']),
   'folder_id' => $array['folder_id'],
   'created' => $array['created'],
);
// Verify the data array
// echo '```'; print_r($data);
$this->db->insert('ins_files', $data);
</code>```

Body:
I am having multi file upload in my codeigniter. I need to store the following values inside the database. I having the file_name as an array of 0,1,2 and so on(the maximum value depends upon the user's action), folder_id, created as fixed values.

For every file_name(0,1,2....), the folder_id & created, has to be inserted in the table

array (size=4)
  'file_name' =>
    array (size=3)
      0 => string '1.jpg' (length=5)
      1 => string '2.jpg' (length=5)
      2 => string '10_deepak.jpg' (length=13)
  'folder_id' => string '5' (length=1)
  'created' => string '2017-07-03 23:42:42' (length=19)

So Far, I have tried with the following;

$data = array(
             'file_name' => $data['file_name'] ,
             'created' => $data['created'] ,
             'folder_id' => $data['folder_id']
                );
         $this->db->insert('ins_files', $data);

For when i tried , I also got Array to String Conversion error too.

Body:
Based on your code. Here is the straightforward approach you can use like this.

$array = array(
    'file_name' => array(
      '1.jpg',
      '2.jpg',
      '10_deepak.jpg',
    ),
    'folder_id' => 5,
    'created' => '2017-07-03 23:42:42'
);
// encode the files name in Json array better
// approach other you can also implode them to store

$data = array(
   'file_name' => json_encode($array['file_name']),
   'folder_id' => $array['folder_id'],
   'created' => $array['created'],
);
// Verify the data array
// echo '<pre>'; print_r($data);
$this->db->insert('ins_files', $data);


问:
Django redirect views with parameter/context
I have register view in my django app, that redirects to the homepage:

```<code>def register(request):
   ...register...
   return redirect("/")

def homepage(request):
    users = User.objects.all().order_by('username')
    return render(request, 'index.html', {'users': users})
</code>```

I want to add variable new_user that would tell the homepage if user is new. I would pass variable from register view to the homepage view and than into the template where i would handle it:

```<code>{% if new_user %}
<h1>Welcome</h1>
{% endif %}
</code>```

But i dont know how to pass this variable from register view to homepage and than into the template.
Help is well appreciated!

答:
A simple way to achieve that would be to set a parameter in query:    </p>

```<code>def register(request):
   ...register...
   return redirect('/?new')

def homepage(request):
    is_new_user = 'new' in request.GET
    ....
</code>```

Body:
I have register view in my django app, that redirects to the homepage:

def register(request):
   ...register...
   return redirect("/")

def homepage(request):
    users = User.objects.all().order_by('username')
    return render(request, 'index.html', {'users': users})

I want to add variable new_user that would tell the homepage if user is new. I would pass variable from register view to the homepage view and than into the template where i would handle it:

{% if new_user %}

Welcome

{% endif %}

But i dont know how to pass this variable from register view to homepage and than into the template.
Help is well appreciated!

Body:
A simple way to achieve that would be to set a parameter in query:

def register(request):
   ...register...
   return redirect('/?new')

def homepage(request):
    is_new_user = 'new' in request.GET
    ....


问:
Selenium - Failed to Start Browser Session - Access Denied - XP
I'm getting the following error when starting up Selenium on XP

```<code>java.lang.RuntimeException:
Could not start Selenium session: Failed to start new browser session:
java.lang.RuntimeException: java.io.FileNotFoundException:
C:\Program Files\Mozilla Firefox (Access is denied)
</code>```

Any thoughts?

答: Are you starting Firefox with the actual path to the Firefox browser? If you set Chrome as the target browser you should be able to avoid this.</p>

Body:
I'm getting the following error when starting up Selenium on XP

java.lang.RuntimeException:
Could not start Selenium session: Failed to start new browser session:
java.lang.RuntimeException: java.io.FileNotFoundException:
C:\Program Files\Mozilla Firefox (Access is denied)

Any thoughts?


问:
What is the specific reason for the runtime error I'm getting here?
```<code>#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}
</code>```

What is the specific reason for the runtime error I'm getting here?

答:
To solve this issue you should simply consider to use strings (arrays of chars) to contain the different names.

Here is an example how to do that:

```<code>    void main()
{
// The string "a" can contain up to 100 symbols (chars).
char a[100];

printf("Enter an alien name:\n");

scanf("%s",a);

printf("The alien name is %s.", a);

}
</code>```

The difference between "char a" and "char a[100]" is that in the first case the variable "a" corresponds to a single character and in the second it corresponds to a string - an array of chars which can contain up to 100 characters.

Body:
#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}

What is the specific reason for the runtime error I'm getting here?

Body:
To solve this issue you should simply consider to use strings (arrays of chars) to contain the different names.

Here is an example how to do that:

    void main()
{
// The string "a" can contain up to 100 symbols (chars).
char a[100];

printf("Enter an alien name:\n");

scanf("%s",a);

printf("The alien name is %s.", a);

}

The difference between "char a" and "char a[100]" is that in the first case the variable "a" corresponds to a single character and in the second it corresponds to a string - an array of chars which can contain up to 100 characters.


问:
how can i parse a url json code to delete items an a listview
i need some help  please... In my popup menu i have a delete option to delete items in a listview

how can i parse this url json to delete the items in the listview

this is the result of my  list view

```<code>    @Override
    protected void onPostExecute(String result) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        super.onPostExecute(result);

        codigo.setText(recode);
        nombre.setText(reNombre);
        nroComprobante.setText(reNumero);

        final ListAdapter adapter = new SimpleAdapter(Compra.this, prod,
                R.layout.item_carrito, new String[]{"renglon", "codigo", "descrip", "precio"},
                new int[]{R.id.tvreglon, R.id.tvcode, R.id.tvdescrip, R.id.tvprec});
        lista_eligida.setAdapter(adapter);
        Log.d("ADAP", String.valueOf(adapter));
        registerForContextMenu(lista_eligida);

    }

}
</code>```

and this is my popup menu code...

```<code>  public boolean onContextItemSelected(final MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int id = info.position;
    switch (item.getItemId()) {
        case R.id.del:
            String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";
</code>```

// what can i do??... should i parse the new json again.?..
//i just want to delete a item when i clicked on delete option on my popup menu thank you

答:
this is how a did it</p>

```<code>      String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";
            HttpHandler she = new HttpHandler();
            JSONObject jsonStr = she.makeServiceCall(url);

            try {
                JSONObject    jsonObj = new JSONObject((Map) jsonStr);
                JSONArray contacts = jsonObj.getJSONArray("PRR");
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String codig = c.getString("codigo");
                    String des = c.getString("descrip");
                    String prec = c.getString("precio");
                    String reglon = c.getString("renglon");

                    Log.d("REGLON", String.valueOf(reglon));

                    HashMap<String, String> contacto = new HashMap<>();
                    contacto.put("codigo", codig);
                    contacto.put("descrip", des);
                    contacto.put("precio", prec);
                    contacto.put("renglon", reglon);
                    reg = "" + reglon;
                    prod.add(contacto);
</code>```

Body:
i need some help  please... In my popup menu i have a delete option to delete items in a listview

how can i parse this url json to delete the items in the listview

this is the result of my  list view

    @Override
    protected void onPostExecute(String result) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        super.onPostExecute(result);

        codigo.setText(recode);
        nombre.setText(reNombre);
        nroComprobante.setText(reNumero);

        final ListAdapter adapter = new SimpleAdapter(Compra.this, prod,
                R.layout.item_carrito, new String[]{"renglon", "codigo", "descrip", "precio"},
                new int[]{R.id.tvreglon, R.id.tvcode, R.id.tvdescrip, R.id.tvprec});
        lista_eligida.setAdapter(adapter);
        Log.d("ADAP", String.valueOf(adapter));
        registerForContextMenu(lista_eligida);

    }

}

and this is my popup menu code...

  public boolean onContextItemSelected(final MenuItem item) {

    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int id = info.position;
    switch (item.getItemId()) {
        case R.id.del:
            String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";

// what can i do??... should i parse the new json again.?..
//i just want to delete a item when i clicked on delete option on my popup menu thank you

Body:
this is how a did it

      String url = "http://www.air-intra.com/apps/air-app/agregar.php?token=" + Token_Recibido + "&codiart=" + codigo + "&oper=Q&renglon=" + reglo + "";
            HttpHandler she = new HttpHandler();
            JSONObject jsonStr = she.makeServiceCall(url);

            try {
                JSONObject    jsonObj = new JSONObject((Map) jsonStr);
                JSONArray contacts = jsonObj.getJSONArray("PRR");
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String codig = c.getString("codigo");
                    String des = c.getString("descrip");
                    String prec = c.getString("precio");
                    String reglon = c.getString("renglon");

                    Log.d("REGLON", String.valueOf(reglon));

                    HashMap<String, String> contacto = new HashMap<>();
                    contacto.put("codigo", codig);
                    contacto.put("descrip", des);
                    contacto.put("precio", prec);
                    contacto.put("renglon", reglon);
                    reg = "" + reglon;
                    prod.add(contacto);


问:
Android ProgressDialog thread
How to show ProgressDialog in separate UI thread?

I have the following code:

```<code>public boolean myMethod() {

  // show here ProgressDialog in thread

  // long operation, MUST BE NOT in thread, as there's a return value...

  return value;
}
</code>```

Using Handler, Thread, AsyncTask didn't help...

Is there any way to run ProgressDialog in separate thread and main (long) operation in main thread?

Thanks,

答:
There is only one UI thread. You should never run anything heavy in it. I'm afraid you have to run that in the background and the progress bar in the UI thread.

You might have to do a bit redesigning to achieve that. You can use callbacks to get rid of the return values.

Title: Android ProgressDialog thread

Body:
How to show ProgressDialog in separate UI thread?

I have the following code:

public boolean myMethod() {

  // show here ProgressDialog in thread

  // long operation, MUST BE NOT in thread, as there's a return value...

  return value;
}

Using Handler, Thread, AsyncTask didn't help...

Is there any way to run ProgressDialog in separate thread and main (long) operation in main thread?

Thanks,