问:
Showing Form Entry on Modal Window Bootstrap / jQuery
I'm creating a form confirmation window with Bootstrap Modal before user submission.

Here is the html part:

```<code><form role="form">
    <div class="form-group">
      <label for="Company" class="col-sm-3 control-label">Company:</label>
      <div class="col-sm-9">
        <input type="text" name="Company" id="Company" size="50" maxlength="100" class="form-control" placeholder="Companyt">
      </div>
    </div>

    <div class="form-group">
      <label for="Department" class="col-sm-3 control-label">Department:</label>
      <div class="col-sm-9">
        <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control" placeholder="Department">
      </div>
    </div>

    <div class="form-group">
      <label for="Username" class="col-sm-3 control-label">Name:</label>
      <div class="col-sm-9">
        <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control" placeholder="Username">
      </div>
    </div>

    <div class="form-group">
      <label for="Address" class="col-sm-3 control-label">Address:</label>
      <div class="col-sm-9">
        <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">
      </div>
    </div>

    <div class="form-group">
      <label for="TEL" class="col-sm-3 control-label">TEL:</label>
      <div class="col-sm-9">
        <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control" placeholder="TEL">
      </div>
    </div>

    <div class="form-group">
      <label for="Email" class="col-sm-3 control-label">Email:</label>
      <div class="col-sm-9">
        <input type="text" name="Email" id="Email" size="50" maxlength="100" class="form-control" placeholder="Email">
      </div>
    </div>
    <input type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">
  </form>
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title" id="myModalLabel">Confirm your entry</h4>
        </div>
        <div class="modal-body">
          <div class="row">
          <div class="entryname col-xs-3 ">Company:</div>
          <div class="entrydata col-xs-9" id="mCompany"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Department:</div>
          <div class="entrydata col-xs-9" id="mDepartment"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Name:</div>
          <div class="entrydata col-xs-9" id="mUsername"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Address:</div>
          <div class="entrydata col-xs-9" id="mAddress"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">TEL:</div>
          <div class="entrydata col-xs-9" id="mTel"></div>
          </div>
          <div class="row">
          <div class="entryname col-xs-3">Email:</div>
          <div class="entrydata col-xs-9" id="mEmail"></div>
          </div>
          <div class="clearfix"></div>
        </div>
        <div class="modal-footer">
          <div class="col-xs-6"><button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button></div>
          <div class="col-xs-6"><button class="btn btn-block btn-primary">Submit</button></div>
        </div>
      </div>
    </div>
  </div>
</code>```

And here is the jQuery part:

```<code>$('#submitBtn').click(function() {
  $('#mCompany').text($('#Company').val());
  $('#mDepartment').text($('#Department').val());
  $('#mUsername').text($('#Username').val());
  $('#mAddress').text($('#Address').val());
  $('#mTEL').text($('#TEL').val());
  $('#mEmail').text($('#Email').val());
});
</code>```

You can see and try with this
link to JSFiddle.

Not all fields are required, and what I want to do is to show only the entry with data.

For example in the below image, I don't want the red bordered part to show up.

Example Screen Shot

The sample on JSFiddle has only 6 fields but my form has over 30 fields. I'm wondering if there's a way to show only the fields with data.

