问:
Select based on another select using php Not working
Select based on another select using PHP not working only when a new row is added.

For demo visit here (See steps for demo)

There are two rows when the page is loaded, they are working as wanted. (Service option is as per item option)

Click on the Add Row button, one more row will be added

The newly inserted row is not working. (Service select is not giving any options, as first two gives)

What I tried:

```<code><?php require_once '../home.php' ?>
<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
        ob_clean();

        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
        if( $action && $id && !is_nan( $id ) ){

            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmt->bindParam(':irn',$id);
            $stmt->execute();
            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmtin->bindParam(':irn',$id);
            $stmtin->execute();
            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );

            if( $stmt->rowCount() > 0 ){
                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
                 }
            }
        }
        exit();
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type='text/javascript' charset='utf-8'>
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }
            function createmenu(r,o,h){
                o.menu.innerHTML=r;
            }

            function bindEvents(){
                var oSelItem=document.querySelector('select[name="item1"]');
                var oSelService=document.querySelector('select[name="service1"]');
                oSelItem.onchange=function(e){

                    var method='post';
                    var url=location.href;
                    var params={
                        'action':'get_dependant_menu',
                        'id':this.options[ this.options.selectedIndex ].value
                    };
                    var opts={
                        menu:oSelService
                    };
                    ajax.call( this, method, url, params, createmenu, opts );
                }.bind( oSelItem );
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents,false );
        </script>
</head>
<body>
<form method="post" action="invoice_form.php" id="item_sel">

    <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
   <tr>
    <td colspan="3">
      <input type="text" name="customer" value="" placeholder="Customer Name">
    </td>
  </tr>
  <tr>
    <th>Item</th>
    <th>Service</th>
    <th>Qty</th>

  </tr>

    <tr>
      <td>
      <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
            <?php

                //$sql='select * from `item` order by `Sr` asc;';
                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select></td>

      <td><select class="country" name="service1">
</select></td>
<td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
      <td>
      <select name='item2' class='country'>
            <option>Select Item</option>
            <?php

                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select></td>

      <td><select class="country" name="service2">
</select></td>
<td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
        <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
        <span class="glyphicon glyphicon-save"></span>   Save
        </button>
        </td>
    </tr>
</table>
    <input type="button" class="add-row" value="Add Row">
</form>
<div id="markup_model" class="hide">
  <table>
    <tr>
      <td>
        <select name="nameitem" class="country">
                    <option>Select Item</option>
                    <?php
                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                        $stmt->execute();

                        if( $stmt->rowCount() > 0 ){
                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                            }
                        }
                    ?>
                </select>
      </td>
      <td>
        <select class="country" name="namewhat"></select>
      </td>
      <td>
        <input type="text" name="nameqty" value="" placeholder="Quantity" />
      </td>
    </tr>
  </table>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
  var cont = 3
  var qty = "qty"
  var item = "item"
  var what = "service"

  $(".add-row").click(function() {
    var nameqty = qty + cont;
    var nameitem = item + cont;
    var namewhat = what + cont;

    var markup = $('#markup_model tbody');

    $(markup).find('.country:eq(0)').attr('name', nameitem);
    $(markup).find('.country:eq(1)').attr('name', namewhat);
    $(markup).find('input').attr('name', nameqty);

    $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));

    cont++;
  });
});
</script>
<script type='text/javascript' charset='utf-8'>
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }
            function createmenu(r,o,h){
                o.menu.innerHTML=r;
            }

            function bindEvents(){
                var oSelItem2=document.querySelector('select[name="item2"]');
                var oSelService2=document.querySelector('select[name="service2"]');
                oSelItem2.onchange=function(e){

                    var method='post';
                    var url=location.href;
                    var params={
                        'action':'get_dependant_menu',
                        'id':this.options[ this.options.selectedIndex ].value
                    };
                    var opts={
                        menu:oSelService2
                    };
                    ajax.call( this, method, url, params, createmenu, opts );
                }.bind( oSelItem2 );
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents,false );
        </script>
        <script type='text/javascript' charset='utf-8'>
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }
            function createmenu(r,o,h){
                o.menu.innerHTML=r;
            }

            function bindEvents(){
                var oSelItem3=document.querySelector('select[name="item3"]');
                var oSelService3=document.querySelector('select[name="service3"]');
                oSelItem3.onchange=function(e){

                    var method='post';
                    var url=location.href;
                    var params={
                        'action':'get_dependant_menu',
                        'id':this.options[ this.options.selectedIndex ].value
                    };
                    var opts={
                        menu:oSelService3
                    };
                    ajax.call( this, method, url, params, createmenu, opts );
                }.bind( oSelItem3 );
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents,false );
        </script>

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

答:
Your problem is because of this error - Uncaught TypeError: Cannot set property 'onchange' of null at HTMLDocument.bindEvents on line 243. You can see the same in inspect elements. This is because you are defining the function bindEvents for item3, which has not yet been added. Also this will work only in case of a single row being added. Changed your logic and used jquery a lot. I have commented out php part in your code and hard coded that stuff. Also created a php file that sends ajax response on select box change.

```<code>    <?php // require_once '../home.php' ?>
    <?php

    foreach($_POST as $key => $val) {
        echo "$key => $val <br>";
    }

        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
            echo "here <br>";
            ob_clean();
    //
    //        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
    //        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
    //        if( $action && $id && !is_nan( $id ) ){
    //
    //            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
    //            $stmt->bindParam(':irn',$id);
    //            $stmt->execute();
    //            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
    //            $stmtin->bindParam(':irn',$id);
    //            $stmtin->execute();
    //            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );
    //
    //            if( $stmt->rowCount() > 0 ){
    //                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
    //                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
    //                 }
    //            }
    //        }
            echo "<option value='Select Service'>Select Service (Pant)</option>";
            echo "<option value='12121211'>Iron</option>";
            exit();
        }
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>

    </head>
    <body>
        <div class="container">
    <form method="post" action="invoice_form.php" id="item_sel">

        <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
       <tr>
        <td colspan="3">
          <input type="text" name="customer" value="" placeholder="Customer Name">
        </td>
      </tr>
      <tr>
        <th>Item</th>
        <th>Service</th>
        <th>Qty</th>

      </tr>

        <tr>
          <td>
          <select name='item1' class='country'>
                <option value="Select Item">Select Item</option>
                <?php

    //                //$sql='select * from `item` order by `Sr` asc;';
    //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                $stmt->execute();
    //
    //                if( $stmt->rowCount() > 0 ){
    //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                    }
    //                }

                ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>

    </select></td>

          <td><select class="country" name="service1">
    </select></td>
    <td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
        </tr>
        <tr>
          <td>
          <select name='item2' class='country'>
                <option>Select Item</option>
                <?php

    //
    //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                $stmt->execute();
    //
    //                if( $stmt->rowCount() > 0 ){
    //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                    }
    //                }

                ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>
    </select></td>

          <td><select class="country" name="service2">
    </select></td>
    <td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
        </tr>
        <tr>
            <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
            <span class="glyphicon glyphicon-save"></span>   Save
            </button>
            </td>
        </tr>
    </table>
        <input type="button" class="add-row" value="Add Row">
    </form>
    <div id="markup_model" class="hide">
      <table>
        <tr>
          <td>
            <select name="nameitem" class="country">
                        <option>Select Item</option>
                        <?php
    //                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                        $stmt->execute();
    //
    //                        if( $stmt->rowCount() > 0 ){
    //                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                            }
    //                        }
                        ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>
                    </select>
          </td>
          <td>
            <select class="country" name="namewhat"></select>
          </td>
          <td>
            <input type="text" name="nameqty" value="" placeholder="Quantity" />
          </td>
        </tr>
      </table>
    </div>
    </div>
    <script src="js/jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
      var cont = 3;
      var qty = "qty";
      var item = "item";
      var what = "service";

      $(".add-row").click(function() {
        var nameqty = qty + cont;
        var nameitem = item + cont;
        var namewhat = what + cont;

        var markup = $('#markup_model tbody');

        $(markup).find('.country:eq(0)').attr('name', nameitem);
        $(markup).find('.country:eq(1)').attr('name', namewhat);
        $(markup).find('input').attr('name', nameqty);

        $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));

        cont++;
      });

        $('.container').on( 'change', '.country', function () {
            //console.log($(this).attr('name'));
            var oSelItem = $(this).attr('name');
            var lastChar = oSelItem.substr(oSelItem.length -1);
            var prevChar = oSelItem.substr(0, oSelItem.length-1);
            //console.log(prevChar);
            if(prevChar === "item") {
              var oSelService = "service" + lastChar;
              console.log(oSelItem + "  " + oSelService);
              console.log($(this).val());
              var thisId = $(this).val();
             $.ajax({
                type: 'post',
                url: 'ajax.php',
                data: {
                 'id':thisId,
                 'action':'get_dependent_menu'
                },
                success: function (response) {
                //alert(response);
                console.log(oSelService);
                $('select[name="'+ oSelService +'"]').html(response);

                }
             });

            }

        });
    });
    </script>

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

