问:
How to show a message after check validate of checkbox button?
I am using JavaScript to check Validate. The above input items I use required to check validate. In the check bank section of the checkbox field I have used JavaScript to check validation of the form . How do I show a message when the validation is complete? I have tried several solutions but it doesn't seem to work. This is my code

function checkbox() {
   if (document.getElementById("tab-1").checked) {
      document.getElementById("myCheck").required = true;
      document.getElementById("deadline").required = true;
      document.getElementById("Desired_payment_date").required = true;
      document.getElementById("Bank_transfer_destination").required = true;
       return false;
    }
    else if (document.getElementById("tab-2").checked) {
      document.getElementById("myCheck").required = false;
      document.getElementById("AccountTransfer").required = true;
      return false;
    }
   return true;
 }

 function done(){
   if(checkbox()==true){
      alert("done")
   }
 }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, tr, th,td {
  border: 2px solid #dfd7ca;
}</code>```

         <input type="checkbox" id="tab-1"  name="one" value="✔" style="height:20px;width:20px;margin-right:10px;" >Bank transfer
         <input type="checkbox" id="tab-2" 　name="two" value="✔"style="height:20px;width:20px;margin-right:10px;"  >Account transfer

      </script>

                deadline
               <select class="" name="deadline" id="deadline" class="form-select"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                  <option value="" selected></option>
                  <option value="20">20</option>
                  <option value="30">30</option>
               </select>

               Desired payment date
               <select class="Desired_payment_date" id="Desired_payment_date" name="Desired_payment_date" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                  <option value="" selected></option>
                  <option value="20">20</option>
                  <option value="21">21</option>
                  <option value="22">22</option>
                  <option value="23">23</option>
                  <option value="24">24</option>
                  <option value="25">25</option>
                  <option value="26">26</option>
                  <option value="27">27</option>
                  <option value="28">28</option>
                  <option value="29">29</option>
               </select>

               Bank
               <select class="bank" name="Bank_transfer_destination" id="Bank_transfer_destination"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;">
                  <option value="" selected></option>
                  <option value="福井銀行">A</option>
                  <option value="北陸銀行">B</option>
                  <option value="敦賀信用金庫">C</option>
                  <option value="商工中金">D</option>
                  <option value="滋賀銀行">E</option>
                  <option value="三菱UFG銀行">F</option>
               </select>

            <input type="checkbox" style="height:20px;width:20px;margin-right:10px;" 　 class="form-check-input" 　id="flexCheckChecked"  id="myCheck" name="Checkbox_value"  value="✔振込手数料の負担に同意します。">
            I agree to bear the transfer fee.。

               Deadline
               <select class="" name="AccountTransfer" id="AccountTransfer" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                  <option value="" selected></option>
                  <option value="20日">20日</option>
                  <option value="末日">末日</option>
               </select>

<button onclick="checkbox()"  id="btn" type="submit" name="input" class="btn btn-primary btn-block">Send</button>```

答:
You can check the DOM attribute select.options.selectedIndex to check if the <select> elements are selected.

let button = document.getElementById('btn');
let deadline = document.getElementById("deadline");
let desiredPD = document.getElementById("Desired_payment_date");
let bankTD = document.getElementById("Bank_transfer_destination");
let myCkeck = document.getElementById("myCheck");
let accountT = document.getElementById("AccountTransfer");

/* In this solution, when the button is clicked, <form> control is done. */
button.addEventListener('click', function(event) {
  if(isValid()){
    alert("done");
  }
  else{
    alert("failed");
  }
});