答:
I make some improvents:

    var all = "";
    $('#submitBtn').click(function () {
    /* when the button in the form,
    display the entered values in the modal */
    //console.log($("from input"));
    all = "";
    $.each($("form input"),function(i,v){
    var id= $(this).attr('id');
     //console.log(id);
      //console.log("#m"+id);
     $("#m"+id).text($(this).val());
      all = all + $(this).val();
    });
    hideEmptyInputs();
  });
  $('#myModal').on('show.bs.modal', function (e) {
          if(all == ""){
           e.preventDefault();
          }
    })

  function hideEmptyInputs(){
   //console.log($("#myModal div"));
   //console.log($("#myModal div[id^=m]"));
    $.each($("#myModal div[id^=m]"),function(i,v){
     //console.log($(this).text());
      var value = $(this).text();
      if(value == ""){
       //Hide if empty
        $(this).parent().css('display','none');
      }else{
        $(this).parent().css('display','block');
      }
    });
   //console.log("algo");
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<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"></script>
<form role="form">
        <div class="form-group">
          <label for="Company" class="col-sm-3 control-label">Company:</label>
          <div class="col-sm-9">
            <input type="text" name="Company" id="Company" size="50" maxlength="100" class="form-control" placeholder="Companyt">
          </div>
        </div>

        <div class="form-group">
          <label for="Department" class="col-sm-3 control-label">Department:</label>
          <div class="col-sm-9">
            <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control" placeholder="Department">
          </div>
        </div>

        <div class="form-group">
          <label for="Username" class="col-sm-3 control-label">Name:</label>
          <div class="col-sm-9">
            <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control" placeholder="Username">
          </div>
        </div>

        <div class="form-group">
          <label for="Address" class="col-sm-3 control-label">Address:</label>
          <div class="col-sm-9">
            <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">
          </div>
        </div>

        <div class="form-group">
          <label for="TEL" class="col-sm-3 control-label">TEL:</label>
          <div class="col-sm-9">
            <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control" placeholder="TEL">
          </div>
        </div>
        <button type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">Submit</button>
</form>
<!-- ########## Start Modal Section ########## -->
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
              <h4 class="modal-title" id="myModalLabel">Confirm your entry</h4>
            </div>
            <div class="modal-body">
              <div class="row">
              <div class="entryname col-xs-3 ">Company:</div>
              <div class="entrydata col-xs-9" id="mCompany"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Department:</div>
              <div class="entrydata col-xs-9" id="mDepartment"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Name:</div>
              <div class="entrydata col-xs-9" id="mUsername"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Address:</div>
              <div class="entrydata col-xs-9" id="mAddress"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">TEL:</div>
              <div class="entrydata col-xs-9" id="mTEL"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Email:</div>
              <div class="entrydata col-xs-9" id="mEmail"></div>
              </div>
              <div class="clearfix"></div>
            </div>
            <div class="modal-footer">
              <div class="col-xs-6"><button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button></div>
              <div class="col-xs-6"><button class="btn btn-block btn-primary">Submit</button></div>
            </div>
          </div>
        </div>
      </div>
      <!-- ########## End Modal Section ########## --></code>```

You can add some classes to know what field did you want to show in the modal and what not to show....  I think could be add dynamical to the modal too...

Add inputs dynamical:

    var all = "";
    $('#submitBtn').click(function () {
    /* when the button in the form,
    display the entered values in the modal */
    //console.log($("from input"));
    all = "";

      $("#modalBody").html('');
    $.each($("form input"),function(i,v){
    var id= $(this).attr('id');
    if($(this).hasClass('add')){
      all = all + $(this).val();
      var input = '
'
      + '
' + id + ':
'
      + '
' + $(this).val(); + '
'
      + '
';

      //console.log(input);

      $("#modalBody").append(input);

    }
     //console.log(id);
      //console.log("#m"+id);
     //$("#m"+id).text($(this).val());
     // all = all + $(this).val();
    });
    hideEmptyInputs();
  });
  $('#myModal').on('show.bs.modal', function (e) {
          if(all == ""){
           e.preventDefault();
          }
    })

  function hideEmptyInputs(){
   //console.log($("#myModal div"));
   //console.log($("#myModal div[id^=m]"));
    $.each($("#myModal div[id^=m]"),function(i,v){
     //console.log($(this).text());
      var value = $(this).text();
      if(value == ""){
       //Hide if empty
        $(this).parent().css('display','none');
      }else{
        $(this).parent().css('display','block');
      }
    });
   //console.log("algo");
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<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"></script>
<form role="form">
        <div class="form-group">
          <label for="Company" class="col-sm-3 control-label">Company:</label>
          <div class="col-sm-9">
            <input type="text"  name="Company" id="Company" size="50" maxlength="100" class="form-control add" placeholder="Companyt">
          </div>
        </div>

        <div class="form-group">
          <label for="Department" class="col-sm-3 control-label">Department:</label>
          <div class="col-sm-9">
            <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control add" placeholder="Department">
          </div>
        </div>

        <div class="form-group">
          <label for="Username" class="col-sm-3 control-label">Name:</label>
          <div class="col-sm-9">
            <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control add" placeholder="Username">
          </div>
        </div>

        <div class="form-group">
          <label for="Address" class="col-sm-3 control-label">Address:</label>
          <div class="col-sm-9">
            <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">
          </div>
        </div>

        <div class="form-group">
          <label for="TEL" class="col-sm-3 control-label">TEL:</label>
          <div class="col-sm-9">
            <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control add" placeholder="TEL">
          </div>
        </div>
        <button type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">Submit</button>
</form>
<!-- ########## Start Modal Section ########## -->
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
              <h4 class="modal-title" id="myModalLabel">Confirm your entry</h4>
            </div>
            <div class="modal-body">
            <div id="modalBody"></div>
              <div class="clearfix"></div>
            </div>
            <div class="modal-footer">
              <div class="col-xs-6"><button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button></div>
              <div class="col-xs-6"><button class="btn btn-block btn-primary">Submit</button></div>
            </div>
          </div>
        </div>
      </div>
      <!-- ########## End Modal Section ########## --></code>```

Body:
I'm creating a form confirmation window with Bootstrap Modal before user submission.

Here is the html part:

<form role="form">

      Company:

        <input type="text" name="Company" id="Company" size="50" maxlength="100" class="form-control" placeholder="Companyt">

      Department:

        <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control" placeholder="Department">

      Name:

        <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control" placeholder="Username">

      Address:

        <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">

      TEL:

        <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control" placeholder="TEL">

      Email:

        <input type="text" name="Email" id="Email" size="50" maxlength="100" class="form-control" placeholder="Email">

    <input type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">
  </form>

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Confirm your entry

Company:

Department:

Name:

Address:

TEL:

Email:

<button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button>

<button class="btn btn-block btn-primary">Submit</button>

And here is the jQuery part:

$('#submitBtn').click(function() {
  $('#mCompany').text($('#Company').val());
  $('#mDepartment').text($('#Department').val());
  $('#mUsername').text($('#Username').val());
  $('#mAddress').text($('#Address').val());
  $('#mTEL').text($('#TEL').val());
  $('#mEmail').text($('#Email').val());
});

You can see and try with this
link to JSFiddle.

Not all fields are required, and what I want to do is to show only the entry with data.

For example in the below image, I don't want the red bordered part to show up.

Example Screen Shot

The sample on JSFiddle has only 6 fields but my form has over 30 fields. I'm wondering if there's a way to show only the fields with data.

Body:
I make some improvents:

    var all = "";
    $('#submitBtn').click(function () {
    /* when the button in the form,
    display the entered values in the modal */
    //console.log($("from input"));
    all = "";
    $.each($("form input"),function(i,v){
    var id= $(this).attr('id');
     //console.log(id);
      //console.log("#m"+id);
     $("#m"+id).text($(this).val());
      all = all + $(this).val();
    });
    hideEmptyInputs();
  });
  $('#myModal').on('show.bs.modal', function (e) {
          if(all == ""){
           e.preventDefault();
          }
    })

  function hideEmptyInputs(){
   //console.log($("#myModal div"));
   //console.log($("#myModal div[id^=m]"));
    $.each($("#myModal div[id^=m]"),function(i,v){
     //console.log($(this).text());
      var value = $(this).text();
      if(value == ""){
       //Hide if empty
        $(this).parent().css('display','none');
      }else{
        $(this).parent().css('display','block');
      }
    });
   //console.log("algo");
  }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<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"></script>
<form role="form">
        <div class="form-group">
          <label for="Company" class="col-sm-3 control-label">Company:</label>
          <div class="col-sm-9">
            <input type="text" name="Company" id="Company" size="50" maxlength="100" class="form-control" placeholder="Companyt">
          </div>
        </div>

        <div class="form-group">
          <label for="Department" class="col-sm-3 control-label">Department:</label>
          <div class="col-sm-9">
            <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control" placeholder="Department">
          </div>
        </div>

        <div class="form-group">
          <label for="Username" class="col-sm-3 control-label">Name:</label>
          <div class="col-sm-9">
            <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control" placeholder="Username">
          </div>
        </div>

        <div class="form-group">
          <label for="Address" class="col-sm-3 control-label">Address:</label>
          <div class="col-sm-9">
            <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">
          </div>
        </div>

        <div class="form-group">
          <label for="TEL" class="col-sm-3 control-label">TEL:</label>
          <div class="col-sm-9">
            <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control" placeholder="TEL">
          </div>
        </div>
        <button type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">Submit</button>
</form>
<!-- ########## Start Modal Section ########## -->
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">Confirm your entry</h4>
            </div>
            <div class="modal-body">
              <div class="row">
              <div class="entryname col-xs-3 ">Company:</div>
              <div class="entrydata col-xs-9" id="mCompany"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Department:</div>
              <div class="entrydata col-xs-9" id="mDepartment"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Name:</div>
              <div class="entrydata col-xs-9" id="mUsername"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Address:</div>
              <div class="entrydata col-xs-9" id="mAddress"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">TEL:</div>
              <div class="entrydata col-xs-9" id="mTEL"></div>
              </div>
              <div class="row">
              <div class="entryname col-xs-3">Email:</div>
              <div class="entrydata col-xs-9" id="mEmail"></div>
              </div>
              <div class="clearfix"></div>
            </div>
            <div class="modal-footer">
              <div class="col-xs-6"><button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button></div>
              <div class="col-xs-6"><button class="btn btn-block btn-primary">Submit</button></div>
            </div>
          </div>
        </div>
      </div>
      <!-- ########## End Modal Section ########## -->

You can add some classes to know what field did you want to show in the modal and what not to show....  I think could be add dynamical to the modal too...

Add inputs dynamical:

    var all = "";
    $('#submitBtn').click(function () {
    /* when the button in the form,
    display the entered values in the modal */
    //console.log($("from input"));
    all = "";

      $("#modalBody").html('');
    $.each($("form input"),function(i,v){
    var id= $(this).attr('id');
    if($(this).hasClass('add')){
      all = all + $(this).val();
      var input = '<div class="row">'
      + '<div class="entryname col-xs-3">' + id + ':</div>'
      + '<div class="entrydata col-xs-9" id="m' + id +'">' + $(this).val(); + '</div>'
      + '        </div>';

      //console.log(input);

      $("#modalBody").append(input);

    }
     //console.log(id);
      //console.log("#m"+id);
     //$("#m"+id).text($(this).val());
     // all = all + $(this).val();
    });
    hideEmptyInputs();
  });
  $('#myModal').on('show.bs.modal', function (e) {
          if(all == ""){
           e.preventDefault();
          }
    })

  function hideEmptyInputs(){
   //console.log($("#myModal div"));
   //console.log($("#myModal div[id^=m]"));
    $.each($("#myModal div[id^=m]"),function(i,v){
     //console.log($(this).text());
      var value = $(this).text();
      if(value == ""){
       //Hide if empty
        $(this).parent().css('display','none');
      }else{
        $(this).parent().css('display','block');
      }
    });
   //console.log("algo");
  }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<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"></script>
<form role="form">
        <div class="form-group">
          <label for="Company" class="col-sm-3 control-label">Company:</label>
          <div class="col-sm-9">
            <input type="text"  name="Company" id="Company" size="50" maxlength="100" class="form-control add" placeholder="Companyt">
          </div>
        </div>

        <div class="form-group">
          <label for="Department" class="col-sm-3 control-label">Department:</label>
          <div class="col-sm-9">
            <input type="text" name="Department" id="Department" size="50" maxlength="100" class="form-control add" placeholder="Department">
          </div>
        </div>

        <div class="form-group">
          <label for="Username" class="col-sm-3 control-label">Name:</label>
          <div class="col-sm-9">
            <input type="text" name="Username" id="Username" size="50" maxlength="100" class="form-control add" placeholder="Username">
          </div>
        </div>

        <div class="form-group">
          <label for="Address" class="col-sm-3 control-label">Address:</label>
          <div class="col-sm-9">
            <input type="text" name="Address" id="Address" size="50" maxlength="100" class="form-control" placeholder="Address">
          </div>
        </div>

        <div class="form-group">
          <label for="TEL" class="col-sm-3 control-label">TEL:</label>
          <div class="col-sm-9">
            <input type="text" name="TEL" id="TEL" size="50" maxlength="100" class="form-control add" placeholder="TEL">
          </div>
        </div>
        <button type="button" class="btn btn-primary btn-block enduserinfobtn" id="submitBtn" data-toggle="modal" data-target="#myModal" value="Submit">Submit</button>
</form>
<!-- ########## Start Modal Section ########## -->
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">Confirm your entry</h4>
            </div>
            <div class="modal-body">
            <div id="modalBody"></div>
              <div class="clearfix"></div>
            </div>
            <div class="modal-footer">
              <div class="col-xs-6"><button class="btn btn-block btn-default" data-dismiss="modal">Cancel</button></div>
              <div class="col-xs-6"><button class="btn btn-block btn-primary">Submit</button></div>
            </div>
          </div>
        </div>
      </div>
      <!-- ########## End Modal Section ########## -->


来源: stackexchange

问:
Programmatically collapse a group in ExpandableListView
When I expand a new group, can I collapse the last one expanded?</p>

答:
Try putting this in your ExpandableListAdapter, listView is a reference to the ExpandableListView itself. And lastExpandedGroupPosition is a integer member variable defined inside your ExpandableListAdapter.

```<code>    @Override
    public void onGroupExpanded(int groupPosition){
        //collapse the old expanded group, if not the same
        //as new group to expand
        if(groupPosition != lastExpandedGroupPosition){
            listView.collapseGroup(lastExpandedGroupPosition);
        }

        super.onGroupExpanded(groupPosition);
        lastExpandedGroupPosition = groupPosition;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try putting this in your ExpandableListAdapter, listView is a reference to the ExpandableListView itself. And lastExpandedGroupPosition is a integer member variable defined inside your ExpandableListAdapter.

    @Override
    public void onGroupExpanded(int groupPosition){
        //collapse the old expanded group, if not the same
        //as new group to expand
        if(groupPosition != lastExpandedGroupPosition){
            listView.collapseGroup(lastExpandedGroupPosition);
        }

        super.onGroupExpanded(groupPosition);
        lastExpandedGroupPosition = groupPosition;
    }


Title: Find the highest and lowest value locations within an interval on a column?

Body:
Given this pandas dataframe with two columns, 'Values' and 'Intervals'. How do I get a third column 'MinMax' indicating whether the value is a maximum or a minimum within that interval? The challenge for me is that the interval length and the distance between intervals are not fixed, therefore I post the question.

import pandas as pd
import numpy as np

data = pd.DataFrame([
        [1879.289,np.nan],[1879.281,np.nan],[1879.292,1],[1879.295,1],[1879.481,1],[1879.294,1],[1879.268,1],
        [1879.293,1],[1879.277,1],[1879.285,1],[1879.464,1],[1879.475,1],[1879.971,1],[1879.779,1],
        [1879.986,1],[1880.791,1],[1880.29,1],[1879.253,np.nan],[1878.268,np.nan],[1875.73,1],[1876.792,1],
        [1875.977,1],[1876.408,1],[1877.159,1],[1877.187,1],[1883.164,1],[1883.171,1],[1883.495,1],
        [1883.962,1],[1885.158,1],[1885.974,1],[1886.479,np.nan],[1885.969,np.nan],[1884.693,1],[1884.977,1],
        [1884.967,1],[1884.691,1],[1886.171,1],[1886.166,np.nan],[1884.476,np.nan],[1884.66,1],[1882.962,1],
        [1881.496,1],[1871.163,1],[1874.985,1],[1874.979,1],[1871.173,np.nan],[1871.973,np.nan],[1871.682,np.nan],
        [1872.476,np.nan],[1882.361,1],[1880.869,1],[1882.165,1],[1881.857,1],[1880.375,1],[1880.66,1],
        [1880.891,1],[1880.377,1],[1881.663,1],[1881.66,1],[1877.888,1],[1875.69,1],[1875.161,1],
        [1876.697,np.nan],[1876.671,np.nan],[1879.666,np.nan],[1877.182,np.nan],[1878.898,1],[1878.668,1],[1878.871,1],
        [1878.882,1],[1879.173,1],[1878.887,1],[1878.68,1],[1878.872,1],[1878.677,1],[1877.877,1],
        [1877.669,1],[1877.69,1],[1877.684,1],[1877.68,1],[1877.885,1],[1877.863,1],[1877.674,1],
        [1877.676,1],[1877.687,1],[1878.367,1],[1878.179,1],[1877.696,1],[1877.665,1],[1877.667,np.nan],
        [1878.678,np.nan],[1878.661,1],[1878.171,1],[1877.371,1],[1877.359,1],[1878.381,1],[1875.185,1],
        [1875.367,np.nan],[1865.492,np.nan],[1865.495,1],[1866.995,1],[1866.672,1],[1867.465,1],[1867.663,1],
        [1867.186,1],[1867.687,1],[1867.459,1],[1867.168,1],[1869.689,1],[1869.693,1],[1871.676,1],
        [1873.174,1],[1873.691,np.nan],[1873.685,np.nan]
    ])

In the third column below you can see where the max and min is for each interval.

+-------+----------+-----------+---------+
| index |  Value   | Intervals | Min/Max |
+-------+----------+-----------+---------+
|     0 | 1879.289 | np.nan    |         |
|     1 | 1879.281 | np.nan    |         |
|     2 | 1879.292 | 1         |         |
|     3 | 1879.295 | 1         |         |
|     4 | 1879.481 | 1         |         |
|     5 | 1879.294 | 1         |         |
|     6 | 1879.268 | 1         | min     |
|     7 | 1879.293 | 1         |         |
|     8 | 1879.277 | 1         |         |
|     9 | 1879.285 | 1         |         |
|    10 | 1879.464 | 1         |         |
|    11 | 1879.475 | 1         |         |
|    12 | 1879.971 | 1         |         |
|    13 | 1879.779 | 1         |         |
|    17 | 1879.986 | 1         |         |
|    18 | 1880.791 | 1         | max     |
|    19 |  1880.29 | 1         |         |
|    55 | 1879.253 | np.nan    |         |
|    56 | 1878.268 | np.nan    |         |
|    57 |  1875.73 | 1         |         |
|    58 | 1876.792 | 1         |         |
|    59 | 1875.977 | 1         | min     |
|    60 | 1876.408 | 1         |         |
|    61 | 1877.159 | 1         |         |
|    62 | 1877.187 | 1         |         |
|    63 | 1883.164 | 1         |         |
|    64 | 1883.171 | 1         |         |
|    65 | 1883.495 | 1         |         |
|    66 | 1883.962 | 1         |         |
|    67 | 1885.158 | 1         |         |
|    68 | 1885.974 | 1         | max     |
|    69 | 1886.479 | np.nan    |         |
|    70 | 1885.969 | np.nan    |         |
|    71 | 1884.693 | 1         |         |
|    72 | 1884.977 | 1         |         |
|    73 | 1884.967 | 1         |         |
|    74 | 1884.691 | 1         | min     |
|    75 | 1886.171 | 1         | max     |
|    76 | 1886.166 | np.nan    |         |
|    77 | 1884.476 | np.nan    |         |
|    78 |  1884.66 | 1         | max     |
|    79 | 1882.962 | 1         |         |
|    80 | 1881.496 | 1         |         |
|    81 | 1871.163 | 1         | min     |
|    82 | 1874.985 | 1         |         |
|    83 | 1874.979 | 1         |         |
|    84 | 1871.173 | np.nan    |         |
|    85 | 1871.973 | np.nan    |         |
|    86 | 1871.682 | np.nan    |         |
|    87 | 1872.476 | np.nan    |         |
|    88 | 1882.361 | 1         | max     |
|    89 | 1880.869 | 1         |         |
|    90 | 1882.165 | 1         |         |
|    91 | 1881.857 | 1         |         |
|    92 | 1880.375 | 1         |         |
|    93 |  1880.66 | 1         |         |
|    94 | 1880.891 | 1         |         |
|    95 | 1880.377 | 1         |         |
|    96 | 1881.663 | 1         |         |
|    97 |  1881.66 | 1         |         |
|    98 | 1877.888 | 1         |         |
|    99 |  1875.69 | 1         |         |
|   100 | 1875.161 | 1         | min     |
|   101 | 1876.697 | np.nan    |         |
|   102 | 1876.671 | np.nan    |         |
|   103 | 1879.666 | np.nan    |         |
|   111 | 1877.182 | np.nan    |         |
|   112 | 1878.898 | 1         |         |
|   113 | 1878.668 | 1         |         |
|   114 | 1878.871 | 1         |         |
|   115 | 1878.882 | 1         |         |
|   116 | 1879.173 | 1         | max     |
|   117 | 1878.887 | 1         |         |
|   118 |  1878.68 | 1         |         |
|   119 | 1878.872 | 1         |         |
|   120 | 1878.677 | 1         |         |
|   121 | 1877.877 | 1         |         |
|   122 | 1877.669 | 1         |         |
|   123 |  1877.69 | 1         |         |
|   124 | 1877.684 | 1         |         |
|   125 |  1877.68 | 1         |         |
|   126 | 1877.885 | 1         |         |
|   127 | 1877.863 | 1         |         |
|   128 | 1877.674 | 1         |         |
|   129 | 1877.676 | 1         |         |
|   130 | 1877.687 | 1         |         |
|   131 | 1878.367 | 1         |         |
|   132 | 1878.179 | 1         |         |
|   133 | 1877.696 | 1         |         |
|   134 | 1877.665 | 1         | min     |
|   135 | 1877.667 | np.nan    |         |
|   136 | 1878.678 | np.nan    |         |
|   137 | 1878.661 | 1         | max     |
|   138 | 1878.171 | 1         |         |
|   139 | 1877.371 | 1         |         |
|   140 | 1877.359 | 1         |         |
|   141 | 1878.381 | 1         |         |
|   142 | 1875.185 | 1         | min     |
|   143 | 1875.367 | np.nan    |         |
|   144 | 1865.492 | np.nan    |         |
|   145 | 1865.495 | 1         | max     |
|   146 | 1866.995 | 1         |         |
|   147 | 1866.672 | 1         |         |
|   148 | 1867.465 | 1         |         |
|   149 | 1867.663 | 1         |         |
|   150 | 1867.186 | 1         |         |
|   151 | 1867.687 | 1         |         |
|   152 | 1867.459 | 1         |         |
|   153 | 1867.168 | 1         |         |
|   154 | 1869.689 | 1         |         |
|   155 | 1869.693 | 1         |         |
|   156 | 1871.676 | 1         |         |
|   157 | 1873.174 | 1         | min     |
|   158 | 1873.691 | np.nan    |         |
|   159 | 1873.685 | np.nan    |         |
+-------+----------+-----------+---------+

Body:
isnull = data.iloc[:, 1].isnull()
minmax = data.groupby(isnull.cumsum()[~isnull])[0].agg(['idxmax', 'idxmin'])
data.loc[minmax['idxmax'], 'MinMax'] = 'max'
data.loc[minmax['idxmin'], 'MinMax'] = 'min'
data.MinMax = data.MinMax.fillna('')
print(data)

            0    1 MinMax
0    1879.289  NaN
1    1879.281  NaN
2    1879.292  1.0
3    1879.295  1.0
4    1879.481  1.0
5    1879.294  1.0
6    1879.268  1.0    min
7    1879.293  1.0
8    1879.277  1.0
9    1879.285  1.0
10   1879.464  1.0
11   1879.475  1.0
12   1879.971  1.0
13   1879.779  1.0
14   1879.986  1.0
15   1880.791  1.0    max
16   1880.290  1.0
17   1879.253  NaN
18   1878.268  NaN
19   1875.730  1.0    min
20   1876.792  1.0
21   1875.977  1.0
22   1876.408  1.0
23   1877.159  1.0
24   1877.187  1.0
25   1883.164  1.0
26   1883.171  1.0
27   1883.495  1.0
28   1883.962  1.0
29   1885.158  1.0
..        ...  ...    ...
85   1877.687  1.0
86   1878.367  1.0
87   1878.179  1.0
88   1877.696  1.0
89   1877.665  1.0    min
90   1877.667  NaN
91   1878.678  NaN
92   1878.661  1.0    max
93   1878.171  1.0
94   1877.371  1.0
95   1877.359  1.0
96   1878.381  1.0
97   1875.185  1.0    min
98   1875.367  NaN
99   1865.492  NaN
100  1865.495  1.0    min
101  1866.995  1.0
102  1866.672  1.0
103  1867.465  1.0
104  1867.663  1.0
105  1867.186  1.0
106  1867.687  1.0
107  1867.459  1.0
108  1867.168  1.0
109  1869.689  1.0
110  1869.693  1.0
111  1871.676  1.0
112  1873.174  1.0    max
113  1873.691  NaN
114  1873.685  NaN

[115 rows x 3 columns]


问:
I am getting an error: "struct.error: unpack requires a string argument of length 14"
I tried to capture a packet from the network and parser the packet file into my python code. The code ran perfectly for the first few packets in the captured packet list, then it showed the above stated

error in the line : " l2data=unpack("!6s6sH", l2hdr) "

How do I change the value of 'unpack' to fit my packet length in it?

My code:

```<code>#!usr/bin/python

import pcapy

from struct import*

pcap_file=pcapy.open_offline("single.pcap")

count=1

while count:
    print("Packet #:",count)

    count=count+1
    (header,payload)=pcap_file.next()

    l2hdr=payload[:14]
    l2data=unpack("!6s6sH",l2hdr)

    srcmac="%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:" %(ord(l2hdr[0]),ord(l2hdr[1]),ord(l2hdr[2]),ord(l2hdr[3]),ord(l2hdr[4]),ord(l2hdr[5]))
    dstmac="%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:" %(ord(l2hdr[6]),ord(l2hdr[7]),ord(l2hdr[8]),ord(l2hdr[9]),ord(l2hdr[10]),ord(l2hdr[11]))

    print("source MAC:",srcmac,"Destination MAC:",dstmac)

    ipheader=unpack('!BBHHHBBH4s4s',payload[14:34])
    timetolive=ipheader[5]
    protocol=ipheader[6]

    print("Protocol:",str(protocol)],"Time to live:",str(timetolive))
</code>```

答:
```<code>#!/usr/bin/python

import pcapy
from struct import *

cap = pcapy.open_live("en0", 65536, 1, 0)

while 1:
    (header,payload) = cap.next()
    l2hdr = payload[:14]
    l2data = unpack("!6s6sH", l2hdr)
    srcmac = "{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}".format(l2hdr[0],l2hdr[1],l2hdr[2],l2hdr[3],l2hdr[4],l2hdr[5])
    dstmac = "{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}".format(l2hdr[6], l2hdr[7], l2hdr[8], l2hdr[9], l2hdr[10],l2hdr[11])
    print("Source MAC: ", srcmac, " Destination MAC: ", dstmac)

    ipheader = unpack('!BBHHHBBH4s4s' , payload[14:34])
    timetolive = ipheader[5]
    protocol = ipheader[6]
    print("Protocol ", str(protocol), " Time To Live: ", str(timetolive))
</code>```

I'm pretty sure that your problem is related with your file.
However, I recommend to give a look at https://docs.micropython.org/en/latest/pyboard/library/struct.html to understand a bit more about the unpack function.

Body:
I tried to capture a packet from the network and parser the packet file into my python code. The code ran perfectly for the first few packets in the captured packet list, then it showed the above stated

error in the line : " l2data=unpack("!6s6sH", l2hdr) "

How do I change the value of 'unpack' to fit my packet length in it?

My code:

#!usr/bin/python

import pcapy

from struct import*

pcap_file=pcapy.open_offline("single.pcap")

count=1

while count:
    print("Packet #:",count)

    count=count+1
    (header,payload)=pcap_file.next()

    l2hdr=payload[:14]
    l2data=unpack("!6s6sH",l2hdr)

    srcmac="%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:" %(ord(l2hdr[0]),ord(l2hdr[1]),ord(l2hdr[2]),ord(l2hdr[3]),ord(l2hdr[4]),ord(l2hdr[5]))
    dstmac="%.2x:%.2x:%.2x:%.2x:%.2x:%.2x:" %(ord(l2hdr[6]),ord(l2hdr[7]),ord(l2hdr[8]),ord(l2hdr[9]),ord(l2hdr[10]),ord(l2hdr[11]))

    print("source MAC:",srcmac,"Destination MAC:",dstmac)

    ipheader=unpack('!BBHHHBBH4s4s',payload[14:34])
    timetolive=ipheader[5]
    protocol=ipheader[6]

    print("Protocol:",str(protocol)],"Time to live:",str(timetolive))

Body:
#!/usr/bin/python

import pcapy
from struct import *

cap = pcapy.open_live("en0", 65536, 1, 0)

while 1:
    (header,payload) = cap.next()
    l2hdr = payload[:14]
    l2data = unpack("!6s6sH", l2hdr)
    srcmac = "{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}".format(l2hdr[0],l2hdr[1],l2hdr[2],l2hdr[3],l2hdr[4],l2hdr[5])
    dstmac = "{0:02x}:{1:02x}:{2:02x}:{3:02x}:{4:02x}:{5:02x}".format(l2hdr[6], l2hdr[7], l2hdr[8], l2hdr[9], l2hdr[10],l2hdr[11])
    print("Source MAC: ", srcmac, " Destination MAC: ", dstmac)

    ipheader = unpack('!BBHHHBBH4s4s' , payload[14:34])
    timetolive = ipheader[5]
    protocol = ipheader[6]
    print("Protocol ", str(protocol), " Time To Live: ", str(timetolive))

I'm pretty sure that your problem is related with your file.
However, I recommend to give a look at https://docs.micropython.org/en/latest/pyboard/library/struct.html to understand a bit more about the unpack function.


问:
Solving shift/reduce conflicts
I'm using PLY to parse this grammar. I implemented a metagrammar for EBNF used in the linked spec, but PLY reports multiple shift/reduce conflicts.

Grammar:

```<code>Rule 0     S' -> grammar
Rule 1     grammar -> prod_list
Rule 2     grammar -> empty
Rule 3     prod_list -> prod
Rule 4     prod_list -> prod prod_list
Rule 5     prod -> id : : = rule_list
Rule 6     rule_list -> rule
Rule 7     rule_list -> rule rule_list
Rule 8     rule -> rule_simple
Rule 9     rule -> rule_group
Rule 10    rule -> rule_opt
Rule 11    rule -> rule_rep0
Rule 12    rule -> rule_rep1
Rule 13    rule -> rule_alt
Rule 14    rule -> rule_except
Rule 15    rule_simple -> terminal
Rule 16    rule_simple -> id
Rule 17    rule_simple -> char_range
Rule 18    rule_group -> ( rule_list )
Rule 19    rule_opt -> rule_simple ?
Rule 20    rule_opt -> rule_group ?
Rule 21    rule_rep0 -> rule_simple *
Rule 22    rule_rep0 -> rule_group *
Rule 23    rule_rep1 -> rule_simple +
Rule 24    rule_rep1 -> rule_group +
Rule 25    rule_alt -> rule | rule
Rule 26    rule_except -> rule - rule_simple
Rule 27    rule_except -> rule - rule_group
Rule 28    terminal -> SQ string_no_sq SQ
Rule 29    terminal -> DQ string_no_dq DQ
Rule 30    string_no_sq -> LETTER string_no_sq
Rule 31    string_no_sq -> DIGIT string_no_sq
Rule 32    string_no_sq -> SYMBOL string_no_sq
Rule 33    string_no_sq -> DQ string_no_sq
Rule 34    string_no_sq -> + string_no_sq
Rule 35    string_no_sq -> * string_no_sq
Rule 36    string_no_sq -> ( string_no_sq
Rule 37    string_no_sq -> ) string_no_sq
Rule 38    string_no_sq -> ? string_no_sq
Rule 39    string_no_sq -> | string_no_sq
Rule 40    string_no_sq -> [ string_no_sq
Rule 41    string_no_sq -> ] string_no_sq
Rule 42    string_no_sq -> - string_no_sq
Rule 43    string_no_sq -> : string_no_sq
Rule 44    string_no_sq -> = string_no_sq
Rule 45    string_no_sq -> empty
Rule 46    string_no_dq -> LETTER string_no_dq
Rule 47    string_no_dq -> DIGIT string_no_dq
Rule 48    string_no_dq -> SYMBOL string_no_dq
Rule 49    string_no_dq -> SQ string_no_dq
Rule 50    string_no_dq -> + string_no_dq
Rule 51    string_no_dq -> * string_no_dq
Rule 52    string_no_dq -> ( string_no_dq
Rule 53    string_no_dq -> ) string_no_dq
Rule 54    string_no_dq -> ? string_no_dq
Rule 55    string_no_dq -> | string_no_dq
Rule 56    string_no_dq -> [ string_no_dq
Rule 57    string_no_dq -> ] string_no_dq
Rule 58    string_no_dq -> - string_no_dq
Rule 59    string_no_dq -> : string_no_dq
Rule 60    string_no_dq -> = string_no_dq
Rule 61    string_no_dq -> empty
Rule 62    id -> LETTER LETTER id
Rule 63    id -> LETTER DIGIT id
Rule 64    id -> LETTER
Rule 65    id -> DIGIT
Rule 66    rest_of_id -> LETTER rest_of_id
Rule 67    rest_of_id -> DIGIT rest_of_id
Rule 68    rest_of_id -> empty
Rule 69    char_range -> [ UNI_CH - UNI_CH ]
Rule 70    empty -> <empty>
</code>```

Conflicts:

```<code>id  : LETTER LETTER id
            | LETTER DIGIT id
            | LETTER
            | DIGIT
</code>```

.

```<code>state 4

    (62) id -> LETTER . LETTER id
    (63) id -> LETTER . DIGIT id
    (64) id -> LETTER .

  ! shift/reduce conflict for LETTER resolved as shift
  ! shift/reduce conflict for DIGIT resolved as shift
    LETTER          shift and go to state 10
    DIGIT           shift and go to state 9
    |               reduce using rule 64 (id -> LETTER .)
    -               reduce using rule 64 (id -> LETTER .)
    (               reduce using rule 64 (id -> LETTER .)
    SQ              reduce using rule 64 (id -> LETTER .)
    DQ              reduce using rule 64 (id -> LETTER .)
    [               reduce using rule 64 (id -> LETTER .)
    $end            reduce using rule 64 (id -> LETTER .)
    )               reduce using rule 64 (id -> LETTER .)
    :               reduce using rule 64 (id -> LETTER .)
    ?               reduce using rule 64 (id -> LETTER .)
    *               reduce using rule 64 (id -> LETTER .)
    +               reduce using rule 64 (id -> LETTER .)

  ! LETTER          [ reduce using rule 64 (id -> LETTER .) ]
  ! DIGIT           [ reduce using rule 64 (id -> LETTER .) ]
</code>```

The id rule is supposed to guarantee that productions' ids start with a letter.

Next conflict:

```<code>    rule_alt        : rule '|' rule
</code>```

.

```<code>state 113

    (25) rule_alt -> rule | rule .
    (25) rule_alt -> rule . | rule
    (26) rule_except -> rule . - rule_simple
    (27) rule_except -> rule . - rule_group

  ! shift/reduce conflict for | resolved as shift
  ! shift/reduce conflict for - resolved as shift
    (               reduce using rule 25 (rule_alt -> rule | rule .)
    SQ              reduce using rule 25 (rule_alt -> rule | rule .)
    DQ              reduce using rule 25 (rule_alt -> rule | rule .)
    LETTER          reduce using rule 25 (rule_alt -> rule | rule .)
    DIGIT           reduce using rule 25 (rule_alt -> rule | rule .)
    [               reduce using rule 25 (rule_alt -> rule | rule .)
    )               reduce using rule 25 (rule_alt -> rule | rule .)
    $end            reduce using rule 25 (rule_alt -> rule | rule .)
    |               shift and go to state 76
    -               shift and go to state 74

  ! |               [ reduce using rule 25 (rule_alt -> rule | rule .) ]
  ! -               [ reduce using rule 25 (rule_alt -> rule | rule .) ]
</code>```

Connected to a smiliar one:

```<code>rule_except     : rule '-' rule_simple
                | rule '-' rule_group
</code>```

How do I fix these?

答:
First of all, you have apparently slavishly translated the grammar. You need to tokenize the input stream.

Normally, something like id would be a terminal to be discerned by the lexical analyzer, rather than parsed as part of the grammar

```<code>id  : LETTER LETTER id
        | LETTER DIGIT id
        | LETTER
        | DIGIT
</code>```

It looks like everything you have under terminal should not be part of the grammar.

Second, you use right recursion in your grammar. While LALR works with both left and right recursion, you get smaller tables with left recursion.

Suppose you have the input string AA

If you were to insist on parsing identifiers, you'd want something more like

```<code>id : id LETTER
   | id DIGIT
   | LETTER
</code>```

Finally, Shift-Reduce conflicts are not necessarily based. They frequently occur in numeric expressions to be resolved by operator precedent.

Reduce-Reduce conflicts are always bad.

Title: Solving shift/reduce conflicts

Body:
I'm using PLY to parse this grammar. I implemented a metagrammar for EBNF used in the linked spec, but PLY reports multiple shift/reduce conflicts.

Grammar:

Rule 0     S' -> grammar
Rule 1     grammar -> prod_list
Rule 2     grammar -> empty
Rule 3     prod_list -> prod
Rule 4     prod_list -> prod prod_list
Rule 5     prod -> id : : = rule_list
Rule 6     rule_list -> rule
Rule 7     rule_list -> rule rule_list
Rule 8     rule -> rule_simple
Rule 9     rule -> rule_group
Rule 10    rule -> rule_opt
Rule 11    rule -> rule_rep0
Rule 12    rule -> rule_rep1
Rule 13    rule -> rule_alt
Rule 14    rule -> rule_except
Rule 15    rule_simple -> terminal
Rule 16    rule_simple -> id
Rule 17    rule_simple -> char_range
Rule 18    rule_group -> ( rule_list )
Rule 19    rule_opt -> rule_simple ?
Rule 20    rule_opt -> rule_group ?
Rule 21    rule_rep0 -> rule_simple *
Rule 22    rule_rep0 -> rule_group *
Rule 23    rule_rep1 -> rule_simple +
Rule 24    rule_rep1 -> rule_group +
Rule 25    rule_alt -> rule | rule
Rule 26    rule_except -> rule - rule_simple
Rule 27    rule_except -> rule - rule_group
Rule 28    terminal -> SQ string_no_sq SQ
Rule 29    terminal -> DQ string_no_dq DQ
Rule 30    string_no_sq -> LETTER string_no_sq
Rule 31    string_no_sq -> DIGIT string_no_sq
Rule 32    string_no_sq -> SYMBOL string_no_sq
Rule 33    string_no_sq -> DQ string_no_sq
Rule 34    string_no_sq -> + string_no_sq
Rule 35    string_no_sq -> * string_no_sq
Rule 36    string_no_sq -> ( string_no_sq
Rule 37    string_no_sq -> ) string_no_sq
Rule 38    string_no_sq -> ? string_no_sq
Rule 39    string_no_sq -> | string_no_sq
Rule 40    string_no_sq -> [ string_no_sq
Rule 41    string_no_sq -> ] string_no_sq
Rule 42    string_no_sq -> - string_no_sq
Rule 43    string_no_sq -> : string_no_sq
Rule 44    string_no_sq -> = string_no_sq
Rule 45    string_no_sq -> empty
Rule 46    string_no_dq -> LETTER string_no_dq
Rule 47    string_no_dq -> DIGIT string_no_dq
Rule 48    string_no_dq -> SYMBOL string_no_dq
Rule 49    string_no_dq -> SQ string_no_dq
Rule 50    string_no_dq -> + string_no_dq
Rule 51    string_no_dq -> * string_no_dq
Rule 52    string_no_dq -> ( string_no_dq
Rule 53    string_no_dq -> ) string_no_dq
Rule 54    string_no_dq -> ? string_no_dq
Rule 55    string_no_dq -> | string_no_dq
Rule 56    string_no_dq -> [ string_no_dq
Rule 57    string_no_dq -> ] string_no_dq
Rule 58    string_no_dq -> - string_no_dq
Rule 59    string_no_dq -> : string_no_dq
Rule 60    string_no_dq -> = string_no_dq
Rule 61    string_no_dq -> empty
Rule 62    id -> LETTER LETTER id
Rule 63    id -> LETTER DIGIT id
Rule 64    id -> LETTER
Rule 65    id -> DIGIT
Rule 66    rest_of_id -> LETTER rest_of_id
Rule 67    rest_of_id -> DIGIT rest_of_id
Rule 68    rest_of_id -> empty
Rule 69    char_range -> [ UNI_CH - UNI_CH ]
Rule 70    empty -> <empty>

Conflicts:

id  : LETTER LETTER id
            | LETTER DIGIT id
            | LETTER
            | DIGIT

.

state 4

    (62) id -> LETTER . LETTER id
    (63) id -> LETTER . DIGIT id
    (64) id -> LETTER .

  ! shift/reduce conflict for LETTER resolved as shift
  ! shift/reduce conflict for DIGIT resolved as shift
    LETTER          shift and go to state 10
    DIGIT           shift and go to state 9
    |               reduce using rule 64 (id -> LETTER .)
    -               reduce using rule 64 (id -> LETTER .)
    (               reduce using rule 64 (id -> LETTER .)
    SQ              reduce using rule 64 (id -> LETTER .)
    DQ              reduce using rule 64 (id -> LETTER .)
    [               reduce using rule 64 (id -> LETTER .)
    $end            reduce using rule 64 (id -> LETTER .)
    )               reduce using rule 64 (id -> LETTER .)
    :               reduce using rule 64 (id -> LETTER .)
    ?               reduce using rule 64 (id -> LETTER .)
    *               reduce using rule 64 (id -> LETTER .)
    +               reduce using rule 64 (id -> LETTER .)

  ! LETTER          [ reduce using rule 64 (id -> LETTER .) ]
  ! DIGIT           [ reduce using rule 64 (id -> LETTER .) ]

The id rule is supposed to guarantee that productions' ids start with a letter.

Next conflict:

    rule_alt        : rule '|' rule

.

state 113

    (25) rule_alt -> rule | rule .
    (25) rule_alt -> rule . | rule
    (26) rule_except -> rule . - rule_simple
    (27) rule_except -> rule . - rule_group

  ! shift/reduce conflict for | resolved as shift
  ! shift/reduce conflict for - resolved as shift
    (               reduce using rule 25 (rule_alt -> rule | rule .)
    SQ              reduce using rule 25 (rule_alt -> rule | rule .)
    DQ              reduce using rule 25 (rule_alt -> rule | rule .)
    LETTER          reduce using rule 25 (rule_alt -> rule | rule .)
    DIGIT           reduce using rule 25 (rule_alt -> rule | rule .)
    [               reduce using rule 25 (rule_alt -> rule | rule .)
    )               reduce using rule 25 (rule_alt -> rule | rule .)
    $end            reduce using rule 25 (rule_alt -> rule | rule .)
    |               shift and go to state 76
    -               shift and go to state 74

  ! |               [ reduce using rule 25 (rule_alt -> rule | rule .) ]
  ! -               [ reduce using rule 25 (rule_alt -> rule | rule .) ]

Connected to a smiliar one:

rule_except     : rule '-' rule_simple
                | rule '-' rule_group

How do I fix these?

Body:
First of all, you have apparently slavishly translated the grammar. You need to tokenize the input stream.

Normally, something like id would be a terminal to be discerned by the lexical analyzer, rather than parsed as part of the grammar

id  : LETTER LETTER id
        | LETTER DIGIT id
        | LETTER
        | DIGIT

It looks like everything you have under terminal should not be part of the grammar.

Second, you use right recursion in your grammar. While LALR works with both left and right recursion, you get smaller tables with left recursion.

Suppose you have the input string AA

If you were to insist on parsing identifiers, you'd want something more like

id : id LETTER
   | id DIGIT
   | LETTER

Finally, Shift-Reduce conflicts are not necessarily based. They frequently occur in numeric expressions to be resolved by operator precedent.

Reduce-Reduce conflicts are always bad.


问:
Pushing objects into Object Array - Typescript
Having trouble with some code here. Building an application but stumbling over how to work with array objects. I provided the code above NgInit{}. And provided the TS error I am getting in Xcode.

Full component

```<code>import { Component, OnInit } from '@angular/core';
import { Ticker } from '../TickerType';
import { ConversionService } from '../Conversion.service';
import {Observable} from 'rxjs/Rx';
import {resultsType} from './resultsTypeInterface';
@Component({
  selector: 'app-contents',
  templateUrl: './contents.component.html',
  styleUrls: ['./contents.component.scss']
})
export class ContentsComponent implements OnInit{

//Will hold the data from the JSON file

  // Variables for front end
 cryptoSelected : boolean = false;
 regSelected : boolean = false;
 step2AOptions : any[] = [
      {name: "make a selection..."},
      {name: "Bitcoin"},
      {name: "DASH"},
      {name: "Etherium"}
    ]; // step2AOptions
 step2BOptions : any[] = [
      {name: "make a selection..."},
      {name: "CAD"},
      {name: "USD"}
    ]; // step2BOptions
 step2Selection: string;
 holdings: number = 10;

coins: any[] = ["BTC_ETH", "BTC_DASH"];
ticker: Ticker[];
coinResults: resultsType[] =[];
currencyExchange:any[] = [];

  constructor( private conversionService: ConversionService ) {

  }
</code>```

Error

```<code>Argument of type '{ name: string; amount: any; }[]' is not assignable to parameter of type 'resultsType'.
  Property 'name' is missing in type '{ name: string; amount: any; }[]'.
</code>```

This is happening in the code below. What I am trying to do is push this objects into an Object Array so I can access properties of like.

```<code>console.log(coinsResults[0].name);
</code>```

Code

```<code>ngOnInit(){
  this.conversionService.getFullTicker().subscribe((res) => {this.ticker = res;

  for(var j = 0; j<= this.coins.length-1; j++)
  {
    var currencyName: string = this.coins[j];
    if(this.ticker[currencyName])
    {
      var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
      this.coinResults.push(temp)
    }
  }//end the for loop
  }); //end the subscribe function
 this.conversionService.getFullCurrencyExchange().subscribe( (res) => {this.currencyExchange = res["rates"]
  });
  console.log(this.coinResults);
}// End OnInit
</code>```

答:
coinResults is declared as an array of resultsType, so it's push method would only accept arguments of resultsType type. However, you're trying to push an array of resultsType to coinResults (note the square brackets):

// temp is resultsType[]
var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
// but coinResults.push() accept only resultsType
this.coinResults.push(temp)
```

Loose the square brackets around the object literal in var temp=... line.

Body:
Having trouble with some code here. Building an application but stumbling over how to work with array objects. I provided the code above NgInit{}. And provided the TS error I am getting in Xcode.

Full component

import { Component, OnInit } from '@angular/core';
import { Ticker } from '../TickerType';
import { ConversionService } from '../Conversion.service';
import {Observable} from 'rxjs/Rx';
import {resultsType} from './resultsTypeInterface';
@Component({
  selector: 'app-contents',
  templateUrl: './contents.component.html',
  styleUrls: ['./contents.component.scss']
})
export class ContentsComponent implements OnInit{

//Will hold the data from the JSON file

  // Variables for front end
 cryptoSelected : boolean = false;
 regSelected : boolean = false;
 step2AOptions : any[] = [
      {name: "make a selection..."},
      {name: "Bitcoin"},
      {name: "DASH"},
      {name: "Etherium"}
    ]; // step2AOptions
 step2BOptions : any[] = [
      {name: "make a selection..."},
      {name: "CAD"},
      {name: "USD"}
    ]; // step2BOptions
 step2Selection: string;
 holdings: number = 10;

coins: any[] = ["BTC_ETH", "BTC_DASH"];
ticker: Ticker[];
coinResults: resultsType[] =[];
currencyExchange:any[] = [];

  constructor( private conversionService: ConversionService ) {

  }

Error

Argument of type '{ name: string; amount: any; }[]' is not assignable to parameter of type 'resultsType'.
  Property 'name' is missing in type '{ name: string; amount: any; }[]'.

This is happening in the code below. What I am trying to do is push this objects into an Object Array so I can access properties of like.

console.log(coinsResults[0].name);

Code

ngOnInit(){
  this.conversionService.getFullTicker().subscribe((res) => {this.ticker = res;

  for(var j = 0; j<= this.coins.length-1; j++)
  {
    var currencyName: string = this.coins[j];
    if(this.ticker[currencyName])
    {
      var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
      this.coinResults.push(temp)
    }
  }//end the for loop
  }); //end the subscribe function
 this.conversionService.getFullCurrencyExchange().subscribe( (res) => {this.currencyExchange = res["rates"]
  });
  console.log(this.coinResults);
}// End OnInit

Body:
coinResults is declared as an array of resultsType, so it's push method would only accept arguments of resultsType type. However, you're trying to push an array of resultsType to coinResults (note the square brackets):

// temp is resultsType[]
var temp = [{name: currencyName, amount: this.ticker[currencyName].last} ]
// but coinResults.push() accept only resultsType
this.coinResults.push(temp)

Loose the square brackets around the object literal in var temp=... line.


问:
Java Class with multiple methods that can be executed in a thread
I am new to Java multithreaded programming. I have a use case where I have a runnable class called Diner and based on the state of different variables in the program, I want to execute different methods of the Diner Class in parallel.
One way to do that would be to have a single run() method containing multiple if conditions corresponding to different code blocks you want to execute as shown below.

```<code>    public class Diner implements Runnable  {
        Order order;
        int arrivalTime;

        public void run () {
            if(!isSeated){
                //do something to get a seat
            }
            if(!notEatenYet){
                //place order
            }
            if(!orderHasArrived){
                //start eating
            }
            if(finishedEating){
                //pay bill and leave
            }
        }
    }
</code>```

However, is there a more elegant way to do this? Like rather than having a single run() method that can be parallelized, have different methods in the class that could be parallelized (overloading run() ?).

I believe I can use Akka Actors to accomplish something like this, but I am looking for a native solution.

答:
```<code>public class SOCLass {

    public void method1(){
        System.out.println("method1");
    }

    public void method2(){
        System.out.println("method1");
    }

    public static void main(String[] args){
        SOCLass clazz = new SOCLass();

        Runnable task1 = () -> { clazz.method1();};
        Thread t1 = new Thread(task1);
        t1.start();

        Runnable task2 = () -> { clazz.method2();};
        Thread t2 = new Thread(task1);
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
</code>```

EDIT

I think for your case this approach would work better. You could launch the threads in a launch task method after evaluating the boolean. Just one Diner instance

Just keep the threads in place where you can control them

Body:
I am new to Java multithreaded programming. I have a use case where I have a runnable class called Diner and based on the state of different variables in the program, I want to execute different methods of the Diner Class in parallel.
One way to do that would be to have a single run() method containing multiple if conditions corresponding to different code blocks you want to execute as shown below.

    public class Diner implements Runnable  {
        Order order;
        int arrivalTime;

        public void run () {
            if(!isSeated){
                //do something to get a seat
            }
            if(!notEatenYet){
                //place order
            }
            if(!orderHasArrived){
                //start eating
            }
            if(finishedEating){
                //pay bill and leave
            }
        }
    }

However, is there a more elegant way to do this? Like rather than having a single run() method that can be parallelized, have different methods in the class that could be parallelized (overloading run() ?).

I believe I can use Akka Actors to accomplish something like this, but I am looking for a native solution.

Body:
public class SOCLass {

    public void method1(){
        System.out.println("method1");
    }

    public void method2(){
        System.out.println("method1");
    }

    public static void main(String[] args){
        SOCLass clazz = new SOCLass();

        Runnable task1 = () -> { clazz.method1();};
        Thread t1 = new Thread(task1);
        t1.start();

        Runnable task2 = () -> { clazz.method2();};
        Thread t2 = new Thread(task1);
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

EDIT

I think for your case this approach would work better. You could launch the threads in a launch task method after evaluating the boolean. Just one Diner instance

Just keep the threads in place where you can control them


问:
Cannot read property x of undefined in HTML5 Canvas
Hi I have the following Canvas application: http://dev.driz.co.uk/canvas/

But it's not rendering anything out. It should be showing a bunch of balls that move around the screen when the user moves the cursor. I think it's just a small bug somewhere because it was working fine in an older version here: http://dev.driz.co.uk/app/

It's taking a while to load as if it's doing something but just snagging somewhere, but the code looks fine to me. After testing in Firebug the following error comes up: 'Cannot read property x of undefined' on several lines mainly around the gradient creation. I have no idea what the problem is :/ It also complains about property color as well. I have tried for a couple of hours to try and fix this, but I'm lost, really need some help.

If anyone can help it'd be much appreciated. Thank you

EDIT: Here is the code:

```<code>function App()
            {

                var pool    =   document.getElementById('pool');
                var canvas  =   pool.getContext('2d');
                var cwidth  =   pool.width = document.width;
                var cheight =   pool.height = document.height;
                var ctop    =   pool.offsetTop;
                var cleft   =   pool.offsetLeft;
                var size    =   [5, 10, 15, 20, 25, 30];

                var numBalls    =   10;

                var i;
                var x;
                var y;

                var mouseX = 0;
                var mouseY = 0;

                // GIVES EACH BALL A RANDOM COLOR

                function rgb()
                {
                    var color = 'rgb(';

                    for( i=0; i<3; i++)
                    {
                        color += Math.floor(Math.random() * 255) + ',';
                    }

                    return color.replace(/\,$/,')');
                }

                // CREATES A BALL

                function CreateBall(x, y, vx, vy, r, s)
                {
                    this.color = rgb();
                    this.x     = x;
                    this.y     = y;
                    this.vX    = vx;
                    this.vY    = vy;
                    this.r     = r;
                    this.size  = s;
                }

                var ball = [], x, y, vx, vy, r, s;

                for ( i = 0; i < numBalls; i++ )
                {
                    /*x  = Math.random() * cwidth  >> 0;
                    y  = Math.random() * cheight >> 0;
                    vx = Math.random() * 20 - 6;
                    vy = Math.random() * 20 - 6;
                    r  = Math.random() * 30 + 30;*/
                    x = cwidth / 2;
                    y = cheight / 2;
                    vx = Math.random() * 20 - 6;
                    vy = Math.random() * 20 - 6;
                    r = Math.random() * 30 + 30;

                    s  = size[Math.random() * size.length >> 0];

                    // CREATES THE BALLS

                    ball.push( new CreateBall(x, y, vx, vy, r, s));
                }

                setInterval(function ()
                {
                    canvas.clearRect(0, 0, cwidth, cheight);

                    for ( i = 0; i < balls.length; i++ )
                    {
                        var gradient = canvas.createRadialGradient(ball[i].x + ball[i].r/4, ball[i].y - ball[i].r/4, ball[i].r/5, ball[i].x, ball[i].y, ball[i].r);
                        gradient.addColorStop(0, '#fff');
                        gradient.addColorStop(.85, ball[i].color);
                        gradient.addColorStop(1, '#222');

                        canvas.fillStyle = gradient;

                        ball[i].vx *= 0.99;
                        ball[i].vy *= 0.99;

                        ball[i].x += ball[i].vx;
                        ball[i].y += ball[i].vy;

                        if ( ball[i].x < ball[i].r || ball[i].x > cwidth - ball[i].r )
                        {
                            ball[i].vx = -ball[i].vx;
                            ball[i].x += ball[i].vx;
                        }

                        if ( ball[i].y < ball[i].r || ball[i].y > cheight - ball[i].r )
                        {
                            ball[i].vy = -ball[i].vy;
                            ball[i].y += ball[i].vy;
                        }

                        canvas.beginPath();

                        canvas.arc ( ball[i].x, ball[i].y, ball[i].r, 0, Math.PI * 2, true );

                        canvas.fill();
                    }
                }, 30);

                // END FOR

                // MOUSE MOVEMENT - BALLS SHOULD MOVE AWAY FROM MOUSE CURSOR

                pool.onmousemove = function ( e )
                {
                    x = e.pageX - cleft;
                    y = e.pageY - ctop;

                    for ( i = 0; i < balls.length; i++ )
                    {
                        if ( Math.abs( x - ball[i].x ) < 20 && Math.abs( y - ball[i].y ) < 20 )
                        {
                            ball[i].vx = ( x - ball[i].x ) / 1;
                            ball[i].vy = ( y - ball[i].y ) / 1;
                        }
                    }
                };

              // END APP

            }
</code>```

答:
```<code>function App() {
    var pool = document.getElementById('pool');
    var canvas = pool.getContext('2d');
    var cwidth = pool.width = document.width;
    var cheight = pool.height = document.height;
    var ctop = pool.offsetTop;
    var cleft = pool.offsetLeft;
    var size = [5, 10, 15, 20, 25, 30];
    var numBalls = 3;
    var i;
    var x;
    var y;
    var mouseX = 0;
    var mouseY = 0;

    function rgb() {
        var color = 'rgb(';
        for (var i = 0; i < 3; i++) {
            color += Math.floor(Math.random() * 255) + ',';
        }
        return color.replace(/\,$/, ')');
    }

    function CreateBall(x, y, vx, vy, r, s) {
        this.color = rgb();
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.r = r;
        this.size = s;
    }

    var ball = [],
        x, y, vx, vy, r, s;

    for (var i = 0; i < numBalls; i++) {
        x = cwidth / 2;
        y = cheight / 2;
        vx = Math.random() * 20 - 6;
        vy = Math.random() * 20 - 6;
        r = Math.random() * 30 + 30;
        s = size[Math.random() * size.length >> 0];

        ball.push(new CreateBall(x, y, vx, vy, r, s));
    }

    setInterval(function () {
        canvas.clearRect(0, 0, cwidth, cheight);
        for (var i = 0; i < ball.length; i++) {
            var gradient = canvas.createRadialGradient(ball[i].x + ball[i].r / 4, ball[i].y - ball[i].r / 4, ball[i].r / 5, ball[i].x, ball[i].y, ball[i].r);
            gradient.addColorStop(0, '#fff');
            gradient.addColorStop(.85, ball[i].color);
            gradient.addColorStop(1, '#222');

            canvas.fillStyle = gradient;

            ball[i].vx *= 0.99;
            ball[i].vy *= 0.99;

            ball[i].x += ball[i].vx;
            ball[i].y += ball[i].vy;

            if (ball[i].x < ball[i].r || ball[i].x > cwidth - ball[i].r) {
                ball[i].vx = -ball[i].vx;
                ball[i].x += ball[i].vx;
            }

            if (ball[i].y < ball[i].r || ball[i].y > cheight - ball[i].r) {
                ball[i].vy = -ball[i].vy;
                ball[i].y += ball[i].vy;
            }

            canvas.beginPath();
            canvas.arc(ball[i].x, ball[i].y, ball[i].r, 0, Math.PI * 2, 0);
            canvas.fill();
        }
    }, 1000 / 30);

    pool.onmousemove = function (e) {
        x = e.pageX - cleft;
        y = e.pageY - ctop;

        for (var i = 0; i < ball.length; i++) {
            if (Math.abs(x - ball[i].x) < 20 && Math.abs(y - ball[i].y) < 20) {
                ball[i].vx = (x - ball[i].x) / 1;
                ball[i].vy = (y - ball[i].y) / 1;
            }
        }
    };
}
</code>```

I just kicked it's ass here, Do you wanna kick it's ass too ??

ContentLicense: CC BY-SA 2.5

Body:
Hi I have the following Canvas application: http://dev.driz.co.uk/canvas/

But it's not rendering anything out. It should be showing a bunch of balls that move around the screen when the user moves the cursor. I think it's just a small bug somewhere because it was working fine in an older version here: http://dev.driz.co.uk/app/

It's taking a while to load as if it's doing something but just snagging somewhere, but the code looks fine to me. After testing in Firebug the following error comes up: 'Cannot read property x of undefined' on several lines mainly around the gradient creation. I have no idea what the problem is :/ It also complains about property color as well. I have tried for a couple of hours to try and fix this, but I'm lost, really need some help.

If anyone can help it'd be much appreciated. Thank you

EDIT: Here is the code:

function App()
            {

                var pool    =   document.getElementById('pool');
                var canvas  =   pool.getContext('2d');
                var cwidth  =   pool.width = document.width;
                var cheight =   pool.height = document.height;
                var ctop    =   pool.offsetTop;
                var cleft   =   pool.offsetLeft;
                var size    =   [5, 10, 15, 20, 25, 30];

                var numBalls    =   10;

                var i;
                var x;
                var y;

                var mouseX = 0;
                var mouseY = 0;

                // GIVES EACH BALL A RANDOM COLOR

                function rgb()
                {
                    var color = 'rgb(';

                    for( i=0; i<3; i++)
                    {
                        color += Math.floor(Math.random() * 255) + ',';
                    }

                    return color.replace(/\,$/,')');
                }

                // CREATES A BALL

                function CreateBall(x, y, vx, vy, r, s)
                {
                    this.color = rgb();
                    this.x     = x;
                    this.y     = y;
                    this.vX    = vx;
                    this.vY    = vy;
                    this.r     = r;
                    this.size  = s;
                }

                var ball = [], x, y, vx, vy, r, s;

                for ( i = 0; i < numBalls; i++ )
                {
                    /*x  = Math.random() * cwidth  >> 0;
                    y  = Math.random() * cheight >> 0;
                    vx = Math.random() * 20 - 6;
                    vy = Math.random() * 20 - 6;
                    r  = Math.random() * 30 + 30;*/
                    x = cwidth / 2;
                    y = cheight / 2;
                    vx = Math.random() * 20 - 6;
                    vy = Math.random() * 20 - 6;
                    r = Math.random() * 30 + 30;

                    s  = size[Math.random() * size.length >> 0];

                    // CREATES THE BALLS

                    ball.push( new CreateBall(x, y, vx, vy, r, s));
                }

                setInterval(function ()
                {
                    canvas.clearRect(0, 0, cwidth, cheight);

                    for ( i = 0; i < balls.length; i++ )
                    {
                        var gradient = canvas.createRadialGradient(ball[i].x + ball[i].r/4, ball[i].y - ball[i].r/4, ball[i].r/5, ball[i].x, ball[i].y, ball[i].r);
                        gradient.addColorStop(0, '#fff');
                        gradient.addColorStop(.85, ball[i].color);
                        gradient.addColorStop(1, '#222');

                        canvas.fillStyle = gradient;

                        ball[i].vx *= 0.99;
                        ball[i].vy *= 0.99;

                        ball[i].x += ball[i].vx;
                        ball[i].y += ball[i].vy;

                        if ( ball[i].x < ball[i].r || ball[i].x > cwidth - ball[i].r )
                        {
                            ball[i].vx = -ball[i].vx;
                            ball[i].x += ball[i].vx;
                        }

                        if ( ball[i].y < ball[i].r || ball[i].y > cheight - ball[i].r )
                        {
                            ball[i].vy = -ball[i].vy;
                            ball[i].y += ball[i].vy;
                        }

                        canvas.beginPath();

                        canvas.arc ( ball[i].x, ball[i].y, ball[i].r, 0, Math.PI * 2, true );

                        canvas.fill();
                    }
                }, 30);

                // END FOR

                // MOUSE MOVEMENT - BALLS SHOULD MOVE AWAY FROM MOUSE CURSOR

                pool.onmousemove = function ( e )
                {
                    x = e.pageX - cleft;
                    y = e.pageY - ctop;

                    for ( i = 0; i < balls.length; i++ )
                    {
                        if ( Math.abs( x - ball[i].x ) < 20 && Math.abs( y - ball[i].y ) < 20 )
                        {
                            ball[i].vx = ( x - ball[i].x ) / 1;
                            ball[i].vy = ( y - ball[i].y ) / 1;
                        }
                    }
                };

              // END APP

            }

Body:
function App() {
    var pool = document.getElementById('pool');
    var canvas = pool.getContext('2d');
    var cwidth = pool.width = document.width;
    var cheight = pool.height = document.height;
    var ctop = pool.offsetTop;
    var cleft = pool.offsetLeft;
    var size = [5, 10, 15, 20, 25, 30];
    var numBalls = 3;
    var i;
    var x;
    var y;
    var mouseX = 0;
    var mouseY = 0;

    function rgb() {
        var color = 'rgb(';
        for (var i = 0; i < 3; i++) {
            color += Math.floor(Math.random() * 255) + ',';
        }
        return color.replace(/\,$/, ')');
    }

    function CreateBall(x, y, vx, vy, r, s) {
        this.color = rgb();
        this.x = x;
        this.y = y;
        this.vx = vx;
        this.vy = vy;
        this.r = r;
        this.size = s;
    }

    var ball = [],
        x, y, vx, vy, r, s;

    for (var i = 0; i < numBalls; i++) {
        x = cwidth / 2;
        y = cheight / 2;
        vx = Math.random() * 20 - 6;
        vy = Math.random() * 20 - 6;
        r = Math.random() * 30 + 30;
        s = size[Math.random() * size.length >> 0];

        ball.push(new CreateBall(x, y, vx, vy, r, s));
    }

    setInterval(function () {
        canvas.clearRect(0, 0, cwidth, cheight);
        for (var i = 0; i < ball.length; i++) {
            var gradient = canvas.createRadialGradient(ball[i].x + ball[i].r / 4, ball[i].y - ball[i].r / 4, ball[i].r / 5, ball[i].x, ball[i].y, ball[i].r);
            gradient.addColorStop(0, '#fff');
            gradient.addColorStop(.85, ball[i].color);
            gradient.addColorStop(1, '#222');

            canvas.fillStyle = gradient;

            ball[i].vx *= 0.99;
            ball[i].vy *= 0.99;

            ball[i].x += ball[i].vx;
            ball[i].y += ball[i].vy;

            if (ball[i].x < ball[i].r || ball[i].x > cwidth - ball[i].r) {
                ball[i].vx = -ball[i].vx;
                ball[i].x += ball[i].vx;
            }

            if (ball[i].y < ball[i].r || ball[i].y > cheight - ball[i].r) {
                ball[i].vy = -ball[i].vy;
                ball[i].y += ball[i].vy;
            }

            canvas.beginPath();
            canvas.arc(ball[i].x, ball[i].y, ball[i].r, 0, Math.PI * 2, 0);
            canvas.fill();
        }
    }, 1000 / 30);

    pool.onmousemove = function (e) {
        x = e.pageX - cleft;
        y = e.pageY - ctop;

        for (var i = 0; i < ball.length; i++) {
            if (Math.abs(x - ball[i].x) < 20 && Math.abs(y - ball[i].y) < 20) {
                ball[i].vx = (x - ball[i].x) / 1;
                ball[i].vy = (y - ball[i].y) / 1;
            }
        }
    };
}

I just kicked it's ass here, Do you wanna kick it's ass too ??


问:
Get list of stored procedures from a U-SQL database
Is that a way to get list of all stored procedures (and functions) for a U-SQL database? It would be great if I could get full stored procedure name and it's body script.

I'm building a simple tool for automating of creating/updating U-SQL stored procedures. I'm trying to find a way to implement the operations:
deleted all stored procedures, check stored procedure existence, compare exited stored procedure's body with the new one.

Could anyone help me?

答: the different client SDKs have commands to enumerate your meta data objects. Eg. Get-AzureRmDataLakeAnalyticsCatalogItem in Powershell. See https://learn.microsoft.com/en-us/azure/data-lake-analytics/data-lake-analytics-manage-use-powershell. Similar commands exists in the other SDKs.


问:
SQL Server PHP Code Igniter show one to many relationship
i want to show data from table_one,where tableone_id is included on table_two..which is one to many relationship..here is the example.

```<code>table_one                table_two
id  | name               id  | name |tableone_id
1   |   A                1   |   C  |     1
2   |   B                2   |   D  |     1
                         3   |   E  |     2
                         4   |   F  |     2
</code>```

The result i was expecting on my PHP is..

```<code>Number  | Name | Linked Item |
  1     |  A   |    C        |
        |      |    D        |
  2     |  B   |    E        |
        |      |    F        |
</code>```

i already tried some code like

```<code>**Controller.php**
$head = $this->db->query("SELECT * from table_one)->result_array();

foreach($head as $key => $value)
{
   $head[$key]['items'] = $this->db->query("SELECT
   a.id,
   b.id,
   b.name as tabletwo_name,
   FROM table_one a
   JOIN table_two b on a.id = b.id
   where b.id =".$value['id'])->result_array();
}
</code>```

the code i make ,fails.how did i do the right code for that case ?

Thank you

答:
your db queries should be in the model, not in the controller

you are missing double quotes in the first select, your string is not closed

why are you selecting all results from table_one and then doing JOINed select? You are not even selecting the data you want to have in your output (like table_two.name).

Change your first query to:

```<code>$this->db->query("SELECT table_one.id as number, table_one.name as name, table_two.name as linked_item FROM table_one LEFT JOIN table_two ON table_one.id = table_two.tableone_id")->result_array();
</code>```

and then just do this:

```<code>foreach($head as $key => $value)
{
   $head[$key]['items'] = $value;
}
</code>```

Body:
i want to show data from table_one,where tableone_id is included on table_two..which is one to many relationship..here is the example.

table_one                table_two
id  | name               id  | name |tableone_id
1   |   A                1   |   C  |     1
2   |   B                2   |   D  |     1
                         3   |   E  |     2
                         4   |   F  |     2

The result i was expecting on my PHP is..

Number  | Name | Linked Item |
  1     |  A   |    C        |
        |      |    D        |
  2     |  B   |    E        |
        |      |    F        |

i already tried some code like

**Controller.php**
$head = $this->db->query("SELECT * from table_one)->result_array();

foreach($head as $key => $value)
{
   $head[$key]['items'] = $this->db->query("SELECT
   a.id,
   b.id,
   b.name as tabletwo_name,
   FROM table_one a
   JOIN table_two b on a.id = b.id
   where b.id =".$value['id'])->result_array();
}

the code i make ,fails.how did i do the right code for that case ?

Thank you

Body:
your db queries should be in the model, not in the controller

you are missing double quotes in the first select, your string is not closed

why are you selecting all results from table_one and then doing JOINed select? You are not even selecting the data you want to have in your output (like table_two.name).

Change your first query to:

$this->db->query("SELECT table_one.id as number, table_one.name as name, table_two.name as linked_item FROM table_one LEFT JOIN table_two ON table_one.id = table_two.tableone_id")->result_array();

and then just do this:

foreach($head as $key => $value)
{
   $head[$key]['items'] = $value;
}


问:
Remove whitespace after first line using SED
I am trying to edit a file with sed, my goal is to remove the white-space between the numbers but preserve it after the first word (eg Water 1983 02 13, - 1984 02 1, turns into Water,19840213,1984021)
Here is my current command:

```<code>awk '{print $10,$4,$2,$3,$5,$8,$6,$7}' czodiac | sed 's/Feb/02/g;s/Jan/02/g;s/–//g;s/ //g;s/,$//g'
</code>```

output so far: Water19830213,1984021

Body:
I am trying to edit a file with sed, my goal is to remove the white-space between the numbers but preserve it after the first word (eg Water 1983 02 13, - 1984 02 1, turns into Water,19840213,1984021)
Here is my current command:

awk '{print $10,$4,$2,$3,$5,$8,$6,$7}' czodiac | sed 's/Feb/02/g;s/Jan/02/g;s/–//g;s/ //g;s/,$//g'

output so far: Water19830213,1984021

Body:
Given:

$ echo "$s"
Water 1983 02 13, - 1984 02 1

You can do:

$ echo "$s" | awk '{sub(/ /,","); sub(/, - /,","); gsub(/[  ]+/,"")}1'
Water,19830213,1984021


问:
how to change language of retrieved content using language api in wikipedia?
I want two api call one for content and the other one for language change.</p>

答:
Some experimentation shows that getting content links for one or more page titles, and specifying a required language for the content are part of the same API query. A specific language can be requested by providing a lllang parameter in the query string with a suitable language code value.

For example to get the URL of a page with title "Albert Einstein" translated into Egyptian Arabic (code "arz") in the API's sandbox:

```<code>https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&format=json&prop=langlinks&titles=Albert+Einstein&llprop=url&lllang=arz
</code>```

Depending on the application and query volumes, it can improve efficiency to request data for multiple titles and/or all languages in one call and search through the results, as opposed to making many separate, individual calls.

FWIW. The API documentation seems to lack instructions to provide specific parameters for a "langlinks` or other query types simply by adding them as key-value pairs to the query string.

Body:
Some experimentation shows that getting content links for one or more page titles, and specifying a required language for the content are part of the same API query. A specific language can be requested by providing a lllang parameter in the query string with a suitable language code value.

For example to get the URL of a page with title "Albert Einstein" translated into Egyptian Arabic (code "arz") in the API's sandbox:

https://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&format=json&prop=langlinks&titles=Albert+Einstein&llprop=url&lllang=arz

Depending on the application and query volumes, it can improve efficiency to request data for multiple titles and/or all languages in one call and search through the results, as opposed to making many separate, individual calls.

FWIW. The API documentation seems to lack instructions to provide specific parameters for a "langlinks` or other query types simply by adding them as key-value pairs to the query string.


问:
Access to instance not referenced by user code of IDisposable into "using" statement
I have this piece of code:

```<code>using(var a = myFunction()){

    a.Process();

}
</code>```

There is some way to reference not defined instance (a in the above sample) into the using statement?

I mean, to write some like:

```<code>using(myFunction()){

    [Reflection?, another stuff?].Process();

}
</code>```

Where [Reflection?, another stuff?] should be the equivalent to a.

The instance (the value returned by myFunction()) exist into the using scope, I am sure, because the method Dispose() of IDisposable is fired properly.

Some clue?

答:
I suppose you could put the last created instance in a static field. I hope you don't want to do this multiple times concurrently.</p>

```<code>static void Main(string[] args)
{
    using (myFunction())
    {
        myClass.LastInstance.Process();
    }
    Console.ReadLine();
}
static myClass myFunction()
{
    return new myClass();
}
class myClass : IDisposable
{
    public static myClass LastInstance;
    public myClass()
    {
        Console.WriteLine("constructor");
        LastInstance = this;
    }
    public void Dispose() { Console.WriteLine("dispose"); }
    public void Process() { Console.WriteLine("process"); }
}
</code>```

Body:
I have this piece of code:

using(var a = myFunction()){

    a.Process();

}

There is some way to reference not defined instance (a in the above sample) into the using statement?

I mean, to write some like:

using(myFunction()){

    [Reflection?, another stuff?].Process();

}

Where [Reflection?, another stuff?] should be the equivalent to a.

The instance (the value returned by myFunction()) exist into the using scope, I am sure, because the method Dispose() of IDisposable is fired properly.

Some clue?

Body:
I suppose you could put the last created instance in a static field. I hope you don't want to do this multiple times concurrently.

static void Main(string[] args)
{
    using (myFunction())
    {
        myClass.LastInstance.Process();
    }
    Console.ReadLine();
}
static myClass myFunction()
{
    return new myClass();
}
class myClass : IDisposable
{
    public static myClass LastInstance;
    public myClass()
    {
        Console.WriteLine("constructor");
        LastInstance = this;
    }
    public void Dispose() { Console.WriteLine("dispose"); }
    public void Process() { Console.WriteLine("process"); }
}


问:
Why am I having so much trouble submitting my app to Apple?
This is my first time trying to submit an app to Apple, and I'm having a bunch of issues. I'm pretty sure I've generated all my certificates, AppID's, etc... I've been running the app on my phone just fine, then all of a sudden I started getting errors submitting. My first error was this:

But as you can see, the Bundle ID's are the same:

The ID in Xcode:

And the ID in iTunes Connect:

So I tried changing the Bundle ID, and made sure the Bundle ID's were the same across iTunes connect, Xcode, etc. I started out the project with a different name. Should I just start a new project with consistent naming?

Should the Bundle Identifier in Info read com.Kaen.M01eskin ?

It doesn't work with Application Loader either:

答: Try using the Application Loader utility instead of the Archive upload to the App Store. It's available in the menu under Xcode... Open Developer Tool... Application Loader.  You still have to create an Archive first; main difference is that you have to pick out your Archive via a Finder interface. Plus, you can get an active timeline for all the tasks, with current task and elapsed times.</p>


问:
How point application to database.php which resides in a non-public folder?
Now that my app is built I am researching how to secure it. If I place database.php file in a folder outside of the public folder how can I point to it from inside the app? Simply using the include structure is not sufficient since this only goes to the top of the public folder.</p>

```<code>include '../database.php';
</code>```

答:
You can use dirname(). Let's say your folder structure is:

```<code>public_html/
  index.php
  contact.php
  whatever.php
private/
  database.php
</code>```

In your public_html files, you can call:

```<code>$db_file = dirname( $_SERVER[ 'DOCUMENT_ROOT' ] ) . '/private/database.php';
include_once( $db );
</code>```

If public_html is your $_SERVER[ 'DOCUMENT_ROOT' ], dirname will give you the folder containing public_html and private. Then you just need to pass the path to database.php.

If it's up another level (or more), you can use dirname multiple times:

```<code>$db_file = dirname( dirname( $_SERVER[ 'DOCUMENT_ROOT' ] ) ) . '/private/database.php';
</code>```

This would get you another folder up.

Body:
Now that my app is built I am researching how to secure it. If I place database.php file in a folder outside of the public folder how can I point to it from inside the app? Simply using the include structure is not sufficient since this only goes to the top of the public folder.

include '../database.php';

Body:
You can use dirname(). Let's say your folder structure is:

public_html/
  index.php
  contact.php
  whatever.php
private/
  database.php

In your public_html files, you can call:

$db_file = dirname( $_SERVER[ 'DOCUMENT_ROOT' ] ) . '/private/database.php';
include_once( $db );

If public_html is your $_SERVER[ 'DOCUMENT_ROOT' ], dirname will give you the folder containing public_html and private. Then you just need to pass the path to database.php.

If it's up another level (or more), you can use dirname multiple times:

$db_file = dirname( dirname( $_SERVER[ 'DOCUMENT_ROOT' ] ) ) . '/private/database.php';

This would get you another folder up.


问:
Converting function signature from compiler language to c++
Hey guys, I need to make a list of some functions that are listed in the linker output. The syntax i get is as follows:

```<code>int foo(int num,double dnum, Temp & temp) (in namespace "funcsns")
</code>```

Turns into:

```<code>.text._ZN7funcsns3fooEidRNS_4TempE
</code>```

(You might know it from the "undefined symbol" and some other linking errors that print functions names)

Now, i can write a script that somehow turns it into something readable but i wonder if there is a smart way of doing it.

Please share your ideas!

thanks.

答:
On a system using the GNU toolchain, the c++filt program does exactly what you're looking for.  It's part of the "binutils" package.  Dunno about other systems.

The ".text." isn't part of the mangled name.  Running c++filt _ZN7funcsns3fooEidRNS_4TempE yields funcsns::foo(int, double, funcsns::Temp&).

Body:
Hey guys, I need to make a list of some functions that are listed in the linker output. The syntax i get is as follows:

int foo(int num,double dnum, Temp & temp) (in namespace "funcsns")

Turns into:

.text._ZN7funcsns3fooEidRNS_4TempE

(You might know it from the "undefined symbol" and some other linking errors that print functions names)

Now, i can write a script that somehow turns it into something readable but i wonder if there is a smart way of doing it.

Please share your ideas!

thanks.


答:
You can use it multiple times include '../../../../database.php'; each .. represents one parent folder
also you can define full path instead of relative path
like include '/home/secret_folder/place_of_database/database.php';

Title: How point application to database.php which resides in a non-public folder?