And ajax.php

```<code>    <?php
    echo "<option value='Select Service'>Select Service (Pant)</option>";
    echo "<option value='12121211'>Iron</option>";

    ?>
</code>```

Body:
Select based on another select using PHP not working only when a new row is added.

For demo visit here (See steps for demo)

There are two rows when the page is loaded, they are working as wanted. (Service option is as per item option)

Click on the Add Row button, one more row will be added

The newly inserted row is not working. (Service select is not giving any options, as first two gives)

What I tried:

<?php require_once '../home.php' ?>
<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
        ob_clean();

        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
        if( $action && $id && !is_nan( $id ) ){

            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmt->bindParam(':irn',$id);
            $stmt->execute();
            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmtin->bindParam(':irn',$id);
            $stmtin->execute();
            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );

            if( $stmt->rowCount() > 0 ){
                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
                 }
            }
        }
        exit();
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<form method="post" action="invoice_form.php" id="item_sel">

      <input type="text" name="customer" value="" placeholder="Customer Name">

    Item
    Service
    Qty

      <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
            <?php

                //$sql='select * from `item` order by `Sr` asc;';
                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select>

      <select class="country" name="service1">
</select>
<input type="text" name="qty1" value="" placeholder="Quantity">

      <select name='item2' class='country'>
            <option>Select Item</option>
            <?php

                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select>

      <select class="country" name="service2">
</select>
<input type="text" name="qty2" value="" placeholder="Quantity">

        <button type="submit" name="btnsave" class="btn btn-default">
           Save
        </button>

    <input type="button" class="add-row" value="Add Row">
</form>

        <select name="nameitem" class="country">
                    <option>Select Item</option>
                    <?php
                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                        $stmt->execute();

                        if( $stmt->rowCount() > 0 ){
                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                            }
                        }
                    ?>
                </select>

        <select class="country" name="namewhat"></select>

        <input type="text" name="nameqty" value="" placeholder="Quantity" />