/* This method returns true if validation is successful. */
function isValid()
{
  if (document.getElementById("tab-1").checked) {
    let result = (deadline.selectedIndex != 0) ? true : false;
    result &= (deadline.selectedIndex != 0) ? true : false;
    result &= (desiredPD.selectedIndex != 0) ? true : false;
    result &= (bankTD.selectedIndex != 0) ? true : false;
    result &= (myCkeck.selectedIndex != 0) ? true : false;
    return result;
  }
  else if (document.getElementById("tab-2").checked) {
    return (accountT.selectedIndex != 0) ? true : false;
  }
  else
    return false;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, tr, th,td{
  border: 2px solid #dfd7ca;
}</code>```

            <input type="checkbox" id="tab-1"  name="one" value="✔" style="height:20px;width:20px;margin-right:10px;" >Bank transfer
            <input type="checkbox" id="tab-2" 　name="two" value="✔"style="height:20px;width:20px;margin-right:10px;"  >Account transfer

        </script>

                     deadline
                    <select class="" name="deadline" id="deadline" class="form-select"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                        <option value="" selected></option>
                        <option value="20">20</option>
                        <option value="30">30</option>
                    </select>

                    Desired payment date
                    <select class="Desired_payment_date" id="Desired_payment_date" name="Desired_payment_date" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                        <option value="" selected></option>
                        <option value="20">20</option>
                        <option value="21">21</option>
                        <option value="22">22</option>
                        <option value="23">23</option>
                        <option value="24">24</option>
                        <option value="25">25</option>
                        <option value="26">26</option>
                        <option value="27">27</option>
                        <option value="28">28</option>
                        <option value="29">29</option>
                    </select>

                    Bank
                    <select class="bank" name="Bank_transfer_destination" id="Bank_transfer_destination"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;">
                        <option value="" selected></option>
                        <option value="福井銀行">A</option>
                        <option value="北陸銀行">B</option>
                        <option value="敦賀信用金庫">C</option>
                        <option value="商工中金">D</option>
                        <option value="滋賀銀行">E</option>
                        <option value="三菱UFG銀行">F</option>
                    </select>

                <input type="checkbox" style="height:20px;width:20px;margin-right:10px;" 　 class="form-check-input" id="myCheck" name="Checkbox_value"  value="✔振込手数料の負担に同意します。">
                I agree to bear the transfer fee.。

                    Deadline
                    <select class="" name="AccountTransfer" id="AccountTransfer" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                        <option value="" selected></option>
                        <option value="20日">20日</option>
                        <option value="末日">末日</option>
                    </select>

<button id="btn" type="submit" name="input" class="btn btn-primary btn-block">Send</button>```

Body:
I am using JavaScript to check Validate. The above input items I use required to check validate. In the check bank section of the checkbox field I have used JavaScript to check validation of the form . How do I show a message when the validation is complete? I have tried several solutions but it doesn't seem to work. This is my code

function checkbox() {
   if (document.getElementById("tab-1").checked) {
      document.getElementById("myCheck").required = true;
      document.getElementById("deadline").required = true;
      document.getElementById("Desired_payment_date").required = true;
      document.getElementById("Bank_transfer_destination").required = true;
       return false;
    }
    else if (document.getElementById("tab-2").checked) {
      document.getElementById("myCheck").required = false;
      document.getElementById("AccountTransfer").required = true;
      return false;
    }
   return true;
 }

 function done(){
   if(checkbox()==true){
      alert("done")
   }
 }

table, tr, th,td {
  border: 2px solid #dfd7ca;
}

         <input type="checkbox" id="tab-1"  name="one" value="✔" style="height:20px;width:20px;margin-right:10px;" >Bank transfer
         <input type="checkbox" id="tab-2" 　name="two" value="✔"style="height:20px;width:20px;margin-right:10px;"  >Account transfer

      </script>

                deadline
               <select class="" name="deadline" id="deadline" class="form-select"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                  <option value="" selected></option>
                  <option value="20">20</option>
                  <option value="30">30</option>
               </select>

               Desired payment date
               <select class="Desired_payment_date" id="Desired_payment_date" name="Desired_payment_date" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                  <option value="" selected></option>
                  <option value="20">20</option>
                  <option value="21">21</option>
                  <option value="22">22</option>
                  <option value="23">23</option>
                  <option value="24">24</option>
                  <option value="25">25</option>
                  <option value="26">26</option>
                  <option value="27">27</option>
                  <option value="28">28</option>
                  <option value="29">29</option>
               </select>

               Bank
               <select class="bank" name="Bank_transfer_destination" id="Bank_transfer_destination"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;">
                  <option value="" selected></option>
                  <option value="福井銀行">A</option>
                  <option value="北陸銀行">B</option>
                  <option value="敦賀信用金庫">C</option>
                  <option value="商工中金">D</option>
                  <option value="滋賀銀行">E</option>
                  <option value="三菱UFG銀行">F</option>
               </select>

            <input type="checkbox" style="height:20px;width:20px;margin-right:10px;" 　 class="form-check-input" 　id="flexCheckChecked"  id="myCheck" name="Checkbox_value"  value="✔振込手数料の負担に同意します。">
            I agree to bear the transfer fee.。

               Deadline
               <select class="" name="AccountTransfer" id="AccountTransfer" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                  <option value="" selected></option>
                  <option value="20日">20日</option>
                  <option value="末日">末日</option>
               </select>

<button onclick="checkbox()"  id="btn" type="submit" name="input" class="btn btn-primary btn-block">Send</button>

Body:
You can check the DOM attribute select.options.selectedIndex to check if the <select> elements are selected.

let button = document.getElementById('btn');
let deadline = document.getElementById("deadline");
let desiredPD = document.getElementById("Desired_payment_date");
let bankTD = document.getElementById("Bank_transfer_destination");
let myCkeck = document.getElementById("myCheck");
let accountT = document.getElementById("AccountTransfer");

/* In this solution, when the button is clicked, <form> control is done. */
button.addEventListener('click', function(event) {
  if(isValid()){
    alert("done");
  }
  else{
    alert("failed");
  }
});

/* This method returns true if validation is successful. */
function isValid()
{
  if (document.getElementById("tab-1").checked) {
    let result = (deadline.selectedIndex != 0) ? true : false;
    result &= (deadline.selectedIndex != 0) ? true : false;
    result &= (desiredPD.selectedIndex != 0) ? true : false;
    result &= (bankTD.selectedIndex != 0) ? true : false;
    result &= (myCkeck.selectedIndex != 0) ? true : false;
    return result;
  }
  else if (document.getElementById("tab-2").checked) {
    return (accountT.selectedIndex != 0) ? true : false;
  }
  else
    return false;
}

table, tr, th,td{
  border: 2px solid #dfd7ca;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-borderless">
    <thead>
        <tr >
            <th scope="col" style="font-size:24px"><input type="checkbox" id="tab-1"  name="one" value="✔" style="height:20px;width:20px;margin-right:10px;" ><span id="銀行振込">Bank transfer</span></th>
            <th scope="col" style="font-size:24px"><input type="checkbox" id="tab-2" 　name="two" value="✔"style="height:20px;width:20px;margin-right:10px;"  ><span id="口座振替">Account transfer</span></th>
        </tr>
        <script>
            $(document).ready(function(){
                $("#tab-1").click(function(){
                    $("#tab-2").prop("checked", false);
                    $("#銀行振込").css("color", "#44aa00");
                    $("#銀行振込").css("text-decoration", "underline  #44aa00");
                    $("#口座振替").css("color", "black");
                    $("#口座振替").css("text-decoration", "none ");
               });

                $("#tab-2").click(function(){
                    $("#tab-1").prop("checked", false);
                    $("#口座振替").css("color", "#44aa00");
                    $("#銀行振込").css("color", "black");
                    $("#口座振替").css("text-decoration", "underline  #44aa00");
                    $("#銀行振込").css("text-decoration", "none ");
                });
            });
        </script>
        </script>
    </thead>
    <tbody>
        <tr>
            <th scope="row">
                <p>
                    <label for=""> deadline </label>
                    <select class="" name="deadline" id="deadline" class="form-select"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                        <option value="" selected></option>
                        <option value="20">20</option>
                        <option value="30">30</option>
                    </select>
                </p>
                <p>
                    <label for="">Desired payment date </label>
                    <select class="Desired_payment_date" id="Desired_payment_date" name="Desired_payment_date" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                        <option value="" selected></option>
                        <option value="20">20</option>
                        <option value="21">21</option>
                        <option value="22">22</option>
                        <option value="23">23</option>
                        <option value="24">24</option>
                        <option value="25">25</option>
                        <option value="26">26</option>
                        <option value="27">27</option>
                        <option value="28">28</option>
                        <option value="29">29</option>
                    </select>
                </p>
                <p>
                    <label for="">Bank </label>
                    <select class="bank" name="Bank_transfer_destination" id="Bank_transfer_destination"  style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;">
                        <option value="" selected></option>
                        <option value="福井銀行">A</option>
                        <option value="北陸銀行">B</option>
                        <option value="敦賀信用金庫">C</option>
                        <option value="商工中金">D</option>
                        <option value="滋賀銀行">E</option>
                        <option value="三菱UFG銀行">F</option>
                    </select>
                </p>
                <label style="font-weight:bold;font-size: 20px;"><input type="checkbox" style="height:20px;width:20px;margin-right:10px;" 　 class="form-check-input" id="myCheck" name="Checkbox_value"  value="✔振込手数料の負担に同意します。">
                I agree to bear the transfer fee.。</label>
            </th>
            <td>
                <p >
                    <label for="">Deadline</label>
                    <select class="" name="AccountTransfer" id="AccountTransfer" style="display: block;width: 100%;height: 46px;padding: 12px 16px;font-size: 14px;line-height: 1.42857143;color: #3e3f3a;background-color: #ffffff;background-image: none;border: 1px solid #dfd7ca;border-radius: 4px;-webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);box-shadow: inset 0 1px 1px rgb(0 0 0 / 8%);-webkit-transition: border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;" >
                        <option value="" selected></option>
                        <option value="20日">20日</option>
                        <option value="末日">末日</option>
                    </select>
                </p>
            </td>
        </tr>
        </tr>
    </tbody>
</table>
<button id="btn" type="submit" name="input" class="btn btn-primary btn-block">Send</button>


来源: stackexchange

问:
django urls without a trailing slash show Page not found
in django urls without a trailing slash in the end i get this result "Page not found 404"
the same project and the same code in one pc i get different result.
this code is when i get the page without slash:

```<code>from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about', views.about, name='about'),
]
</code>```

and this the same code but i should to add slash

```<code>from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
]
</code>```

what i am waiting in the frontend its my views.py

```<code>from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def about(request):
return HttpResponse('about page')
</code>```

i am waiting for your help guys

答:
This behaviour is controlled by the APPEND_SLASH setting. In the default setting APPEND_SLASH is set to True which means if the requested URL does not match any paths set in urls.py an HTTP redirect will issue to the same URL with a trailing slash.

Eg:
Assume a request to /foo.com/bar will redirect to /foo.com/bar/ in case the provided URL /foo.com/bar is an invalid URL pattern.

Documentation states that

Note that the redirect may cause any data submitted in a POST request to be lost.

The APPEND_SLASH setting is only used if CommonMiddleware is installed (see Middleware). See also PREPEND_WWW.

please read the documentation for further clarification.

ContentLicense: CC BY-SA 4.0

Body:
in django urls without a trailing slash in the end i get this result "Page not found 404"
the same project and the same code in one pc i get different result.
this code is when i get the page without slash:

from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about', views.about, name='about'),
]

and this the same code but i should to add slash

from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
]

what i am waiting in the frontend its my views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def about(request):
return HttpResponse('about page')

i am waiting for your help guys


问:
How to render pages dynamically in nextjs
I am rendering a webpage in frontend, taking the data for webpage from the database. Right now I have hard coded the route for a perticular webpage, but I want to make it dynamic as there are multiple webpages in the db and also dynamically render them on nextjs with unique url.

Following is the code for rendering the webpage

```<code>import React, { useEffect, useState } from "react";
import axios from "axios";
import NavigationBar from "../../components/Navbar"
import Footer from "../../components/Footer";
// import { useParams } from "react-router";

export default function Webpage() {
  // let { slug }: any = useParams();
  const [webpage, setWebpage] = useState("");
  // console.log(slug, "slug")
  useEffect(() => {
    async function renderPage() {
      const response = await axios.get(
        "http://localhost:8080/dfsk-ec35-docs"
      );
      setWebpage(response.data);
    }
    renderPage();
  }, []);

  return (
    <div>
      {/* Navigation bar component */}
      <NavigationBar type="main"/>
      {/* rendering the web page */}
      <div dangerouslySetInnerHTML={{ __html: webpage}} />
      {/* Footer component */}
      <Footer />
    </div>
  );
}
</code>```

Following is the code I have for dynamic routes.

```<code>import { useRouter } from "next/dist/client/router";
import Webpage from "./webpage"
export default function WebpageId(){
 const router = useRouter()
 const  pid  = router.query.id
    return(
        <div>page: {pid}</div>
        // <Webpage/>
    )
}
</code>```

答:
You can pass in the pid you extracted as a prop into the Webpage component.
You can also use useRouter() to get the id in your Webpage component directly. Example:

```<code>import React, { useEffect, useState } from "react";
import axios from "axios";
import NavigationBar from "../../components/Navbar"
import Footer from "../../components/Footer";
// import { useParams } from "react-router";

export default function Webpage() {
  // let { slug }: any = useParams();
 const router = useRouter()
 const  pid  = router.query.id
  const [webpage, setWebpage] = useState("");
  // console.log(slug, "slug")
  useEffect(() => {
    async function renderPage() {
      const response = await axios.get(
        `http://localhost:8080/${pid}`
      );
      setWebpage(response.data);
    }
    renderPage();
  }, []);

  return (
    <div>
      {/* Navigation bar component */}
      <NavigationBar type="main"/>
      {/* rendering the web page */}
      <div dangerouslySetInnerHTML={{ __html: webpage}} />
      {/* Footer component */}
      <Footer />
    </div>
  );
}
</code>```

Body:
I am rendering a webpage in frontend, taking the data for webpage from the database. Right now I have hard coded the route for a perticular webpage, but I want to make it dynamic as there are multiple webpages in the db and also dynamically render them on nextjs with unique url.

Following is the code for rendering the webpage

import React, { useEffect, useState } from "react";
import axios from "axios";
import NavigationBar from "../../components/Navbar"
import Footer from "../../components/Footer";
// import { useParams } from "react-router";

export default function Webpage() {
  // let { slug }: any = useParams();
  const [webpage, setWebpage] = useState("");
  // console.log(slug, "slug")
  useEffect(() => {
    async function renderPage() {
      const response = await axios.get(
        "http://localhost:8080/dfsk-ec35-docs"
      );
      setWebpage(response.data);
    }
    renderPage();
  }, []);

  return (

      {/* Navigation bar component */}
      <NavigationBar type="main"/>
      {/* rendering the web page */}

      {/* Footer component */}

  );
}

Following is the code I have for dynamic routes.

import { useRouter } from "next/dist/client/router";
import Webpage from "./webpage"
export default function WebpageId(){
 const router = useRouter()
 const  pid  = router.query.id
    return(

page: {pid}

        // <Webpage/>
    )
}

Body:
You can pass in the pid you extracted as a prop into the Webpage component.
You can also use useRouter() to get the id in your Webpage component directly. Example:

import React, { useEffect, useState } from "react";
import axios from "axios";
import NavigationBar from "../../components/Navbar"
import Footer from "../../components/Footer";
// import { useParams } from "react-router";

export default function Webpage() {
  // let { slug }: any = useParams();
 const router = useRouter()
 const  pid  = router.query.id
  const [webpage, setWebpage] = useState("");
  // console.log(slug, "slug")
  useEffect(() => {
    async function renderPage() {
      const response = await axios.get(
        `http://localhost:8080/${pid}`
      );
      setWebpage(response.data);
    }
    renderPage();
  }, []);

  return (
    <div>
      {/* Navigation bar component */}
      <NavigationBar type="main"/>
      {/* rendering the web page */}
      <div dangerouslySetInnerHTML={{ __html: webpage}} />
      {/* Footer component */}
      <Footer />
    </div>
  );
}