Body:
Your problem is because of this error - Uncaught TypeError: Cannot set property 'onchange' of null at HTMLDocument.bindEvents on line 243. You can see the same in inspect elements. This is because you are defining the function bindEvents for item3, which has not yet been added. Also this will work only in case of a single row being added. Changed your logic and used jquery a lot. I have commented out php part in your code and hard coded that stuff. Also created a php file that sends ajax response on select box change.

    <?php // require_once '../home.php' ?>
    <?php

    foreach($_POST as $key => $val) {
        echo "$key => $val <br>";
    }

        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
            echo "here <br>";
            ob_clean();
    //
    //        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
    //        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
    //        if( $action && $id && !is_nan( $id ) ){
    //
    //            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
    //            $stmt->bindParam(':irn',$id);
    //            $stmt->execute();
    //            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
    //            $stmtin->bindParam(':irn',$id);
    //            $stmtin->execute();
    //            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );
    //
    //            if( $stmt->rowCount() > 0 ){
    //                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
    //                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
    //                 }
    //            }
    //        }
            echo "<option value='Select Service'>Select Service (Pant)</option>";
            echo "<option value='12121211'>Iron</option>";
            exit();
        }
    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>

    </head>
    <body>
        <div class="container">
    <form method="post" action="invoice_form.php" id="item_sel">

        <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
       <tr>
        <td colspan="3">
          <input type="text" name="customer" value="" placeholder="Customer Name">
        </td>
      </tr>
      <tr>
        <th>Item</th>
        <th>Service</th>
        <th>Qty</th>

      </tr>

        <tr>
          <td>
          <select name='item1' class='country'>
                <option value="Select Item">Select Item</option>
                <?php

    //                //$sql='select * from `item` order by `Sr` asc;';
    //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                $stmt->execute();
    //
    //                if( $stmt->rowCount() > 0 ){
    //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                    }
    //                }

                ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>

    </select></td>

          <td><select class="country" name="service1">
    </select></td>
    <td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
        </tr>
        <tr>
          <td>
          <select name='item2' class='country'>
                <option>Select Item</option>
                <?php

    //
    //                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                $stmt->execute();
    //
    //                if( $stmt->rowCount() > 0 ){
    //                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                    }
    //                }

                ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>
    </select></td>

          <td><select class="country" name="service2">
    </select></td>
    <td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
        </tr>
        <tr>
            <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
            <span class="glyphicon glyphicon-save"></span> &nbsp; Save
            </button>
            </td>
        </tr>
    </table>
        <input type="button" class="add-row" value="Add Row">
    </form>
    <div id="markup_model" class="hide">
      <table>
        <tr>
          <td>
            <select name="nameitem" class="country">
                        <option>Select Item</option>
                        <?php
    //                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
    //                        $stmt->execute();
    //
    //                        if( $stmt->rowCount() > 0 ){
    //                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
    //                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
    //                            }
    //                        }
                        ?>

                            <option value='ZZ2017TF11A1'>Shirt</option>
                            <option value='ZZ2017TF11A2'>Pant</option>
                    </select>
          </td>
          <td>
            <select class="country" name="namewhat"></select>
          </td>
          <td>
            <input type="text" name="nameqty" value="" placeholder="Quantity" />
          </td>
        </tr>
      </table>
    </div>
    </div>
    <script src="js/jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
      var cont = 3;
      var qty = "qty";
      var item = "item";
      var what = "service";

      $(".add-row").click(function() {
        var nameqty = qty + cont;
        var nameitem = item + cont;
        var namewhat = what + cont;

        var markup = $('#markup_model tbody');

        $(markup).find('.country:eq(0)').attr('name', nameitem);
        $(markup).find('.country:eq(1)').attr('name', namewhat);
        $(markup).find('input').attr('name', nameqty);

        $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));

        cont++;
      });

        $('.container').on( 'change', '.country', function () {
            //console.log($(this).attr('name'));
            var oSelItem = $(this).attr('name');
            var lastChar = oSelItem.substr(oSelItem.length -1);
            var prevChar = oSelItem.substr(0, oSelItem.length-1);
            //console.log(prevChar);
            if(prevChar === "item") {
              var oSelService = "service" + lastChar;
              console.log(oSelItem + "  " + oSelService);
              console.log($(this).val());
              var thisId = $(this).val();
             $.ajax({
                type: 'post',
                url: 'ajax.php',
                data: {
                 'id':thisId,
                 'action':'get_dependent_menu'
                },
                success: function (response) {
                //alert(response);
                console.log(oSelService);
                $('select[name="'+ oSelService +'"]').html(response);

                }
             });

            }

        });
    });
    </script>

    </body>
    </html>

And ajax.php

    <?php
    echo "<option value='Select Service'>Select Service (Pant)</option>";
    echo "<option value='12121211'>Iron</option>";

    ?>


来源: stackexchange

问:
Spring data rest method not able to search on DbRef Id field
I am using mongodb and spring boot in my appliation. In Area collection city is DBRef but spring data rest method is unable to search using city's Id. It's returning empty JSON although for that city I have area's in my database.My Area collection and repository are as below.

```<code>@Document(collection = "area")
    public class Area  {

      private String name;

      private String areaCode;

      private String postalCode;

      private String latitude;

      private String longitude;

      private String category;

      @DBRef(lazy = false)
      private City city;

public interface AreaRepo extends MongoRepository<Area, String> {

  @RestResource(path = "byCityId")
  List<Area> findByCityId(@Param(value = "cityId") String cityId);
</code>```

Same kind of relationship in other collection is working file.

答:
You could add @Query annotation.

```<code>@Query("{ 'city': {'$ref': 'City', '$id': { '$oid': ?0 } } }")
List<Area> findByCityId(@Param(value = "cityId") String cityId);
</code>```

Or find directly with city object

```<code>City city = new City(cityId);
List<Area> findByCity(City city);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using mongodb and spring boot in my appliation. In Area collection city is DBRef but spring data rest method is unable to search using city's Id. It's returning empty JSON although for that city I have area's in my database.My Area collection and repository are as below.

@Document(collection = "area")
    public class Area  {

      private String name;

      private String areaCode;

      private String postalCode;

      private String latitude;

      private String longitude;

      private String category;

      @DBRef(lazy = false)
      private City city;

public interface AreaRepo extends MongoRepository<Area, String> {

  @RestResource(path = "byCityId")
  List<Area> findByCityId(@Param(value = "cityId") String cityId);

Same kind of relationship in other collection is working file.

Body:
You could add @Query annotation.

@Query("{ 'city': {'$ref': 'City', '$id': { '$oid': ?0 } } }")
List<Area> findByCityId(@Param(value = "cityId") String cityId);

Or find directly with city object

City city = new City(cityId);
List<Area> findByCity(City city);


问:
Finding the idNumber element from this below HTML code
```<code><div id="rightContent" style="display: inline-block; width: 700px; vertical-align: top;">
                <div>
                    <h1><em class="SomethingHeading">Something</em></h1>
                </div>

<div class="content scaffold-list" role="main">
    <h1>Search</h1>

    <form action="/SomethingArchiveUI/search/search" method="post">
        <table>
            <tbody>
            <tr>
                <td>ID/Registration Number:</td>
                <td>
                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>
                </td>
            </tr>
            <tr>
                <td>Client Name:</td>
                <td>
                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">
                </td>
            </tr>
            <tr>
                <td>Client Surname:</td>
                <td>
                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"><label for="dateRange"> Use date range?</label>
                </td>
            </tr>
            <tr>
                <td colspan="2"><p>From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker"></p></td>
            </tr>
            </tbody>
        </table>
        <div style="display: inline;">
            <div id="divSubmit">
                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">
            </div>
            <div id="divBusy" style="display: none;">
                Busy Searching...
            </div>
        </div>
    </form>

    <table id="customerIdentificationList" style="display: block;">

    </table>
    <div id="loadingMessage" style="display: none;">
        Loading. Please wait.
    </div>
</div>

            </div>
</code>```

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

```<code>driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();
</code>```

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

答: Use  : .//input[@id='idnumber']</p>

Body:
Something

Search

    <form action="/SomethingArchiveUI/search/search" method="post">

                ID/Registration Number:

                    <**input type="text" name="idNumber" maxlength="20" value="" id="idNumber"**>

                Client Name:

                    <input type="text" name="clientName" maxlength="50" value="" id="clientName">

                Client Surname:

                    <input type="text" name="clientSurname" maxlength="50" value="" id="clientSurname">

                    <input type="hidden" name="_dateRange"><input type="checkbox" name="dateRange" value="true" id="dateRange"> Use date range?

From: <input type="text" name="fromDate" value="" maxlength="10" id="fromDate" class="hasDatepicker"> To: <input type="text" name="toDate" value="" maxlength="10" id="toDate" class="hasDatepicker">

                <input type="submit" name="cmdSearch" class="buttons" value="Search" id="cmdSearch">

                Busy Searching...

    </form>

        Loading. Please wait.

I used this code below for logging into the Application, but similar code doesn't seem to work on this form above. I'm trying to find the 'idNumber' element:

driver.findElement(By.xpath("//*[@id='idnumber']")).sendKeys("Username");
driver.findElement(By.xpath("//*[@id=\'password\']")).sendKeys("Password");
driver.findElement(By.xpath("//*[@id=\'submit\']")).click();

The error i get is: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":

Looking forward to your responses.

Body: Use  : .//input[@id='idnumber']


问:
@UniqueConstraint with multiple columns not enforced when using bidirectional mapping
I have these 3 entities :

```<code>@Entity
class Resource {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "resource", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Element> elements;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "resource_id", nullable = false)
    List<Action> actions;
}

@Entity
@Table(name = "element", uniqueConstraints = @UniqueConstraint(name = "UK_ELEMENT_VALUE_FOR_RESOURCE", columnNames = { "value", "resource_id" }))
class Element {

    String value;

    @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE })
    Resource resource;
}

@Entity
@Table(name = "action", uniqueConstraints = @UniqueConstraint(name = "UK_ACTION_VALUE_FOR_RESOURCE", columnNames = { "value", "resource_id" }))
class Action {

    String value;
    // no reference to Resource
}
</code>```

I have written these two tests :

When I persist a Resource with 2 Actions with the same value, I'm greeted with a PersistenceException with an hibernate ConstraintViolationException as a cause which is expected:

```<code>assertEquals(ConstraintViolationException.class,
    assertThrows(PersistenceException.class, () -> {
        Resource res = newResource("res");
        res.setActions(Arrays.asList(new Action("value"), new Action("value")));
        dao.create(res);
    }).getCause().getClass());
</code>```

When I persist a Resource with 2 Elements with the same value, the creation succeeds and no Exception is thrown.

```<code>assertEquals(ConstraintViolationException.class,
    assertThrows(PersistenceException.class, () -> {
        Resource res = newResource("res");
        res.setElements(Arrays.asList(new Element("value"), new Element("value")));
        dao.create(res);
    }).getCause().getClass());
</code>```

If I replace the bidirectional relation with a unidirectional one, my test works.
I don't need the bidirectional relation for Action but I need it in Element.

What am I doing wrong there ? I'm a bit lost.

答:
I got it to work by calling myself the bidirectional setter in Resource class :

```<code>@PrePersist
void setBidirectionalMappingsOnPersist() {
    if (elements != null) {
        elements.forEach(element -> element.setResource(this));
    }
}
</code>```

I was thinking that adding the mappedBy attribute in the @OneToMany, the persistence provider would handle the bidirectional mapping.

Body:
I have these 3 entities :

@Entity
class Resource {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "resource", cascade = CascadeType.ALL, orphanRemoval = true)
    List<Element> elements;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "resource_id", nullable = false)
    List<Action> actions;
}

@Entity
@Table(name = "element", uniqueConstraints = @UniqueConstraint(name = "UK_ELEMENT_VALUE_FOR_RESOURCE", columnNames = { "value", "resource_id" }))
class Element {

    String value;

    @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE })
    Resource resource;
}

@Entity
@Table(name = "action", uniqueConstraints = @UniqueConstraint(name = "UK_ACTION_VALUE_FOR_RESOURCE", columnNames = { "value", "resource_id" }))
class Action {

    String value;
    // no reference to Resource
}

I have written these two tests :

When I persist a Resource with 2 Actions with the same value, I'm greeted with a PersistenceException with an hibernate ConstraintViolationException as a cause which is expected:

assertEquals(ConstraintViolationException.class,
    assertThrows(PersistenceException.class, () -> {
        Resource res = newResource("res");
        res.setActions(Arrays.asList(new Action("value"), new Action("value")));
        dao.create(res);
    }).getCause().getClass());

When I persist a Resource with 2 Elements with the same value, the creation succeeds and no Exception is thrown.

assertEquals(ConstraintViolationException.class,
    assertThrows(PersistenceException.class, () -> {
        Resource res = newResource("res");
        res.setElements(Arrays.asList(new Element("value"), new Element("value")));
        dao.create(res);
    }).getCause().getClass());

If I replace the bidirectional relation with a unidirectional one, my test works.
I don't need the bidirectional relation for Action but I need it in Element.

What am I doing wrong there ? I'm a bit lost.

Body:
I got it to work by calling myself the bidirectional setter in Resource class :

@PrePersist
void setBidirectionalMappingsOnPersist() {
    if (elements != null) {
        elements.forEach(element -> element.setResource(this));
    }
}

I was thinking that adding the mappedBy attribute in the @OneToMany, the persistence provider would handle the bidirectional mapping.


问:
SQL Query to add a new column after an existing column in SQL Server 2005
I need a SQL query which add a new column after an existing column, so the column will be added in a specific order.

Please suggest me if any ALTER query which do that.

答:
ALTER won't do it because column order does not matter for storage or querying

If SQL Server, you'd have to use the SSMS Table Designer to arrange your columns, which can then generate a script which drops and recreates the table

Edit Jun 2013

Cross link to my answer here: Performance / Space implications when ordering SQL Server columns?


问:
Background-size cover/center not working
I'm trying to center the background image to the div using background-size: cover and background-size: contain, but it does not work. I need to display background images inside HTML tags and use background-size in the css file, this is the code:

.container {
    width: 200px;
    height: 260px;
    position: relative;
    margin: 0 auto 40px;
    margin-left: 20px;
    display: inline-block;
}
.main{
    border: 1px solid black;
    background-color: #A6A6A6;
}
.card {
    width: 100%;
    height: 100%;
    position: absolute;
    border: 2px solid white;
}
.card div {
    height: 100%;
    width: 100%;
    color: white;
    text-align: center;
    position: absolute;
}
.card .front {
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body style="background-image:url(https://s3.amazonaws.com/Syntaxxx/background-gold-bokeh.jpg);">
<div class="main">
  <section class="container">
      <div class="card">
          <div class="front" style="background-image: url('http://www.mobygames.com/images/covers/l/403626-injustice-2-playstation-4-front-cover.png');">
          </div>
          <div class="back">1</div>
      </div>
  </section>
  <section class="container">
      <div class="card">
          <div class="front" style="background-image: url('http://www.mobygames.com/images/covers/l/403651-the-surge-playstation-4-front-cover.jpg');">
          </div>
          <div class="back">2</div>
      </div>
  </section>
</div>

</body></code>```