问:
Logfile reformatting with regex
I'm using grep to filter certain lines from a log file and present them to my conky config.
The log file is /var/log/messages.
The entries pertain to UFW block events.

The trouble is that I only care about certain strings of each line.
I can grep the only the UFW blocks, but the line is too long to fit in conky.
Even if conky were not part of the equation, learning to only show pieces of a log line would benefit me in future.

I have got somewhere by using the following:

grep -Ewoh '(IN=([a-z]){4,})|((DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3})|(PROTO=[a-z]{2,6})|((SPT|DPT)=[0-9]{1,5})' /var/log/messages

This ugly-looking regex is filtering for entries (like) this:

```<code>IN=wlan0
SRC=10.10.123.23
DST=192.168.41.23
PROTO=TCP
SPT=443
DPT=41080
</code>```

Which (nearly) line-for-line is as such:

```<code>'
IN=([a-z]){4,}
(DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3}
PROTO=[a-z]{2,6}
(SPT|DPT)=[0-9]{1,5}
'
</code>```

The problem is that this produces a new line for each matching word, where I just want the filtered strings of each line, in their line.

```<code>$ grep -Ewoh '(IN=([a-z]){4,})|((DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3})|(PROTO=[a-z]{2,6})|((SPT|DPT)=[0-9]{1,5})' /var/log/messages
IN=wlan
SRC=103.81.76.20
DST=172.31.77.54
SPT=443
DPT=41080
$
</code>```

I'd rather not use a very complicated awk method unless I can walk back into it a few months later and remember it easily. awk is incredible, but it can be difficult to digest if you drop the ball just once!

Thank you.

答:
If I understand correctly, instead of the list provided by grep -o, you want to remove non matching strings, and print only matching strings, in place. Ie. in the lines and order they appear.

Using gawk's FPAT:

```<code>gawk -v FPAT='my-regex' '$1=$1'
</code>```

Replace my-regex with the regex for strings you want to see.

This will print the matches on each line, in order, delimited by a space.

Add -v OFS= to remove the space, or for example, -v OFS=', ' to change the delimiting string.

You were using grep -w to match a whole word. You can do this in a gawk regex by using \< and \> for left and right word boundary (respectively).

For example, add parentheses and word boundaries around the whole list of 'or' operators (|):

-v FPAT='\<((IN=([a-z]){4,})|((DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3})|(PROTO=[a-z]{2,6})|((SPT|DPT)=[0-9]{1,5}))\>'

Note the bugs in your regex, such as tshiono commented, which won't match PROTO=TCP.

Title: Logfile reformatting with regex

Body:
I'm using grep to filter certain lines from a log file and present them to my conky config.
The log file is /var/log/messages.
The entries pertain to UFW block events.

The trouble is that I only care about certain strings of each line.
I can grep the only the UFW blocks, but the line is too long to fit in conky.
Even if conky were not part of the equation, learning to only show pieces of a log line would benefit me in future.

I have got somewhere by using the following:

grep -Ewoh '(IN=([a-z]){4,})|((DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3})|(PROTO=[a-z]{2,6})|((SPT|DPT)=[0-9]{1,5})' /var/log/messages

This ugly-looking regex is filtering for entries (like) this:

IN=wlan0
SRC=10.10.123.23
DST=192.168.41.23
PROTO=TCP
SPT=443
DPT=41080

Which (nearly) line-for-line is as such:

'
IN=([a-z]){4,}
(DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3}
PROTO=[a-z]{2,6}
(SPT|DPT)=[0-9]{1,5}
'

The problem is that this produces a new line for each matching word, where I just want the filtered strings of each line, in their line.

$ grep -Ewoh '(IN=([a-z]){4,})|((DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3})|(PROTO=[a-z]{2,6})|((SPT|DPT)=[0-9]{1,5})' /var/log/messages
IN=wlan
SRC=103.81.76.20
DST=172.31.77.54
SPT=443
DPT=41080
$

I'd rather not use a very complicated awk method unless I can walk back into it a few months later and remember it easily. awk is incredible, but it can be difficult to digest if you drop the ball just once!

Thank you.

Body:
If I understand correctly, instead of the list provided by grep -o, you want to remove non matching strings, and print only matching strings, in place. Ie. in the lines and order they appear.

Using gawk's FPAT:

gawk -v FPAT='my-regex' '$1=$1'

Replace my-regex with the regex for strings you want to see.

This will print the matches on each line, in order, delimited by a space.

Add -v OFS= to remove the space, or for example, -v OFS=', ' to change the delimiting string.

You were using grep -w to match a whole word. You can do this in a gawk regex by using \< and \> for left and right word boundary (respectively).

For example, add parentheses and word boundaries around the whole list of 'or' operators (|):

-v FPAT='\<((IN=([a-z]){4,})|((DST|SRC)=(([0-9]){1,3}\.){3,}([0-9]){1,3})|(PROTO=[a-z]{2,6})|((SPT|DPT)=[0-9]{1,5}))\>'

Note the bugs in your regex, such as tshiono commented, which won't match PROTO=TCP.


问:
Nodejs | npm : html-pdf,set image size
I'm using html-pdf to convert an SVG file to PNG, and I can't get the output image size to reflect the input size (128x128). Instead it comes with blank space (see image below).
I've tried explicitly setting width and height, setting header and footer height (as per this link), but nothing has any effect.

Any suggestions?

Code:

```<code>htmlpdf.create(qrcode, { "border": "0", "type": "png"}).toFile(originalname.split(".")[0]+".png", function(err, res) {
        if (err) throw err;
        console.log(res);
      });
</code>```

答:
To fix the above problem you can make use of an npm package called: npm:sharp.

It worked perfectly for the problem above.

Title: Nodejs | npm : html-pdf,set image size

Body:
I'm using html-pdf to convert an SVG file to PNG, and I can't get the output image size to reflect the input size (128x128). Instead it comes with blank space (see image below).
I've tried explicitly setting width and height, setting header and footer height (as per this link), but nothing has any effect.

Any suggestions?

Code:

htmlpdf.create(qrcode, { "border": "0", "type": "png"}).toFile(originalname.split(".")[0]+".png", function(err, res) {
        if (err) throw err;
        console.log(res);
      });


问:
Eclipse AndroidManifest.xml format
When I format the xml using Ctrl+Shift+F the result is being like that:

But It would be nice if something can make xml like that:

Is there any way to format the formatting on eclipse?

答:
You don't need that plug-in!
To have all the attributes on their own lines, go to: Window→Preferences→XML→XML Files→Editor and check Split multiple attributes each on a new line.

Then Ctrl+Shift+F to auto-format.

ContentLicense: CC BY-SA 3.0

Title: Eclipse AndroidManifest.xml format


问:
Creating Multiple Excel sheets using data frames Python pandas
I am trying to create Multiple Excel sheets using Python Pandas But its only creating the latest one and old one is getting replaced. Here my Scan2 Replaces Scan1 Sheet in output.xlsx file it's not saving the sheets.

import pandas as pd
from openpyxl import load_workbook

#scan1
df = pd.read_csv("C:/Users/t/Downloads/a.csv")

dfdf = df[df["Data"].str.contains("None") == False]

dfdf.to_excel("output.xlsx" , sheet_name= 'scan1' , index = False )

#scan2

dfg = pd.read_csv("C:/Users/t/Downloads/b.csv")

dfdfd = dfg[df["Data"].str.contains("None") == False]

dfdfd.to_excel("output.xlsx" , sheet_name= 'Scan2' , index=False)
```

答:
To save multiple sheets to excel, you have to use pandas' ExcelWriter method

try this:

```<code>writer = pd.ExcelWriter('output.xlsx', engine = 'xlsxwriter')

dfdf.to_excel(writer, sheet_name = 'Scan01')
dfdfd.to_excel(writer, sheet_name = 'Scan02')
</code>```

other way of doing it without ExcelWriter installation:

```<code>with pd.ExcelWriter('output.xlsx') as writer:
     dfdf.to_excel(writer, sheet_name = 'Scan01')
     dfdfd.to_excel(writer, sheet_name = 'Scan02')
</code>```

Body:
To save multiple sheets to excel, you have to use pandas' ExcelWriter method

try this:

writer = pd.ExcelWriter('output.xlsx', engine = 'xlsxwriter')

dfdf.to_excel(writer, sheet_name = 'Scan01')
dfdfd.to_excel(writer, sheet_name = 'Scan02')

other way of doing it without ExcelWriter installation:

with pd.ExcelWriter('output.xlsx') as writer:
     dfdf.to_excel(writer, sheet_name = 'Scan01')
     dfdfd.to_excel(writer, sheet_name = 'Scan02')


问:
Mouse emulation on Raspberry Pi 4 does not work

For a personal project I am currently trying to make my Raspberry Pi 4 emulate both a keyboard as well as a mouse. The keyboard emulation works really well and convincing, but I keep getting problems when it comes to emulating the mouse.

I've configured my Pi as an HID device with the following code being executed at boot:
```<code>#!/bin/bash
cd /sys/kernel/config/usb_gadget/
mkdir -p pihid
cd pihid
echo 0x1d6b > idVendor # Linux Foundation
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
mkdir -p strings/0x409
echo "fedcba9876543210" > strings/0x409/serialnumber
echo "test" > strings/0x409/manufacturer
echo "PiHID" > strings/0x409/product
mkdir -p configs/c.1/strings/0x409
echo "Config 1: ECM network" > configs/c.1/strings/0x409/configuration
echo 250 > configs/c.1/MaxPower

# Add functions here
mkdir -p functions/hid.usb0
echo 1 > functions/hid.usb0/protocol
echo 1 > functions/hid.usb0/subclass
echo 8 > functions/hid.usb0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.usb0/report_desc
ln -s functions/hid.usb0 configs/c.1/

mkdir -p functions/hid.usb1
echo 2 > functions/hid.usb1/protocol
echo 2 > functions/hid.usb1/subclass
echo 8 > functions/hid.usb1/report_length
echo -ne \\x05\\x01\\x09\\x02\\xA1\\x01\\x09\\x01\\xA1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x03\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x81\\x25\\x7F\\x75\\x08\\x95\\x02\\x81\\x06\\xC0\\xC0 > functions/hid.usb1/report_desc
ln -s functions/hid.usb1 configs/c.1/
# End functions

ls /sys/class/udc > UDC
</code>```

After boot there are two files in /dev, called "hidg0" and "hidg1", which I should be able to write to. Writing keyboard commands to "hidg0" works completely fine with this python script:

```<code>NULL_CHAR = chr(0)

def write_report(report):
    with open('/dev/hidg0', 'rb+') as fd:
        fd.write(report.encode())

write_report(NULL_CHAR*2+chr(6)+chr(7)+chr(8)+chr(9)+chr(10)+chr(11))
write_report(NULL_CHAR*8)
</code>```

When I am in editor, "cdefgh" will appear.

This is my script I use to write to "hidg1":

```<code>NULL_CHAR = chr(0)

def ms_write(report):
    with open("/dev/hidg1", "rb+") as fd:
        fd.write(report.encode())

ms_write(NULL_CHAR+chr(100)+NULL_CHAR*6)
ms_write(NULL_CHAR*8)
</code>```

But after executing, instead of moving the mouse 100 units, nothing happens and the program finishes.
What am I doing wrong concerning the mouse emulation or the communication with the Windows HID Drivers?

答:
I think the mouse needs 3 bytes instead of 8. Also, try wb+ instead of rb+</p>
```<code>NULL_CHAR = chr(0)

def ms_write(report):
    with open("/dev/hidg1", "wb+") as fd:
        fd.write(report.encode())

ms_write(NULL_CHAR+chr(100)+NULL_CHAR)

ms_write(NULL_CHAR*3)
</code>```

Body:
For a personal project I am currently trying to make my Raspberry Pi 4 emulate both a keyboard as well as a mouse. The keyboard emulation works really well and convincing, but I keep getting problems when it comes to emulating the mouse.

I've configured my Pi as an HID device with the following code being executed at boot:

#!/bin/bash
cd /sys/kernel/config/usb_gadget/
mkdir -p pihid
cd pihid
echo 0x1d6b > idVendor # Linux Foundation
echo 0x0104 > idProduct # Multifunction Composite Gadget
echo 0x0100 > bcdDevice # v1.0.0
echo 0x0200 > bcdUSB # USB2
mkdir -p strings/0x409
echo "fedcba9876543210" > strings/0x409/serialnumber
echo "test" > strings/0x409/manufacturer
echo "PiHID" > strings/0x409/product
mkdir -p configs/c.1/strings/0x409
echo "Config 1: ECM network" > configs/c.1/strings/0x409/configuration
echo 250 > configs/c.1/MaxPower

# Add functions here
mkdir -p functions/hid.usb0
echo 1 > functions/hid.usb0/protocol
echo 1 > functions/hid.usb0/subclass
echo 8 > functions/hid.usb0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.usb0/report_desc
ln -s functions/hid.usb0 configs/c.1/

mkdir -p functions/hid.usb1
echo 2 > functions/hid.usb1/protocol
echo 2 > functions/hid.usb1/subclass
echo 8 > functions/hid.usb1/report_length
echo -ne \\x05\\x01\\x09\\x02\\xA1\\x01\\x09\\x01\\xA1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x03\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x81\\x25\\x7F\\x75\\x08\\x95\\x02\\x81\\x06\\xC0\\xC0 > functions/hid.usb1/report_desc
ln -s functions/hid.usb1 configs/c.1/
# End functions

ls /sys/class/udc > UDC

After boot there are two files in /dev, called "hidg0" and "hidg1", which I should be able to write to. Writing keyboard commands to "hidg0" works completely fine with this python script:

NULL_CHAR = chr(0)

def write_report(report):
    with open('/dev/hidg0', 'rb+') as fd:
        fd.write(report.encode())

write_report(NULL_CHAR*2+chr(6)+chr(7)+chr(8)+chr(9)+chr(10)+chr(11))
write_report(NULL_CHAR*8)

When I am in editor, "cdefgh" will appear.

This is my script I use to write to "hidg1":

NULL_CHAR = chr(0)

def ms_write(report):
    with open("/dev/hidg1", "rb+") as fd:
        fd.write(report.encode())

ms_write(NULL_CHAR+chr(100)+NULL_CHAR*6)
ms_write(NULL_CHAR*8)

But after executing, instead of moving the mouse 100 units, nothing happens and the program finishes.
What am I doing wrong concerning the mouse emulation or the communication with the Windows HID Drivers?

Body:
I think the mouse needs 3 bytes instead of 8. Also, try wb+ instead of rb+

NULL_CHAR = chr(0)

def ms_write(report):
    with open("/dev/hidg1", "wb+") as fd:
        fd.write(report.encode())

ms_write(NULL_CHAR+chr(100)+NULL_CHAR)

ms_write(NULL_CHAR*3)


问:
NHibernate - how to fluently map id based property to be one way from domain model to database
Inside my app entity is identified by a string key - a baseN representation of its ID like
xAdWzC which  is a BaseN (52) representation of numeric Id.

numeric Id is generated using similar to oracle sequence algorithm, before insertion ( my custom id generator).

How do I map my class that basicly has 2 representations of Id to be saved in db with 2 columns one numeric - primary key and the other - a string key to identify rows in db better? I obviously dont need 2 primary keys and would prefer numeric PK.

A string key is just a property that wraps around numeric key in C# like this

```<code>public string Key
{
     get { return BaseNFunction(Id); }
}
</code>```

Basicly I want this mapping to be one way to db. When item is loaded from db this column has to be completely ignored.

How would the NHB mapping look like?
Is the question difficult or its just wasn't spotted? I dont think its worth a bounty but please help me.

答:
Just make the generated property readonly (it's access="readonly" in XML; look for something similar in fluent)

Read-only in this case means the property is read from the entity and written to the DB, but not the other way around

Body:
Inside my app entity is identified by a string key - a baseN representation of its ID like
xAdWzC which  is a BaseN (52) representation of numeric Id.

numeric Id is generated using similar to oracle sequence algorithm, before insertion ( my custom id generator).

How do I map my class that basicly has 2 representations of Id to be saved in db with 2 columns one numeric - primary key and the other - a string key to identify rows in db better? I obviously dont need 2 primary keys and would prefer numeric PK.

A string key is just a property that wraps around numeric key in C# like this

public string Key
{
     get { return BaseNFunction(Id); }
}

Basicly I want this mapping to be one way to db. When item is loaded from db this column has to be completely ignored.

How would the NHB mapping look like?
Is the question difficult or its just wasn't spotted? I dont think its worth a bounty but please help me.


问:
WebScrape - Pagination/Next page
The current code works and scrapes the page how I want it to.

However, how can I get this to run for the next page ? The URL is not unique for the second page and I want to run for all pages.

```<code>import requests
from bs4 import BeautifulSoup as bs
lists=[]

r = requests.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
soup = bs(r.content, 'lxml')
d = {i.text.strip():i['href'] for i in soup.select('.ej-toc-subheader + div h4 > a')}
lists.append(d)