答:
Your .card .front has a style of background-repeat which you've given too many properties to.

the center center needs to be given to background-position

```<code>.card .front {
     background-position: center center;
     background-repeat: no-repeat;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
 }
</code>```

With CSS and most other dimensions you use X then Y then Z (No Z apart from Z-index)

Background-size will enlarge the image until the entire div is full.

What you're looking for is background-size: contain. This will display the full image in any container. then add the center center

```<code>.card .front {
    background-image: url(https://s3.amazonaws.com/Syntaxxx/background-gold-bokeh.jpg);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
 }
</code>```

Body:
I'm trying to center the background image to the div using background-size: cover and background-size: contain, but it does not work. I need to display background images inside HTML tags and use background-size in the css file, this is the code:

.container {
    width: 200px;
    height: 260px;
    position: relative;
    margin: 0 auto 40px;
    margin-left: 20px;
    display: inline-block;
}
.main{
    border: 1px solid black;
    background-color: #A6A6A6;
}
.card {
    width: 100%;
    height: 100%;
    position: absolute;
    border: 2px solid white;
}
.card div {
    height: 100%;
    width: 100%;
    color: white;
    text-align: center;
    position: absolute;
}
.card .front {
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
}

1

2

Body:
Your .card .front has a style of background-repeat which you've given too many properties to.

the center center needs to be given to background-position

.card .front {
     background-position: center center;
     background-repeat: no-repeat;
     -webkit-background-size: cover;
     -moz-background-size: cover;
     -o-background-size: cover;
     background-size: cover;
 }

With CSS and most other dimensions you use X then Y then Z (No Z apart from Z-index)

Background-size will enlarge the image until the entire div is full.

What you're looking for is background-size: contain. This will display the full image in any container. then add the center center

.card .front {
    background-image: url(https://s3.amazonaws.com/Syntaxxx/background-gold-bokeh.jpg);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    -webkit-background-size: contain;
    -moz-background-size: contain;
    -o-background-size: contain;
 }


问:
No connection could be made because the target machine actively refused it. wordpress

Warning: mysql_connect() [function.mysql-connect]: [2002] No connection could be made because the target machine actively (trying to connect via tcp://localhost:3306) in D:\Hosting\8224951\html\word\wp-includes\wp-db.php on line 1141

Warning: mysql_connect() [function.mysql-connect]: No connection could be made because the target       machine actively refused it. in D:\Hosting\8224951\html\word\wp-includes\wp-db.php on line 1141

I always get this error while trying to connect to my wordpress website.
I've searched everywhere and can't seem to find a solution.

here's my wp_db file contains on like 1141.

```<code>    if ( WP_DEBUG ) {
        $this->dbh = mysql_connect(':/Applications/MAMP/tmp/mysql/mysql.sock', 'ShiftBusinessSol', '123456!');
    } else {
        $this->dbh = mysql_connect(':/Applications/MAMP/tmp/mysql/mysql.sock', 'ShiftBusinessSol', '123456!');
    }
</code>```

as for config i have this:

```<code> /** The name of the database for WordPress */
 define('DB_NAME', 'ShiftBusinessSol');
/** MySQL database username */
 define('DB_USER', 'ShiftBusinessSol');
/** MySQL database password */
define('DB_PASSWORD', '123456!');
/** MySQL hostname */
define('DB_HOST', '127.0.0.1:3306');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
</code>```

答: Check from your command line is your database is listening to any port or not. </p>

Body:
Warning: mysql_connect() [function.mysql-connect]: [2002] No connection could be made because the target machine actively (trying to connect via tcp://localhost:3306) in D:\Hosting\8224951\html\word\wp-includes\wp-db.php on line 1141

Warning: mysql_connect() [function.mysql-connect]: No connection could be made because the target       machine actively refused it. in D:\Hosting\8224951\html\word\wp-includes\wp-db.php on line 1141

I always get this error while trying to connect to my wordpress website.
I've searched everywhere and can't seem to find a solution.

here's my wp_db file contains on like 1141.

    if ( WP_DEBUG ) {
        $this->dbh = mysql_connect(':/Applications/MAMP/tmp/mysql/mysql.sock', 'ShiftBusinessSol', '123456!');
    } else {
        $this->dbh = mysql_connect(':/Applications/MAMP/tmp/mysql/mysql.sock', 'ShiftBusinessSol', '123456!');
    }

as for config i have this:

 /** The name of the database for WordPress */
 define('DB_NAME', 'ShiftBusinessSol');
/** MySQL database username */
 define('DB_USER', 'ShiftBusinessSol');
/** MySQL database password */
define('DB_PASSWORD', '123456!');
/** MySQL hostname */
define('DB_HOST', '127.0.0.1:3306');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');


问:
Why is there no padding in the structure for only "char" type members?
I have declared only char type members in the structure.

```<code>#include <stdio.h>

struct st
{
    char c1;
    char c2;
    char c3;
    char c4;
    char c5;
};

int main() {
    struct st s;
    printf("%zu\n", sizeof(s));
    return 0;
}
</code>```

Output: [Live Demo]

```<code>5
</code>```

So, why is there no padding in the structure for only char type members?

答:
Some types, when correctly aligned, have better performance/stability etc. When there are other variables behind a variable of such a type that makes its starting position "not well-aligned", the compiler may decide to add padding so the alignment goes well. This is all optional, and of course has no necessity when all you have are bytes (char).

You will more likely observe padding if you writr a structure like this:

```<code>struct pad{
    int8_t a;
    int64_t b;
};
assert(sizeof(struct pad) == 16);
</code>```

whose memory layout should look like this:

```<code>|---|-------|---------|
| 1 |   7   |    8    |
|---|-------|---------|
byte|padding|64-bit int
</code>```

Then again, there's no need to align bytes since they are the mininal unit of storage.

Body:
I have declared only char type members in the structure.

#include <stdio.h>

struct st
{
    char c1;
    char c2;
    char c3;
    char c4;
    char c5;
};

int main() {
    struct st s;
    printf("%zu\n", sizeof(s));
    return 0;
}

Output: [Live Demo]

5

So, why is there no padding in the structure for only char type members?

Body:
Some types, when correctly aligned, have better performance/stability etc. When there are other variables behind a variable of such a type that makes its starting position "not well-aligned", the compiler may decide to add padding so the alignment goes well. This is all optional, and of course has no necessity when all you have are bytes (char).

You will more likely observe padding if you writr a structure like this:

struct pad{
    int8_t a;
    int64_t b;
};
assert(sizeof(struct pad) == 16);

whose memory layout should look like this:

|---|-------|---------|
| 1 |   7   |    8    |
|---|-------|---------|
byte|padding|64-bit int

Then again, there's no need to align bytes since they are the mininal unit of storage.


问:
Python - reordering items in list by moving some items to the front while keeping the rest in the same order
I am trying to reorder items in a list in a way illustrated by the following example:

Suppose the list before reordering is:

```<code>list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

I want to implement a method called reorder_list(list, custom_order) such that:

```<code>list1 = reorder_list(list1, [3, 6, 12, 9])
print(list1)

Out: [3, 6, 9, 1, 2, 4, 5, 7, 8, 10]
</code>```

Explanation: [3, 6, 12, 9] is a custom order I am specifying. 12 is not in  list1 so it will be ignored. 3,6,9 are in list1, so they get moved to the front of the list and their order is the same as in [3, 6, 12, 9]. The remaining items in list1 are after 3,6,9 and in the original order.

Is there is an easier way (and a Pythonic way) than implementing the C-like loop code. For my purpose I care more about code simplicity than performance.

答:
```<code>def reorder_list(items, early):
    moved = [item for item in early if item in items]
    remain = [item for item in items if item not in moved]
    return moved + remain
</code>```

This is really the same algorithm as Gireesh and Stephen Rauch wrote. Gireesh's version is written as it would be before list comprehensions, while Stephen's uses sets for faster lookups (but converts both input lists to sets; one should suffice) and extends with a generator expression instead of allocating a second list.

One thing of note is that we've assumed items are unique within the lists. Both in and set expect this.

00sdf0's answer uses a very different algorithm that might make sense in Haskell, with its lazy evaluation and tail call optimization, but in this case seems neither easily understood nor performant. It can be more clearly rewritten using slices:

```<code>def reorder_list(items, early):
    result = list(items)
    for move in reversed(early):
        try:
            place = result.index(move)
            result = [result[place]] + result[:place] + result[place+1:]
        except ValueError:
            pass   # this item wasn't in the list
</code>```

This does allocate more lists, effectively shallow copying the list twice per moved item. Using islice instead of slice produced lazy evaluation that avoided one of those copies.

Body:
I am trying to reorder items in a list in a way illustrated by the following example:

Suppose the list before reordering is:

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to implement a method called reorder_list(list, custom_order) such that:

list1 = reorder_list(list1, [3, 6, 12, 9])
print(list1)

Out: [3, 6, 9, 1, 2, 4, 5, 7, 8, 10]

Explanation: [3, 6, 12, 9] is a custom order I am specifying. 12 is not in  list1 so it will be ignored. 3,6,9 are in list1, so they get moved to the front of the list and their order is the same as in [3, 6, 12, 9]. The remaining items in list1 are after 3,6,9 and in the original order.

Is there is an easier way (and a Pythonic way) than implementing the C-like loop code. For my purpose I care more about code simplicity than performance.

Body:
def reorder_list(items, early):
    moved = [item for item in early if item in items]
    remain = [item for item in items if item not in moved]
    return moved + remain

This is really the same algorithm as Gireesh and Stephen Rauch wrote. Gireesh's version is written as it would be before list comprehensions, while Stephen's uses sets for faster lookups (but converts both input lists to sets; one should suffice) and extends with a generator expression instead of allocating a second list.

One thing of note is that we've assumed items are unique within the lists. Both in and set expect this.

00sdf0's answer uses a very different algorithm that might make sense in Haskell, with its lazy evaluation and tail call optimization, but in this case seems neither easily understood nor performant. It can be more clearly rewritten using slices:

def reorder_list(items, early):
    result = list(items)
    for move in reversed(early):
        try:
            place = result.index(move)
            result = [result[place]] + result[:place] + result[place+1:]
        except ValueError:
            pass   # this item wasn't in the list

This does allocate more lists, effectively shallow copying the list twice per moved item. Using islice instead of slice produced lazy evaluation that avoided one of those copies.


问:
Fetch the pdf file from every 2nd row of 2nd column of html table in python through selenium
I am new to web scraping. I need to fetch the pdf file from every 2nd row of 2nd column of below HTML table code:

```<code><table class="tablebg" width="100%">
    <tbody>
        <tr>
            <th colspan="4" align="left">Nov 09, 2017</th></tr>
                <tr>
                    <td style="word-wrap:break-word;width:450;">
                        <a class="link2" href="FS_Notification.aspx?Id=11162&fn=5&Mode=0">Risk Management and Inter-Bank Dealings – Simplified Hedging Facility</a>
                    </td>
                    <td nowrap="" colspan="3">
                        <a target="_blank" href="http://rbidocs.rbi.org.in/rdocs/notification/PDFs/APD118ED4C6E75FAC43A0BA5A738C21F8A8A7.PDF"><img src="../Images/pdf.gif" border="0" align="bsmiddle"></a>
                        97 kb
                    </td>
                </tr>
</code>```

I have tried below code but its not picking up the 2nd column of 2nd row:

```<code>from selenium import webdriver

chrome_path = r"C:/chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
browser = driver.get("https://rbi.org.in/")

driver.find_element_by_xpath("""//*[@id="FEMA"]/a""").click()
driver.find_element_by_xpath("""//*[@id="FEMANotifications"]""").click()
result = driver.find_elements_by_xpath("//table//tr")

for rows in result:
    second_row = result.__getitem__(2)
    second_col = second_row.find_elements_by_partial_link_text("http://")
    print(second_col)
</code>```

Please suggest any help?

答:
To print every 2nd row of 2nd column of html table you can use the following line of code :</p>

```<code>print(driver.find_elements_by_xpath("//table[@class='tablebg']//tr//td/a[contains(@href,'http://rbidocs.rbi.org.in/rdocs/notification/PDFs')]").get_attribute('href'))
</code>```

Body:
I am new to web scraping. I need to fetch the pdf file from every 2nd row of 2nd column of below HTML table code:

            Nov 09, 2017

                        Risk Management and Inter-Bank Dealings – Simplified Hedging Facility

                        97 kb

I have tried below code but its not picking up the 2nd column of 2nd row:

from selenium import webdriver

chrome_path = r"C:/chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
browser = driver.get("https://rbi.org.in/")

driver.find_element_by_xpath("""//*[@id="FEMA"]/a""").click()
driver.find_element_by_xpath("""//*[@id="FEMANotifications"]""").click()
result = driver.find_elements_by_xpath("//table//tr")

for rows in result:
    second_row = result.__getitem__(2)
    second_col = second_row.find_elements_by_partial_link_text("http://")
    print(second_col)

Please suggest any help?

Body:
To print every 2nd row of 2nd column of html table you can use the following line of code :

print(driver.find_elements_by_xpath("//table[@class='tablebg']//tr//td/a[contains(@href,'http://rbidocs.rbi.org.in/rdocs/notification/PDFs')]").get_attribute('href'))


问:
how to embed one pod configuration to another pod
I comparing the scenario of communication between two pods with  container --link.I had a rabbit mq container and an application that uses it.

Now, how can we do the same in kubernetes where an application is dependent on a rabbitmq.

Below is my code for replicationcontroller of my myapplication which is apache airavata:

airavata-all-rc.yml

```<code>apiVersion: v1

kind: ReplicationController

metadata:

    name: airavata-all-rc

    labels:

      app : airavata-all-sc
spec:

  replicas: 5

  selector:

    app: airavata-all

  template:

    metadata:

      labels:

        app: airavata-all

    spec:

      containers:

      - name: airavata-all

        image: satyamsah/airavata-all

        ports:

        - containerPort: 8080
</code>```

Below is my code for service version the same myapplication which is apache airavata:

airavata-all-svc.yml

```<code>apiVersion: v1

kind: Service

metadata:

  name: airavata-svc

  labels:

    app: airavata-all-svc

spec:

  type: NodePort

  ports:

  - port: 8080

    nodePort: 30002

    protocol: TCP

  selector:

    app: airavata-all
</code>```

Below is the rabbitmq dependency:rmq-rc.yml

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: rmq-rc
spec:
  selector:
    app: rmq
  replicas: 1
  template:
    metadata:
      labels:
        app: rmq
    spec:
      containers:
      - name: rmq
        image: rabbitmq:3-management
        env:
        - name: RABBITMQ_DEFAULT_USER
          value: "airavata"
        - name: RABBITMQ_DEFAULT_PASS
          value: "airavata"
        ports:
        - containerPort: 5672
        - containerPort: 15672
</code>```

How to make these two apps communicate to each other?

答:
Expose the RabbitMQ dependency as a Kubernetes Service, this will give it a consistent IP address. You can use that IP from your other pods, or use the service's DNS name in the format: my-svc.my-namespace.svc.cluster.local.

On a side note, consider migrating from Replication Controller to ReplicaSet, or Deployment. See: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/

Body:
I comparing the scenario of communication between two pods with  container --link.I had a rabbit mq container and an application that uses it.

Now, how can we do the same in kubernetes where an application is dependent on a rabbitmq.

Below is my code for replicationcontroller of my myapplication which is apache airavata:

airavata-all-rc.yml

apiVersion: v1

kind: ReplicationController

metadata:

    name: airavata-all-rc

    labels:

      app : airavata-all-sc
spec:

  replicas: 5

  selector:

    app: airavata-all

  template:

    metadata:

      labels:

        app: airavata-all

    spec:

      containers:

      - name: airavata-all

        image: satyamsah/airavata-all

        ports:

        - containerPort: 8080

Below is my code for service version the same myapplication which is apache airavata:

airavata-all-svc.yml

apiVersion: v1

kind: Service

metadata:

  name: airavata-svc

  labels:

    app: airavata-all-svc

spec:

  type: NodePort

  ports:

  - port: 8080

    nodePort: 30002

    protocol: TCP

  selector:

    app: airavata-all

Below is the rabbitmq dependency:rmq-rc.yml

apiVersion: v1
kind: ReplicationController
metadata:
  name: rmq-rc
spec:
  selector:
    app: rmq
  replicas: 1
  template:
    metadata:
      labels:
        app: rmq
    spec:
      containers:
      - name: rmq
        image: rabbitmq:3-management
        env:
        - name: RABBITMQ_DEFAULT_USER
          value: "airavata"
        - name: RABBITMQ_DEFAULT_PASS
          value: "airavata"
        ports:
        - containerPort: 5672
        - containerPort: 15672

How to make these two apps communicate to each other?


问:
React - Refactor out eval function and improve code quality
I have just started playing with React today and built a simple Calculator app.
Would someone please be able to advise on steps I could take to improve my code.

Ideally, I want ideas on how to properly use state, and how to refactor out my use of the eval function.

Would appreciate any feedback on how you would have done this differently aswell :)

import React from 'react';

class Calculator extends React.Component {
  constructor(props){
      super(props);
      this.state = {
        prev: [],
        total: []
      };
  }

  inputDigit(int) {

    var newArr = this.state.total.slice();
    newArr.push(int);
    this.setState({total: newArr});

  }

  addition(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "+");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  minus(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "-");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  divide(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "/");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;

  }

  multiply(prevNum) {

    var store = this.arrToNum(prevNum);
    var newArr = this.state.prev.slice();
    newArr.push(store , "*");
    var string = newArr.join(" ");
    this.setState({total:[] , prev: [string]});

    return prevNum;
  }

  clearInput() {

    this.setState({total:[],prev:[]});

  }

  sum(currNum) {

    var store = this.arrToNum(currNum);
    var newArr = this.state.prev.slice();
    newArr.push(store);
    console.log(newArr.join(" "));
    var sum = eval(newArr.join(" "));

    this.setState({total:[sum]});

  }

  arrToNum(arr) {

    var test = Number(arr.join(''));

    return test;

  }

  makePretty(num) {

    var newNum = this.arrToNum(num);
    var formatNum = newNum.toLocaleString();

    return formatNum;

  }

  render() {
    return(

{this.makePretty(this.state.total)}

            <button className="square" onClick={() => this.inputDigit(7)}>7</button>
            <button className="square" onClick={() => this.inputDigit(8)}>8</button>
            <button className="square" onClick={() => this.inputDigit(9)}>9</button>
            <button className="square" onClick={() => this.addition(this.state.total)}>+</button>

            <button className="square" onClick={() => this.inputDigit(4)}>4</button>
            <button className="square" onClick={() => this.inputDigit(5)}>5</button>
            <button className="square" onClick={() => this.inputDigit(6)}>6</button>
            <button className="square" onClick={() => this.minus(this.state.total)}>-</button>

            <button className="square" onClick={() => this.inputDigit(1)}>1</button>
            <button className="square" onClick={() => this.inputDigit(2)}>2</button>
            <button className="square" onClick={() => this.inputDigit(3)}>3</button>
            <button className="square" onClick={() => this.multiply(this.state.total)}>*</button>

            <button className="square" onClick={() => this.inputDigit(0)}>0</button>
            <button className="square" onClick={() => this.inputDigit(".")}>.</button>
            <button className="square" onClick={() => this.sum(this.state.total)}>=</button>
            <button className="square" onClick={() => this.divide(this.state.total)}>/</button>

            <button className="square full" onClick={() => this.clearInput()}>CLEAR</button>

    );
  }
}

export default Calculator;```

答:
And that's another code review...    </p>

```<code>import React from 'react'

class Calculator extends React.Component {
  state = {
    prev: [],
    total: []
  }

  inputDigit(int) {
    let {state} = this.state
    this.setState({
      total: [...total, int]
    })
  }

  action(prevNum, symbol) {
    let store = Number(prevNum.join(''))
    let {prev} = this.state
    let string = [...prev, store, symbol].join(' ')
    this.setState({total: [], prev: [str]})
    return prevNum
  }

  clearInput() {
    this.setState({total: [], prev: []})
  }

  sum(currNum) {
    let store = Number(currNum.join(''))
    let {prev} = this.state
    let sum = eval([...prev, store].join(' '))
    this.setState({total: [sum]})
  }

  makePretty(num) {
    return Number(num.join('')).toLocaleString()
  }
  renderItem(value, onClick) {
    if (!onClick) onClick = () => this.inputDigit(value)
    return (
      <button className="square" onClick={onclick}>
        {value}
      </button>
    )
  }
  render() {
    return (
      <div className="Calculator">
        <div className="Screen">
          <p>{this.makePretty(this.state.total)}</p>
        </div>
        <div className="KeyPad">
          <div className="row">
            {[
              [7],
              [8],
              [9],
              ['+', () => this.action(this.state.total, '+')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [4],
              [5],
              [6],
              ['-', () => this.action(this.state.total, '-')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [1],
              [2],
              [3],
              ['*', () => this.action(this.state.total, '*')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [0],
              ['.'],
              ['='],
              ['/', () => this.action(this.state.total, '/')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            <button className="square full" onClick={() => this.clearInput()}>
              CLEAR
            </button>
          </div>
        </div>
      </div>
    )
  }
}
</code>```

Body:
And that's another code review...

import React from 'react'

class Calculator extends React.Component {
  state = {
    prev: [],
    total: []
  }

  inputDigit(int) {
    let {state} = this.state
    this.setState({
      total: [...total, int]
    })
  }

  action(prevNum, symbol) {
    let store = Number(prevNum.join(''))
    let {prev} = this.state
    let string = [...prev, store, symbol].join(' ')
    this.setState({total: [], prev: [str]})
    return prevNum
  }

  clearInput() {
    this.setState({total: [], prev: []})
  }

  sum(currNum) {
    let store = Number(currNum.join(''))
    let {prev} = this.state
    let sum = eval([...prev, store].join(' '))
    this.setState({total: [sum]})
  }

  makePretty(num) {
    return Number(num.join('')).toLocaleString()
  }
  renderItem(value, onClick) {
    if (!onClick) onClick = () => this.inputDigit(value)
    return (
      <button className="square" onClick={onclick}>
        {value}
      </button>
    )
  }
  render() {
    return (
      <div className="Calculator">
        <div className="Screen">
          <p>{this.makePretty(this.state.total)}</p>
        </div>
        <div className="KeyPad">
          <div className="row">
            {[
              [7],
              [8],
              [9],
              ['+', () => this.action(this.state.total, '+')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [4],
              [5],
              [6],
              ['-', () => this.action(this.state.total, '-')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [1],
              [2],
              [3],
              ['*', () => this.action(this.state.total, '*')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            {[
              [0],
              ['.'],
              ['='],
              ['/', () => this.action(this.state.total, '/')]
            ].map(([value, _function]) => this.renderItem(value, _function))}
          </div>
          <div className="row">
            <button className="square full" onClick={() => this.clearInput()}>
              CLEAR
            </button>
          </div>
        </div>
      </div>
    )
  }
}