</code>```

答: It's a dynamically loaded webpage you need to use selenium for that. Have a look  here : Selenium with Python</p>

Title: WebScrape - Pagination/Next page

Body:
The current code works and scrapes the page how I want it to.

However, how can I get this to run for the next page ? The URL is not unique for the second page and I want to run for all pages.

import requests
from bs4 import BeautifulSoup as bs
lists=[]

r = requests.get('https://journals.lww.com/ccmjournal/toc/2022/01001')
soup = bs(r.content, 'lxml')
d = {i.text.strip():i['href'] for i in soup.select('.ej-toc-subheader + div h4 > a')}
lists.append(d)


问:
How to detect current slide number of carousel in react on ClassChange
I want to detect the current slide number of the carousel when the slide changes.
How can I achieve it?. I was trying it with jquery but stuck on how to detect it on class Change.
Is there any other of achieving this other than jquery
For Carousel, I am using bootstrap.

Update:

The carousel slides are also on auto change after 5 secs interval

You can look at the code below.
https://codesandbox.io/s/sweet-sunset-ns3o1?file=/src/App.js

答:
In Carousel, call a function with onSlide event.

```<code><Carousel onSlide={setMovieKey} />
</code>```

Then in your function, find the element with the active class name and then use elem.ID.

```<code>const setMovieKey = () => {
  const elem = document.getElementsByClassName('carousel-item active')[0]
}
</code>```

Body:
In Carousel, call a function with onSlide event.

<Carousel onSlide={setMovieKey} />

Then in your function, find the element with the active class name and then use elem.ID.

const setMovieKey = () => {
  const elem = document.getElementsByClassName('carousel-item active')[0]
}


问:
How to create input line in pygame screen?
please tell me how to create an input line in pygame as easy as possible? For example, such as the password entry line in Windows, not in terms of graphics, but in terms of functionality.
(sorry for possible grammatical errors. I'm not English)enter image description here</p>

答:
If I'm not wrong, pygame doesn't have a way to create inputs easily (You can use some libraries but in my case, none of them worked for my project needs), but that doesn't mean that it can't be done, I leave you the link of a project that I elaborated with pygame where I created a simple input line Repository in github. I also share with you a video that can help you (Credits to the corresponding channel, I am not the creator of that content) Python / Pygame tutorial: Getting text input

If you want a more concrete answer, I would recommend that you create a rectangle and detect a collision (click) with the mouse, and from that, listen to the keyboard inputs, add them to a string and display them on the screen.


问:
How can I make this progress bar mobile and desktop responsive
I have a progress bar that has three stages (begin, select, result). Once a stage is reached the progress circle becomes black to indicate and stages not achieved yet are transparent with a black border for the circle. The issue I am facing is that the line connecting the three progress bar circles is not responsive. On certain devices, the line doesn't touch the circles as it should and on other devices, the line goes over the circle which I don't want either. I would appreciate any help on making this progress bar responsive across devices, thank you!

https://jsfiddle.net/6p9kmte8/

HTML

```<code><!-- bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="d-flex justify-content-center">
  <div class="progress-container">
    <ul class="progress-steps">
      <li class="active">Begin</li>
      <li class="active">Select</li>
      <li>Results</li>
    </ul>
  </div>
</div>

<!-- jquery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous">
</script>
</code>```

CSS

```<code>.progress_bar>div {
    display: inline-block;
}

.progress-container {
    width: 71.3%;
    /*margin-top: 9.39%;*/
    margin-bottom: 1%;
    font-weight: 300;
    margin-right: 2em;
    position: fixed;
    bottom: 0;
}

.progress-steps {
    counter-reset: step;
}

.progress-steps li {
    list-style-type: none;
    width: 33.333333%;
    float: left;
    font-size: 1.2em;
    position: relative;
    text-align: center;
    color: black;
}

.progress-steps li:before {
    width: 2.5em;
    height: 2.5em;
    content: counter(step);
    counter-increment: step;
    line-height: 2.5em;
    border: 2px solid black;
    display: block;
    text-align: center;
    margin: 0 auto .7em auto;
    border-radius: 50%;
    background-color: black;
}

.progress-steps li:after {
    width: 100%;
    height: 0.2em;
    content: '';
    position: absolute;
    background-color: black;
    top: 1.2em;
    left: -50%;
    z-index: -1;
}

.progress-steps li:first-child:after {
    content: none;
}

.progress-steps li.active {
    color: black;
}

.progress-steps li.active:before {
    border-color: black;
}

.progress-steps li.active+li:after {
    background-color: black;
    width: 85%;
    margin-left: 7.5%;
}

.progress-steps li.active+li:before {
    background-color: transparent;
    border: 2px solid black;
    color: transparent;
}

@media (max-width: 1024px) {
    .progress-container {
        width: 90%;
        /*margin-top: 7.15em;
        padding-bottom: 0.4em;*/
        margin-bottom: 2%;
    }

    .progress-steps li {
        font-size: 0.9em;
    }

    .progress-steps li.active+li:after {
        width: 71%;
    }
}
</code>```

答:
```<code>.progress_bar>div {
    display: inline-block;
}

.progress-container {
    width: 71.3%;
    /*margin-top: 9.39%;*/
    margin-bottom: 1%;
    font-weight: 300;
    margin-right: 2em;
    position: fixed;
    bottom: 0;
}

.progress-steps {
    counter-reset: step;
}

.progress-steps li {
    list-style-type: none;
    width: 33.333333%;
    float: left;
    font-size: 1.2em;
    position: relative;
    text-align: center;
    color: black;
}

.progress-steps li:before {
    width: 2.5em;
    height: 2.5em;
    content: counter(step);
    counter-increment: step;
    line-height: 2.5em;
    border: 2px solid black;
    display: block;
    text-align: center;
    margin: 0 auto .7em auto;
    border-radius: 50%;
    background-color: black;
}

.progress-steps li:after {
    width: calc(100% - 2.5em);
    height: 0.2em;
    content: "";
    position: absolute;
    background-color: black;
    top: 1.25em;
    right: calc(50% + 1.25em);
    z-index: -1;
}

.progress-steps li:first-child:after {
    content: none;
}

.progress-steps li.active {
    color: black;
}

.progress-steps li.active:before {
    border-color: black;
}

.progress-steps li.active+li:before {
    background-color: transparent;
    border: 2px solid black;
    color: transparent;
}

@media (max-width: 1024px) {
    .progress-container {
        width: 90%;
        /*margin-top: 7.15em;
        padding-bottom: 0.4em;*/
        margin-bottom: 2%;
    }

    .progress-steps li {
        font-size: 0.9em;
    }
}
</code>```

Body:
I have a progress bar that has three stages (begin, select, result). Once a stage is reached the progress circle becomes black to indicate and stages not achieved yet are transparent with a black border for the circle. The issue I am facing is that the line connecting the three progress bar circles is not responsive. On certain devices, the line doesn't touch the circles as it should and on other devices, the line goes over the circle which I don't want either. I would appreciate any help on making this progress bar responsive across devices, thank you!

https://jsfiddle.net/6p9kmte8/

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

Begin

Select

Results

CSS

.progress_bar>div {
    display: inline-block;
}

.progress-container {
    width: 71.3%;
    /*margin-top: 9.39%;*/
    margin-bottom: 1%;
    font-weight: 300;
    margin-right: 2em;
    position: fixed;
    bottom: 0;
}

.progress-steps {
    counter-reset: step;
}

.progress-steps li {
    list-style-type: none;
    width: 33.333333%;
    float: left;
    font-size: 1.2em;
    position: relative;
    text-align: center;
    color: black;
}

.progress-steps li:before {
    width: 2.5em;
    height: 2.5em;
    content: counter(step);
    counter-increment: step;
    line-height: 2.5em;
    border: 2px solid black;
    display: block;
    text-align: center;
    margin: 0 auto .7em auto;
    border-radius: 50%;
    background-color: black;
}

.progress-steps li:after {
    width: 100%;
    height: 0.2em;
    content: '';
    position: absolute;
    background-color: black;
    top: 1.2em;
    left: -50%;
    z-index: -1;
}

.progress-steps li:first-child:after {
    content: none;
}

.progress-steps li.active {
    color: black;
}

.progress-steps li.active:before {
    border-color: black;
}

.progress-steps li.active+li:after {
    background-color: black;
    width: 85%;
    margin-left: 7.5%;
}

.progress-steps li.active+li:before {
    background-color: transparent;
    border: 2px solid black;
    color: transparent;
}

@media (max-width: 1024px) {
    .progress-container {
        width: 90%;
        /*margin-top: 7.15em;
        padding-bottom: 0.4em;*/
        margin-bottom: 2%;
    }

    .progress-steps li {
        font-size: 0.9em;
    }

    .progress-steps li.active+li:after {
        width: 71%;
    }
}


问:
Flutter TextFormField: The keyboard appeared and instantly disappeared
When I click the TextFormField, the keyboard appears, then it disappears instantly, just like blinking. I wonder that whether it is because the lacking of some parameters? Or some other problems? Thanks.
Here are my relative codes.</p>
```<code>final _formKey = GlobalKey<FormState>();
String? _account;
Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: new InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _showAccountInput()

          ],
        ),
      ),
    );
  }
}
</code>```

答:
no need to use statefull widget because the state of widget is not changing.

the simplest way to do the example is create the textfield widget first then extract the method and make it reusable widget.

```<code>
class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [ShowAccountInput()],
      ),
    );
  }
}

class ShowAccountInput extends StatelessWidget {
  String? account;

  ShowAccountInput({
    this.account,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: TextFormField(
        maxLines: 1,
        obscureText: true,
        decoration: const InputDecoration(
            hintText: 'input',
            border: InputBorder.none,
            icon: Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => account = value?.trim(),
      ),
    );
  }
}
</code>```

Body:
When I click the TextFormField, the keyboard appears, then it disappears instantly, just like blinking. I wonder that whether it is because the lacking of some parameters? Or some other problems? Thanks.
Here are my relative codes.

final _formKey = GlobalKey<FormState>();
String? _account;
Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: new InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _showAccountInput()

          ],
        ),
      ),
    );
  }
}

Body:
no need to use statefull widget because the state of widget is not changing.

the simplest way to do the example is create the textfield widget first then extract the method and make it reusable widget.

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [ShowAccountInput()],
      ),
    );
  }
}

class ShowAccountInput extends StatelessWidget {
  String? account;

  ShowAccountInput({
    this.account,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: TextFormField(
        maxLines: 1,
        obscureText: true,
        decoration: const InputDecoration(
            hintText: 'input',
            border: InputBorder.none,
            icon: Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => account = value?.trim(),
      ),
    );
  }
}


问:
Python/Mysql UTF8/UTF8MB4 configuration problem?
Since last release of Wordpress I get a

/usr/lib/python3/dist-packages/pymysql/cursors.py:170: Warning: (3719, "'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release error in out logfiles. How to fix that?

答:
That is an annoying warning.  You can probably ignore it.

The VARCHAR and TEXT columns in your WP tables (and zillions of other tables around the globe) were declared CHARACTER SET utf8.  This was reasonable when the tables were first created.

CHARACTER SET utf8mb3 does not handle all Chinese characters or Emoji; utf8mb4 does.

The warning message hints at how MySQL is transitioning from utf8mb3 to utf8mb4.  But it does not say when or in what way the switchover will happen.

"How to fix"?  I hesitate to say.  There are multiple ways, none is simple.  I do think it is safe to ignore the message for now.

The goal is for utf8 to refer to the better utf8mb4, but it will be clumsy to get there.

Keep your eye on bug: https://bugs.mysql.com/bug.php?id=106389


问:
I want to fetch file and image in php code from javascript code
```<code>jwplayer("vplayer").setup({
sources: [{file:"server-url",label:"480p"}],
image: "server.com/img.jpg",
width: "100%",
height: "100%",
stretching: "uniform",
duration: "5931",
preload: 'auto',
androidhls: "true",
hlshtml: "true",
primary: "html5",
startparam: "start"
</code>```

});

I want to fetch file and image in php code from javascript code

答:
I think you can't able to assign directly to the php variable.
what i have done i my project get the javascript variable value and create a hidden input like(<input input ="file" class="file" name ="file" value="" >) and using $(".file").val(image); this i get the value.else u need to send those value to another page using ajax

Body:
jwplayer("vplayer").setup({
sources: [{file:"server-url",label:"480p"}],
image: "server.com/img.jpg",
width: "100%",
height: "100%",
stretching: "uniform",
duration: "5931",
preload: 'auto',
androidhls: "true",
hlshtml: "true",
primary: "html5",
startparam: "start"

});

I want to fetch file and image in php code from javascript code


问:
I am coming across Switch export error from react-router-dom
I am coming across the following error and cannot find a way out of it. Could anyone please help?

export 'Switch' (imported as 'Switch') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)

答:
you can import like this:

```<code>import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";
</code>```

here is codesandbox example for you :

https://codesandbox.io/s/react-router-basic-294mt?from-embed=&file=/example.js

Body:
you can import like this:

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

here is codesandbox example for you :

https://codesandbox.io/s/react-router-basic-294mt?from-embed=&file=/example.js


问:
Undefined parameter in react function when retrieving data from API
I am trying to retrieve data from an API, however it requires an encrypted name, which I receive from another API call. So, I am trying to use the data from the first API to retrieve the Data in the Second API, however when I try to pass in the appropriate data, it says that it is undefined, when I can even print it out.

```<code>import { useState, useEffect } from "react";
import { Typography, Row, Col, Statistic } from "antd";
import { Link } from "react-router-dom";
import axios from "axios";

const { Title } = Typography;

const Homepage = () => {
  const [searchText, setSearchText] = useState("");
  const [playerData, setPlayerData] = useState({});
  const [playerStats, setPlayerStats] = useState({});

  const API_KEY = "MyprivateAPIKEY";

  function searchForPlayer(event) {
    var APICallSummoner =
      "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" +
      searchText +
      "?api_key=" +
      API_KEY;

    axios
      .get(APICallSummoner)
      .then(function (response) {
        setPlayerData(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function searchPlayerData(id) {
    var API =
      "https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/" +
      id +
      "?api_key=" +
      API_KEY;
    axios
      .get(API)
      .then(function (response) {
        setPlayerStats(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  return (
    <>
      <Title level={2} className='heading'>
        LoLTracker
      </Title>

      <input
        type='text'
        onChange={(e) => setSearchText(e.target.value)}></input>
      <button
        onClick={(e) => {
          searchForPlayer(e);
          var a = playerData.id;
          console.log(a);
          searchPlayerData(a);
        }}>
        Search Player
      </button>

      {JSON.stringify(playerData) != "{}" ? (
        <>
          <p>{playerData.name}</p>
          <img
            width='100'
            height='100'
            src={
              "http://ddragon.leagueoflegends.com/cdn/12.3.1/img/profileicon/" +
              playerData.profileIconId +
              ".png"
            }></img>
          <p>Summoner Level: {playerData.summonerLevel} </p>
        </>
      ) : (
        <>
          <p>No Player Data</p>
        </>
      )}

      <Row>
        <Col span={12}>
          <Statistic title='Total Games Played' value={playerStats.wins} />
        </Col>
        <Col span={12}>
          <Statistic title='Ranked Solo Duo Games' value='5' />
        </Col>
        <Col span={12}>
          <Statistic title='Wins' value='5' />
        </Col>
        <Col span={12}>
          <Statistic title='Losses' value='5' />
        </Col>
      </Row>
    </>
  );
};

export default Homepage;
</code>```

In my onClick() function, I get the required information from searchForPlayer, but i cannot pass the data to my searchForPlayer function. Pls help

答:
In React state updates are asynchronous in nature, so because of this you cannot expect updated state values immediately on the next line after calling state update(setState).

In your case on button click, you are doing this -

```<code><button
    onClick={(e) => {
        // this will change state value for playerData
        searchForPlayer(e);
        // but here on next line you cannot access updated value
        // because searchForPlayer will not run synchronously
        var a = playerData.id;
        console.log(a); // so you will mostly get undefined here
        searchPlayerData(a);
    }}>
    Search Player
</button>
</code>```

To fix this either you need to use useEffect with dependency array with playerData like this -

```<code>React.useEffect(() => {
    if(playerData.id){
        //call next function or api here
    }
}, [playerData])
</code>```

Above useEffect will get called when your playerData gets changed. So in here, you can call anything which needs state playerData.

Or if you only need to call searchPlayerData after searchForPlayer then instead of using the state to store playerData and then passing it to searchPlayerData you can directly call searchPlayerData inside .then in searchForPlayer, see below code -

```<code>function searchForPlayer(event) {
    var APICallSummoner =
        "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" +
        searchText +
        "?api_key=" +
        API_KEY;

    axios
        .get(APICallSummoner)
        .then(function (response) {
            // you do not need to set below state value
            // if you are not going to use it other than calling next api
            setPlayerData(response.data);
            if(response.data){
                //calling next function here
                searchPlayerData(response.data.id);
            }
        })
        .catch(function (error) {
            console.log(error);
        });
}

</code>```

Body:
I am trying to retrieve data from an API, however it requires an encrypted name, which I receive from another API call. So, I am trying to use the data from the first API to retrieve the Data in the Second API, however when I try to pass in the appropriate data, it says that it is undefined, when I can even print it out.

import { useState, useEffect } from "react";
import { Typography, Row, Col, Statistic } from "antd";
import { Link } from "react-router-dom";
import axios from "axios";

const { Title } = Typography;

const Homepage = () => {
  const [searchText, setSearchText] = useState("");
  const [playerData, setPlayerData] = useState({});
  const [playerStats, setPlayerStats] = useState({});

  const API_KEY = "MyprivateAPIKEY";

  function searchForPlayer(event) {
    var APICallSummoner =
      "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" +
      searchText +
      "?api_key=" +
      API_KEY;

    axios
      .get(APICallSummoner)
      .then(function (response) {
        setPlayerData(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function searchPlayerData(id) {
    var API =
      "https://na1.api.riotgames.com/lol/league/v4/entries/by-summoner/" +
      id +
      "?api_key=" +
      API_KEY;
    axios
      .get(API)
      .then(function (response) {
        setPlayerStats(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  }

  return (
    <>
      <Title level={2} className='heading'>
        LoLTracker
      </Title>

      <input
        type='text'
        onChange={(e) => setSearchText(e.target.value)}></input>
      <button
        onClick={(e) => {
          searchForPlayer(e);
          var a = playerData.id;
          console.log(a);
          searchPlayerData(a);
        }}>
        Search Player
      </button>

      {JSON.stringify(playerData) != "{}" ? (
        <>

{playerData.name}

Summoner Level: {playerData.summonerLevel}

        </>
      ) : (
        <>

No Player Data

        </>
      )}

      <Row>
        <Col span={12}>
          <Statistic title='Total Games Played' value={playerStats.wins} />
        </Col>
        <Col span={12}>
          <Statistic title='Ranked Solo Duo Games' value='5' />
        </Col>
        <Col span={12}>
          <Statistic title='Wins' value='5' />
        </Col>
        <Col span={12}>
          <Statistic title='Losses' value='5' />
        </Col>
      </Row>
    </>
  );
};

export default Homepage;

In my onClick() function, I get the required information from searchForPlayer, but i cannot pass the data to my searchForPlayer function. Pls help

Body:
In React state updates are asynchronous in nature, so because of this you cannot expect updated state values immediately on the next line after calling state update(setState).

In your case on button click, you are doing this -

<button
    onClick={(e) => {
        // this will change state value for playerData
        searchForPlayer(e);
        // but here on next line you cannot access updated value
        // because searchForPlayer will not run synchronously
        var a = playerData.id;
        console.log(a); // so you will mostly get undefined here
        searchPlayerData(a);
    }}>
    Search Player
</button>

To fix this either you need to use useEffect with dependency array with playerData like this -

React.useEffect(() => {
    if(playerData.id){
        //call next function or api here
    }
}, [playerData])

Above useEffect will get called when your playerData gets changed. So in here, you can call anything which needs state playerData.

Or if you only need to call searchPlayerData after searchForPlayer then instead of using the state to store playerData and then passing it to searchPlayerData you can directly call searchPlayerData inside .then in searchForPlayer, see below code -

function searchForPlayer(event) {
    var APICallSummoner =
        "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" +
        searchText +
        "?api_key=" +
        API_KEY;

    axios
        .get(APICallSummoner)
        .then(function (response) {
            // you do not need to set below state value
            // if you are not going to use it other than calling next api
            setPlayerData(response.data);
            if(response.data){
                //calling next function here
                searchPlayerData(response.data.id);
            }
        })
        .catch(function (error) {
            console.log(error);
        });
}


问:
Memory leak with std::string depends on string size
I am getting a memory leaking in C++ depending on the string size. On the code bellow if the string size is less than 15 valgrind doesn't shows leak, however if string size is greater than 15 I am getting memory leaks:

```<code>#include <string>
#include <memory>
#include <iostream>

class AuthBase {
public:
    virtual void foo() = 0;
};

class APIAuthetication : public AuthBase {
public:
    APIAuthetication(const std::string api_key, const std::string api_secret) : m_api_key(api_key),
                m_api_secret(api_secret) {}

    virtual ~APIAuthetication() {}

    void foo() {}
private:
    const std::string m_api_key;
    const std::string m_api_secret;
};

class ClientBase {
public:
    virtual void bar() = 0;
};

class Client: public ClientBase {
public:
    Client(AuthBase* auth) : m_auth(auth) {}
    ~Client() {}

    void bar() {}
private:
    std::unique_ptr<AuthBase> m_auth;
};

class ClientAPI : public Client {
public:
    ClientAPI(const std::string api_key, const std::string api_secret) :
                Client((new APIAuthetication(api_key, api_secret))) {}
    virtual ~ClientAPI() {}
};

int main(void) {
    /* This runs fine. String size == 15 */
    ClientAPI cli("123456789101112", "123456789101112");
    /* Memory leak. String size > 15 */
    ClientAPI cli_leak("1234567891011121", "1234567891011121");
    return 0;
}
</code>```
```<code>==17060== HEAP SUMMARY:
==17060==     in use at exit: 34 bytes in 2 blocks
==17060==   total heap usage: 9 allocs, 7 frees, 72,950 bytes allocated
==17060==
==17060== Searching for pointers to 2 not-freed blocks
==17060== Checked 111,624 bytes
==17060==
==17060== 17 bytes in 1 blocks are definitely lost in loss record 1 of 2
==17060==    at 0x4C3217F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17060==    by 0x4F6513C: void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_construct<char*>(char*, char*, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)
==17060==    by 0x1091B3: APIAuthetication::APIAuthetication(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x10937C: ClientAPI::ClientAPI(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x108FD3: main (in /home/rogerio/code-studies/curl-examples/weird)
==17060==
==17060== 17 bytes in 1 blocks are definitely lost in loss record 2 of 2
==17060==    at 0x4C3217F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17060==    by 0x4F6513C: void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_construct<char*>(char*, char*, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)
==17060==    by 0x1091CA: APIAuthetication::APIAuthetication(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x10937C: ClientAPI::ClientAPI(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x108FD3: main (in /home/rogerio/code-studies/curl-examples/weird)
==17060==
==17060== LEAK SUMMARY:
==17060==    definitely lost: 34 bytes in 2 blocks
==17060==    indirectly lost: 0 bytes in 0 blocks
==17060==      possibly lost: 0 bytes in 0 blocks
==17060==    still reachable: 0 bytes in 0 blocks
==17060==         suppressed: 0 bytes in 0 blocks
==17060==
==17060== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
==17060== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
</code>```

No leaks if string size is < 15:

```<code>==17211==
==17211== HEAP SUMMARY:
==17211==     in use at exit: 0 bytes in 0 blocks
==17211==   total heap usage: 2 allocs, 2 frees, 72,776 bytes allocated
==17211==
==17211== All heap blocks were freed -- no leaks are possible
==17211==
==17211== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==17211== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

I know that if a string is less than 16 bytes it doesn't allocate memory and uses a char buffer (optimization), but makes no sense to me this memory leak. Does anyone have an idea what is wrong with my code?

答:
You already know why the size of the leaks depend on each string's content (short string optimization vs dynamic allocation).

The leaks themselves are because AuthBase does not have a virtual destructor.

When the std::unique_ptr member in Client is destroyed, it will call delete on the AuthBase* pointer it is holding. And since AuthBase's (default-generated) destructor is not virtual, APIAuthetication's destructor will be not called, thus its 2 std::string members will not be destroyed, leaking any memory they have allocated for themselves.

You need to add a virtual destructor to AuthBase:

```<code>class AuthBase {
public:
    virtual ~AuthBase() = default;
    ...
};
</code>```

And then change APIAuthetication's destructor to override that destructor:

```<code>class APIAuthetication : public AuthBase {
public:
    ...
    ~APIAuthetication() override = default;
    ...
};
</code>```

The same goes with your ClientBase class and its derived classes, too.

```<code>class ClientBase {
public:
    virtual ~ClientBase() = default;
    ...
};

class Client : public ClientBase {
public:
    ...
    ~Client() override = default;
    ...
};

class ClientAPI : public Client {
public:
    ...
    ~ClientAPI() override = default;
};
</code>```

Rule of thumb: if a class can be derived from, it should declare (or inherit) a virtual destructor.

On a side note, it is not a good idea for Client's constructor to take a raw AuthBase* pointer as input. It should take a std::unique_ptr<AuthBase> instead.  In modern C++ coding, it is best to stay away from calling new/delete directly whenever possible. Let smart pointers do their job cradle-to-grave, so to speak.

```<code>class Client : public ClientBase {
public:
    Client(std::unique_ptr<AuthBase> auth) : m_auth(std::move(auth)) {}
    ...
private:
    std::unique_ptr<AuthBase> m_auth;
};

class ClientAPI : public Client {
public:
    ClientAPI(const std::string &api_key, const std::string &api_secret) :
        Client(std::make_unique<APIAuthetication>(api_key, api_secret)) {}
    ...
};
</code>```

Body:
I am getting a memory leaking in C++ depending on the string size. On the code bellow if the string size is less than 15 valgrind doesn't shows leak, however if string size is greater than 15 I am getting memory leaks:

#include <string>
#include <memory>
#include <iostream>

class AuthBase {
public:
    virtual void foo() = 0;
};

class APIAuthetication : public AuthBase {
public:
    APIAuthetication(const std::string api_key, const std::string api_secret) : m_api_key(api_key),
                m_api_secret(api_secret) {}

    virtual ~APIAuthetication() {}

    void foo() {}
private:
    const std::string m_api_key;
    const std::string m_api_secret;
};

class ClientBase {
public:
    virtual void bar() = 0;
};

class Client: public ClientBase {
public:
    Client(AuthBase* auth) : m_auth(auth) {}
    ~Client() {}

    void bar() {}
private:
    std::unique_ptr<AuthBase> m_auth;
};

class ClientAPI : public Client {
public:
    ClientAPI(const std::string api_key, const std::string api_secret) :
                Client((new APIAuthetication(api_key, api_secret))) {}
    virtual ~ClientAPI() {}
};

int main(void) {
    /* This runs fine. String size == 15 */
    ClientAPI cli("123456789101112", "123456789101112");
    /* Memory leak. String size > 15 */
    ClientAPI cli_leak("1234567891011121", "1234567891011121");
    return 0;
}

==17060== HEAP SUMMARY:
==17060==     in use at exit: 34 bytes in 2 blocks
==17060==   total heap usage: 9 allocs, 7 frees, 72,950 bytes allocated
==17060==
==17060== Searching for pointers to 2 not-freed blocks
==17060== Checked 111,624 bytes
==17060==
==17060== 17 bytes in 1 blocks are definitely lost in loss record 1 of 2
==17060==    at 0x4C3217F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17060==    by 0x4F6513C: void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_construct<char*>(char*, char*, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)
==17060==    by 0x1091B3: APIAuthetication::APIAuthetication(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x10937C: ClientAPI::ClientAPI(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x108FD3: main (in /home/rogerio/code-studies/curl-examples/weird)
==17060==
==17060== 17 bytes in 1 blocks are definitely lost in loss record 2 of 2
==17060==    at 0x4C3217F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17060==    by 0x4F6513C: void std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_construct<char*>(char*, char*, std::forward_iterator_tag) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)
==17060==    by 0x1091CA: APIAuthetication::APIAuthetication(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x10937C: ClientAPI::ClientAPI(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >) (in /home/rogerio/code-studies/curl-examples/weird)
==17060==    by 0x108FD3: main (in /home/rogerio/code-studies/curl-examples/weird)
==17060==
==17060== LEAK SUMMARY:
==17060==    definitely lost: 34 bytes in 2 blocks
==17060==    indirectly lost: 0 bytes in 0 blocks
==17060==      possibly lost: 0 bytes in 0 blocks
==17060==    still reachable: 0 bytes in 0 blocks
==17060==         suppressed: 0 bytes in 0 blocks
==17060==
==17060== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
==17060== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

No leaks if string size is < 15:

==17211==
==17211== HEAP SUMMARY:
==17211==     in use at exit: 0 bytes in 0 blocks
==17211==   total heap usage: 2 allocs, 2 frees, 72,776 bytes allocated
==17211==
==17211== All heap blocks were freed -- no leaks are possible
==17211==
==17211== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==17211== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I know that if a string is less than 16 bytes it doesn't allocate memory and uses a char buffer (optimization), but makes no sense to me this memory leak. Does anyone have an idea what is wrong with my code?

Body:
You already know why the size of the leaks depend on each string's content (short string optimization vs dynamic allocation).

The leaks themselves are because AuthBase does not have a virtual destructor.

When the std::unique_ptr member in Client is destroyed, it will call delete on the AuthBase* pointer it is holding. And since AuthBase's (default-generated) destructor is not virtual, APIAuthetication's destructor will be not called, thus its 2 std::string members will not be destroyed, leaking any memory they have allocated for themselves.

You need to add a virtual destructor to AuthBase:

class AuthBase {
public:
    virtual ~AuthBase() = default;
    ...
};

And then change APIAuthetication's destructor to override that destructor:

class APIAuthetication : public AuthBase {
public:
    ...
    ~APIAuthetication() override = default;
    ...
};

The same goes with your ClientBase class and its derived classes, too.

class ClientBase {
public:
    virtual ~ClientBase() = default;
    ...
};

class Client : public ClientBase {
public:
    ...
    ~Client() override = default;
    ...
};

class ClientAPI : public Client {
public:
    ...
    ~ClientAPI() override = default;
};

Rule of thumb: if a class can be derived from, it should declare (or inherit) a virtual destructor.

On a side note, it is not a good idea for Client's constructor to take a raw AuthBase* pointer as input. It should take a std::unique_ptr<AuthBase> instead.  In modern C++ coding, it is best to stay away from calling new/delete directly whenever possible. Let smart pointers do their job cradle-to-grave, so to speak.

class Client : public ClientBase {
public:
    Client(std::unique_ptr<AuthBase> auth) : m_auth(std::move(auth)) {}
    ...
private:
    std::unique_ptr<AuthBase> m_auth;
};

class ClientAPI : public Client {
public:
    ClientAPI(const std::string &api_key, const std::string &api_secret) :
        Client(std::make_unique<APIAuthetication>(api_key, api_secret)) {}
    ...
};


问:
Standard Scaler Producing Unexpected Result for Just One Column
I'm doing some preprocessing on my training data before fitting it to a model. Upon checking the results, there is one column that is returning 0 rather than 1 for the standard deviation. (all columns return a mean of 0 as expected). My code is below:

```<code>y = ml_df['target']
x = ml_df[['Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5', 'Feature6',
           'Feature7', 'Feature8', 'Feature9', 'Feature10', 'Feature11', 'Feature12']]

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.55, random_state=3)

pt_hp = PowerTransformer()
x_train_gaussian = pt_hp.fit_transform(x_train)
x_test_gaussian =  pt_hp.transform(x_test)

ss_hp = StandardScaler()
std_x_train = ss_hp.fit_transform(x_train_gaussian)
std_x_test = ss_hp.transform(x_test_gaussian)
</code>```

After running the above, this line produces the following output:

```<code>print(std_x_train.std(axis = 0))
</code>```

Output: [1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1.]

This particular feature is not materially different than the others; is contains only positive values (no zeros that would impact PowerTransformer) and not anywhere close to near-zero variance. I realize the PowerTransformer also scales the data so the final 2 lines are currently unneccessary, but both x_train_gaussian and std_x_train return this output so I don't think that's the issue here.

Does anyone have any idea why this one particular column is returning such a different standard deviation than the rest? Thanks in advance for any suggestions.

答: Issue was apparently caused by long-standing SKlearn bug - https://github.com/scikit-learn/scikit-learn/issues/14959</p>

Body:
I'm doing some preprocessing on my training data before fitting it to a model. Upon checking the results, there is one column that is returning 0 rather than 1 for the standard deviation. (all columns return a mean of 0 as expected). My code is below:

y = ml_df['target']
x = ml_df[['Feature1', 'Feature2', 'Feature3', 'Feature4', 'Feature5', 'Feature6',
           'Feature7', 'Feature8', 'Feature9', 'Feature10', 'Feature11', 'Feature12']]

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.55, random_state=3)

pt_hp = PowerTransformer()
x_train_gaussian = pt_hp.fit_transform(x_train)
x_test_gaussian =  pt_hp.transform(x_test)

ss_hp = StandardScaler()
std_x_train = ss_hp.fit_transform(x_train_gaussian)
std_x_test = ss_hp.transform(x_test_gaussian)

After running the above, this line produces the following output:

print(std_x_train.std(axis = 0))

Output: [1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1.]

This particular feature is not materially different than the others; is contains only positive values (no zeros that would impact PowerTransformer) and not anywhere close to near-zero variance. I realize the PowerTransformer also scales the data so the final 2 lines are currently unneccessary, but both x_train_gaussian and std_x_train return this output so I don't think that's the issue here.

Does anyone have any idea why this one particular column is returning such a different standard deviation than the rest? Thanks in advance for any suggestions.


问:
Conditional median in MS Excel
I'm trying to calculate the conditional median of a chart that looks like this:

```<code>A  |  B
-------
x  |  1
x  |  1
x  |  3
x  |
y  |  4
z  |  5
</code>```

I'm using MS Excel 2007.  I am aware of the AVERAGEIF() statement, but there is no equivalent for Median.  The main trick is that there are rows with no data - such as the 4th "a" above.  In this case, I don't want this row considered at all in the calculations.

Googling has suggested the following, but Excel won't accept the formula format (maybe because it's 2007?)

```<code>=MEDIAN(IF((A:A="x")*(A:A<>"")), B:B)
</code>```

Excel gives an error saying there is something wrong with my formula(something to do with the * in the condition)  I had also tried the following, but it counts blank cells as 0's in the calculations:

```<code>=MEDIAN(IF(A:A = "x", B:B, "")
</code>```

I am aware that those formulas return Excel "arrays", which means one must enter "Ctrl-shift-enter" to get it to work correctly.

How can I do a conditional evaluation and not consider blank cells?

答:
Use the Googled formula, but instead of hitting Enter after you type it into the formula bar, hit Ctrl+Shift+Enter simultaneously (instead of Enter). This places brackets around the formula and will treat it as an array.

Be warned, if you edit it, you cannot hit Enter again or the formula will not be valid. If editing, you must do the same thing when done (Ctrl+Shift+Enter).

Title: Conditional median in MS Excel

Body:
I'm trying to calculate the conditional median of a chart that looks like this:

A  |  B
-------
x  |  1
x  |  1
x  |  3
x  |
y  |  4
z  |  5

I'm using MS Excel 2007.  I am aware of the AVERAGEIF() statement, but there is no equivalent for Median.  The main trick is that there are rows with no data - such as the 4th "a" above.  In this case, I don't want this row considered at all in the calculations.

Googling has suggested the following, but Excel won't accept the formula format (maybe because it's 2007?)

=MEDIAN(IF((A:A="x")*(A:A<>"")), B:B)

Excel gives an error saying there is something wrong with my formula(something to do with the * in the condition)  I had also tried the following, but it counts blank cells as 0's in the calculations:

=MEDIAN(IF(A:A = "x", B:B, "")

I am aware that those formulas return Excel "arrays", which means one must enter "Ctrl-shift-enter" to get it to work correctly.

How can I do a conditional evaluation and not consider blank cells?


问:
VirtualStringTree how to disable alpha blended selection while doing drag and drop?
When drag and dropping items from one TVirtualStringTree to another TVirtualStringTree how do I disable semi-transparent selection block shown while dragging the selection over the destination tree?

I've tried all the options and still cannot find the right one.

答: You can omit the image by changing DragType from default dtOLE to dtVCL. Additionally DragWidth can be set to 0 which will have the same effect.