问:
why can't I use the same javascript toggle button twice?
I'm attempting to utilize this javascript toggle button in two separate parts on the same page, but I'm having trouble. I tried altering the id as well, but it didn't work. Is it impossible to complete it, or am I overlooking something? I am not an expert in javascript and am a complete novice, so any help would be greatly appreciated.

function toggleText() {
  var showMoreText = document.getElementById("more");
  var buttonText   = document.querySelector("#moreButton span");
  var moreIcon     = document.querySelector("#moreButton img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less');
    moreIcon.classList.remove('less');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less');
    moreIcon.classList.add('less');
  }
}

function toggleText2() {
  var showMoreText2 = document.getElementById("more2");
  var buttonText2   = document.querySelector("#moreButton2 span");
  var moreIcon2     = document.querySelector("#moreButton2 img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less2');
    moreIcon.classList.remove('less2');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less2');
    moreIcon.classList.add('less2');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint"></div>
    <div id="more">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText()" id="moreButton">
            <span class="pink">Show More</span>
            <img class="more" src="./images/load-more.png" alt="">
            </button>
  </div>
</div>

<br>
<br>
<br>
<br>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint2"></div>
    <div id="more2">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText2()" id="moreButton2">
            <span class="pink2">Show More</span>
            <img class="more2" src="./images/load-more.png" alt="">
            </button>
  </div>
</div></code>```

答:
You had some issues with the naming of your variables etc. (things coming up as undefined).

function toggleText() {
  var showMoreText = document.getElementById("more");
  var buttonText   = document.querySelector("#moreButton span");
  var moreIcon     = document.querySelector("#moreButton img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less');
    moreIcon.classList.remove('less');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less');
    moreIcon.classList.add('less');
  }
}

function toggleText2() {
  var showMoreText2 = document.getElementById("more2");
  var buttonText2   = document.querySelector("#moreButton2 span");
  var moreIcon2     = document.querySelector("#moreButton2 img");

  if (startpoint.style.display === "none") {
    showMoreText2.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText2.innerHTML = "Show More";
    buttonText2.classList.remove('less2');
    moreIcon2.classList.remove('less2');
  } else {
    showMoreText2.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText2.innerHTML = "Show Less";
    buttonText2.classList.add('less2');
    moreIcon2.classList.add('less2');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint"></div>
    <div id="more">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText()" id="moreButton">
            <span class="pink">Show More</span>
            <img class="more" src="./images/load-more.png" alt="">
            </button>
  </div>
</div>

<br>
<br>
<br>
<br>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint2"></div>
    <div id="more2">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText2()" id="moreButton2">
            <span class="pink2">Show More</span>
            <img class="more2" src="./images/load-more.png" alt="">
            </button>
  </div>
</div></code>```

With that said, there are much cleaner ways of constructing this logic. For instance, you could parse the event and look for a certain parent or child to toggle. That way, you can utilize the same function as long as it's surrounded by the same html structure. You'd have to exchange the id's for classes however.

Body:
I'm attempting to utilize this javascript toggle button in two separate parts on the same page, but I'm having trouble. I tried altering the id as well, but it didn't work. Is it impossible to complete it, or am I overlooking something? I am not an expert in javascript and am a complete novice, so any help would be greatly appreciated.

function toggleText() {
  var showMoreText = document.getElementById("more");
  var buttonText   = document.querySelector("#moreButton span");
  var moreIcon     = document.querySelector("#moreButton img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less');
    moreIcon.classList.remove('less');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less');
    moreIcon.classList.add('less');
  }
}

function toggleText2() {
  var showMoreText2 = document.getElementById("more2");
  var buttonText2   = document.querySelector("#moreButton2 span");
  var moreIcon2     = document.querySelector("#moreButton2 img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less2');
    moreIcon.classList.remove('less2');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less2');
    moreIcon.classList.add('less2');
  }
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

    <button onclick="toggleText()" id="moreButton">
            Show More

            </button>

    <button onclick="toggleText2()" id="moreButton2">
            Show More

            </button>

Body:
You had some issues with the naming of your variables etc. (things coming up as undefined).

function toggleText() {
  var showMoreText = document.getElementById("more");
  var buttonText   = document.querySelector("#moreButton span");
  var moreIcon     = document.querySelector("#moreButton img");

  if (startpoint.style.display === "none") {
    showMoreText.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText.innerHTML = "Show More";
    buttonText.classList.remove('less');
    moreIcon.classList.remove('less');
  } else {
    showMoreText.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText.innerHTML = "Show Less";
    buttonText.classList.add('less');
    moreIcon.classList.add('less');
  }
}

function toggleText2() {
  var showMoreText2 = document.getElementById("more2");
  var buttonText2   = document.querySelector("#moreButton2 span");
  var moreIcon2     = document.querySelector("#moreButton2 img");

  if (startpoint.style.display === "none") {
    showMoreText2.style.display = "none";
    startpoint.style.display = "table-cell";
    buttonText2.innerHTML = "Show More";
    buttonText2.classList.remove('less2');
    moreIcon2.classList.remove('less2');
  } else {
    showMoreText2.style.display = "table-cell";
    startpoint.style.display = "none";
    buttonText2.innerHTML = "Show Less";
    buttonText2.classList.add('less2');
    moreIcon2.classList.add('less2');
  }
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint"></div>
    <div id="more">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText()" id="moreButton">
            <span class="pink">Show More</span>
            <img class="more" src="./images/load-more.png" alt="">
            </button>
  </div>
</div>

<br>
<br>
<br>
<br>

<div class="container-fluid clientbox text-center">
  <div class="row">
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>
    <div class="col-6 col-md-4 col-lg-3">
      <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
    </div>

    <div id="startpoint2"></div>
    <div id="more2">
      <div class="row">
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class=" col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
        <div class="col-6 col-md-4 col-lg-3">
          <img class="img-fluid brand-img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/69/How_to_use_icon.svg/100px-How_to_use_icon.svg.png" alt="Logo">
        </div>
      </div>
    </div>
    <button onclick="toggleText2()" id="moreButton2">
            <span class="pink2">Show More</span>
            <img class="more2" src="./images/load-more.png" alt="">
            </button>
  </div>
</div>

With that said, there are much cleaner ways of constructing this logic. For instance, you could parse the event and look for a certain parent or child to toggle. That way, you can utilize the same function as long as it's surrounded by the same html structure. You'd have to exchange the id's for classes however.


来源: stackexchange

问:
When is an SQS message sent to deadletter queue via redrive policy?
I have an SQS queue linked to a deadletter queue via a redrive policy. Terraform sample:

```<code>  redrive_policy = jsonencode({
    deadLetterTargetArn = aws_sqs_queue.deadletter_queue.arn
    maxReceiveCount     = 10
  })
</code>```

The queue processing is implemented with exponential backoff. If processing is successful the message is simply deleted. If processing fails it retries with an initial VisibilityTimeout of 30 seconds, which doubles each time, the final retry timeout (between 9th and 10th attempt) is roughly 2 hours.

My question is, after the final retry, when does the message get sent to the deadletter queue? Immediately after the 10th attempt or does it have to wait out the VisibilityTimeout (of about 4 hours)?.

My concern is that it seems redundant to put a visibility timeout on a message if it's just going to be sent straight to the deadletter - this delays alerts for example.

答:
Lets say you are running 2 consumers, A and B.

Visibility timeout is a time period which start right after "consumer A" receives the message. For this duration, "consumer B" is not able to receive the message (message is reserved for the "consumer A"). So visibility timeout's purpose is to "hide" message from other consumers to avoid duplication, while one of the consumers already working on it (also see aws doc here).

About the question, after the final retry, message is immediately moved to dead letter queue. It doesn't wait for a visibility timeout to be over, because it won't have the chance to be consumed again. Message is moved to dead letter queue and removed from source queue.

ContentLicense: CC BY-SA 4.0

Body:
I have an SQS queue linked to a deadletter queue via a redrive policy. Terraform sample:

  redrive_policy = jsonencode({
    deadLetterTargetArn = aws_sqs_queue.deadletter_queue.arn
    maxReceiveCount     = 10
  })

The queue processing is implemented with exponential backoff. If processing is successful the message is simply deleted. If processing fails it retries with an initial VisibilityTimeout of 30 seconds, which doubles each time, the final retry timeout (between 9th and 10th attempt) is roughly 2 hours.

My question is, after the final retry, when does the message get sent to the deadletter queue? Immediately after the 10th attempt or does it have to wait out the VisibilityTimeout (of about 4 hours)?.

My concern is that it seems redundant to put a visibility timeout on a message if it's just going to be sent straight to the deadletter - this delays alerts for example.


问:
Save Outlook email Information to SQL Server
I'm trying to save inbound Outlook mail data to sql server however I'm getting in error in System.Runtime.InteropServices.COMException: 'The attempted operation failed.  An object could not be found.' What did I missed

Note: RetrieveMail is exist in mailbox

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection; // to use Missing.Value
//using Microsoft.Office.Interop.Outlook;
using System.Data.SqlClient;
using System.Data;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace RetrieveEmail
{
    public class Program
    {
         static void Main(string[] args)
        {
            Outlook.Application oLk = new Outlook.Application();
            Outlook._NameSpace olNS = oLk.GetNamespace("MAPI");
            Outlook._Folders oFolders;
            oFolders = olNS.Folders;
            Outlook.MAPIFolder oFolder;
            oFolder = oFolders[1];
            Outlook.MAPIFolder oFolderIn = oFolder.Folders["RetrieveMail"];

            Outlook.Items oItems = oFolderIn.Items;
            foreach (Outlook.MailItem oMailItem in oFolderIn.Items)
            {
                if (oMailItem.SenderName == "sender_name")
                {

                    SqlConnection con = new SqlConnection(@"Data Source=\SQLEXPRESS; initial catalog=EmailReply;Integrated Security=True;User Instance=True");
                    SqlCommand cmd = new SqlCommand("Emails", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("Subject", oMailItem.Subject);
                    cmd.Parameters.AddWithValue("Body", oMailItem.Body);

                    con.Open();
                    int k = cmd.ExecuteNonQuery();
                    if (k != 0)
                    {
                        Console.WriteLine("Record Inserted Succesfully into the Database");

                    }
                    con.Close();
                }
            }
        }
    }
}
</code>```

答:
Use the NameSpace.GetDefaultFolder method to get the Inbox folder and then try to get the required subfolder instead. For example:

```<code>Sub DisplaySubfolderOfInboxFolder()
 Dim myNamespace As Outlook.NameSpace
 Dim myInbox As Outlook.Folder
 Dim myFolder As Outlook.Folder

 Set myNamespace = Application.GetNamespace("MAPI")
 Set myInbox = myNamespace.GetDefaultFolder(olFolderInbox)
 Set myFolder = myInbox.Folders(1)

 myFolder.Display

End Sub
</code>```

So, in your code it should look like that:

```<code>Outlook.Application oLk = new Outlook.Application();
Outlook._NameSpace olNS = oLk.GetNamespace("MAPI");
Outlook._Folders oFolders;
Outlook.MAPIFolder oFolder =  olNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Outlook.MAPIFolder oFolderIn = oFolder.Folders["RetrieveMail"];
</code>```

I've also found a possible pitfall in your code:

```<code>Outlook.Items oItems = oFolderIn.Items;
            foreach (Outlook.MailItem oMailItem in oFolderIn.Items)
            {
                if (oMailItem.SenderName == "sender_name")
                {
</code>```

Be aware, a folder may contain different kind of items. So, I'd suggest using object instead of mail item. Then you may check the item type and cast the object to the underlying type (mail, appointment and etc.).

Another point is that iterating over all items in a folder is not really a good idea. Use the Find/FindNext mehtods of the Items class instead. Read more about these methods in the following articles:

How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

How To: Use Restrict method to retrieve Outlook mail items from a folder

Body:
I'm trying to save inbound Outlook mail data to sql server however I'm getting in error in System.Runtime.InteropServices.COMException: 'The attempted operation failed.  An object could not be found.' What did I missed

Note: RetrieveMail is exist in mailbox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection; // to use Missing.Value
//using Microsoft.Office.Interop.Outlook;
using System.Data.SqlClient;
using System.Data;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace RetrieveEmail
{
    public class Program
    {
         static void Main(string[] args)
        {
            Outlook.Application oLk = new Outlook.Application();
            Outlook._NameSpace olNS = oLk.GetNamespace("MAPI");
            Outlook._Folders oFolders;
            oFolders = olNS.Folders;
            Outlook.MAPIFolder oFolder;
            oFolder = oFolders[1];
            Outlook.MAPIFolder oFolderIn = oFolder.Folders["RetrieveMail"];

            Outlook.Items oItems = oFolderIn.Items;
            foreach (Outlook.MailItem oMailItem in oFolderIn.Items)
            {
                if (oMailItem.SenderName == "sender_name")
                {

                    SqlConnection con = new SqlConnection(@"Data Source=\SQLEXPRESS; initial catalog=EmailReply;Integrated Security=True;User Instance=True");
                    SqlCommand cmd = new SqlCommand("Emails", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("Subject", oMailItem.Subject);
                    cmd.Parameters.AddWithValue("Body", oMailItem.Body);

                    con.Open();
                    int k = cmd.ExecuteNonQuery();
                    if (k != 0)
                    {
                        Console.WriteLine("Record Inserted Succesfully into the Database");

                    }
                    con.Close();
                }
            }
        }
    }
}

Body:
Use the NameSpace.GetDefaultFolder method to get the Inbox folder and then try to get the required subfolder instead. For example:

Sub DisplaySubfolderOfInboxFolder()
 Dim myNamespace As Outlook.NameSpace
 Dim myInbox As Outlook.Folder
 Dim myFolder As Outlook.Folder

 Set myNamespace = Application.GetNamespace("MAPI")
 Set myInbox = myNamespace.GetDefaultFolder(olFolderInbox)
 Set myFolder = myInbox.Folders(1)

 myFolder.Display

End Sub

So, in your code it should look like that:

Outlook.Application oLk = new Outlook.Application();
Outlook._NameSpace olNS = oLk.GetNamespace("MAPI");
Outlook._Folders oFolders;
Outlook.MAPIFolder oFolder =  olNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Outlook.MAPIFolder oFolderIn = oFolder.Folders["RetrieveMail"];

I've also found a possible pitfall in your code:

Outlook.Items oItems = oFolderIn.Items;
            foreach (Outlook.MailItem oMailItem in oFolderIn.Items)
            {
                if (oMailItem.SenderName == "sender_name")
                {

Be aware, a folder may contain different kind of items. So, I'd suggest using object instead of mail item. Then you may check the item type and cast the object to the underlying type (mail, appointment and etc.).

Another point is that iterating over all items in a folder is not really a good idea. Use the Find/FindNext mehtods of the Items class instead. Read more about these methods in the following articles:

How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)

How To: Use Restrict method to retrieve Outlook mail items from a folder


问:
How to get only repeated records in a table?
I couldn't figure out how better to ask this question, so my searches became desperate.

I have a table with three columns(Column1, Column2, Column3). There are lots of records consisted of different and same values in it. I want to get only the exactly same records as column1, column2 and column3 values. How can I get them in the fastest query in general SQL? And especially HSQLDB?

Besides, if my table has 4 columns (+ Column4) but still I need same records of column1,column2 and column3 values. Query must change or will be same?

Example;

```<code>-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    3    |    3    |   10    |
|    4    |    12   |   3     |  <-- C
|    1    |    3    |   3     |
|    1    |    4    |   3     |
|    1    |    5    |   3     |
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------
</code>```

So I need to select all A,B and C records. The result should be;

```<code>-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    4    |    12   |   3     |  <-- C
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------
</code>```

-Result omitted completely different records-

答:
Get them by grouping in combination with a HAVING clause. This should also work in HSQLDB. The HAVING clause removes all data from result a rows isn't contained multiple. When you have a table with 4 columns you have to adopt the statement.

```<code>SELECT Column1,Column2,Column3 FROM Table GROUP BY Column1,Column2,Column3 HAVING COUNT(*)>1
</code>```

EDIT: edited to get all rows

```<code>SELECT x.* FROM Table x INNER JOIN (
    SELECT Column1,Column2,Column3 FROM Table GROUP BY Column1,Column2,Column3 HAVING COUNT(*)>1
) y ON x.Column1=y.Column1 AND x.Column2=y.Column2 AND x.Column3=y.Column3
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I couldn't figure out how better to ask this question, so my searches became desperate.

I have a table with three columns(Column1, Column2, Column3). There are lots of records consisted of different and same values in it. I want to get only the exactly same records as column1, column2 and column3 values. How can I get them in the fastest query in general SQL? And especially HSQLDB?

Besides, if my table has 4 columns (+ Column4) but still I need same records of column1,column2 and column3 values. Query must change or will be same?

Example;

-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    3    |    3    |   10    |
|    4    |    12   |   3     |  <-- C
|    1    |    3    |   3     |
|    1    |    4    |   3     |
|    1    |    5    |   3     |
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------

So I need to select all A,B and C records. The result should be;

-------------------------------
| Column1 | Column2 | Column3 |
|    1    |    2    |   3     |  <-- A
|    2    |    2    |   30    |  <-- B
|    4    |    12   |   3     |  <-- C
|    4    |    12   |   3     |  <-- C
|    2    |    2    |   30    |  <-- B
|    1    |    2    |   3     |  <-- A
|    4    |    12   |   3     |  <-- C
-------------------------------

-Result omitted completely different records-

Body:
Get them by grouping in combination with a HAVING clause. This should also work in HSQLDB. The HAVING clause removes all data from result a rows isn't contained multiple. When you have a table with 4 columns you have to adopt the statement.

SELECT Column1,Column2,Column3 FROM Table GROUP BY Column1,Column2,Column3 HAVING COUNT(*)>1

EDIT: edited to get all rows

SELECT x.* FROM Table x INNER JOIN (
    SELECT Column1,Column2,Column3 FROM Table GROUP BY Column1,Column2,Column3 HAVING COUNT(*)>1
) y ON x.Column1=y.Column1 AND x.Column2=y.Column2 AND x.Column3=y.Column3


问:
Valid Representation of unicode Sequence in Java
I have presto query that contains some Japanese characters in where clause

```<code>select col1  from xyz where col = '自社在庫' // example
</code>```

for some reason i need to interpret this query  and do some validations, for this i am using the facebook presto sql parser .
But when i use com.facebook.presto.sql.SqlFormatter.formatSql(sqlParsed, null);
The returned String looks like this :

```<code>SELECT col1 FROM xyz WHERE (colr = **U&'\81EA\793E\5728\5EAB'**)
</code>```

Should it not convert it as select col1 from xyz where colr = '\u81EA\u793E\u5728\u5EAB'

Any way i can convert U&'\81EA\793E\5728\5EAB' back to '自社在庫' ?

答:
It seems the presto serializer does something different than you expect. I'd try to search for a solution within the presto library.

If that does not work, you could translate the string by stripping off the leading and trailing asterisks, then replace every \ with \u and are back to your assumed result.

Body:
I have presto query that contains some Japanese characters in where clause

select col1  from xyz where col = '自社在庫' // example

for some reason i need to interpret this query  and do some validations, for this i am using the facebook presto sql parser .
But when i use com.facebook.presto.sql.SqlFormatter.formatSql(sqlParsed, null);
The returned String looks like this :

SELECT col1 FROM xyz WHERE (colr = **U&'\81EA\793E\5728\5EAB'**)

Should it not convert it as select col1 from xyz where colr = '\u81EA\u793E\u5728\u5EAB'

Any way i can convert U&'\81EA\793E\5728\5EAB' back to '自社在庫' ?


问:
Recoded missing cells to NA but still showing up in table
I'm trying to build a table using gtsummary.  I"m converting columns to factors, then recoding the factors, then assigning values (" ", "U") to be missing.

However, when I then make the table, the levels that are assigned "missing" still show up as levels in the table.  How do I get them to be hidden?

```<code>data <- tribble(
  ~Patient, ~malig, ~donor,
  #---------/-------/------
  "Peter", "Y", "DCD",
  "Bob", "N", "DBD",
  "John", "U", "DCD",
  "Kate", " ", "DBD"
)

names<-c('malig','donor')

data[,names]<-lapply(data[,names], factor)

data$malig<-recode_factor(data$malig,
                              "N"="No",
                              "Y"="Yes")

data <- data %>%
  mutate_all(na_if,"") %>%
  mutate_all(na_if,"U") %>%
  mutate_all(na_if," ")

(table1 <-
  tbl_summary(
    data,
    by = donor,
    missing="no",
    label=list(malig ~ "Malignancy History")
  ) %>%
  add_n() %>%
  add_p() %>%
  modify_header() %>%
  add_overall())
</code>```

答: The tbl_summary() function will report all levels of a factor variable, even if they are unobserved. If you don't want to report the unobserved levels, you need to remove the unobserved levels from the factor levels. In this example, you can make the values NA before you make the columns factors.

Body:
I'm trying to build a table using gtsummary.  I"m converting columns to factors, then recoding the factors, then assigning values (" ", "U") to be missing.

However, when I then make the table, the levels that are assigned "missing" still show up as levels in the table.  How do I get them to be hidden?

data <- tribble(
  ~Patient, ~malig, ~donor,
  #---------/-------/------
  "Peter", "Y", "DCD",
  "Bob", "N", "DBD",
  "John", "U", "DCD",
  "Kate", " ", "DBD"
)

names<-c('malig','donor')

data[,names]<-lapply(data[,names], factor)

data$malig<-recode_factor(data$malig,
                              "N"="No",
                              "Y"="Yes")

data <- data %>%
  mutate_all(na_if,"") %>%
  mutate_all(na_if,"U") %>%
  mutate_all(na_if," ")

(table1 <-
  tbl_summary(
    data,
    by = donor,
    missing="no",
    label=list(malig ~ "Malignancy History")
  ) %>%
  add_n() %>%
  add_p() %>%
  modify_header() %>%
  add_overall())


问:
Memory Leak in React component using useEffect
Im doing a Carrousel that when it opens a "news" you can see a description in a modal, that works perfect, but when you click on a offer you redirect to another page with the info about that product.

It's working but when you do it, in the consolo shows the error of memory leak
"react-dom.development.js:67 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

I'm knew using useEffect and I don't know how to avoid this.

Thanks for your time

This is the "AxiosCollection"

import axios from "axios";
const baseURL = "http://localhost:8080";

function AxiosGetData(url, setData) {
  axios
    .get(`${baseURL}${url}`, {
      headers: {
        "Content-type": "application/json",
      },
    })
    .then((response) => {
      setData(response.data);
    })
    .catch((error) => {
      return error;
    });
}

export {
  AxiosGetData
};```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useState, useEffect } from "react";
import { AxiosGetData } from "../AxiosCollection/AxiosCollection";
import Modal from "../Modal/Modal";
import { Link } from "react-router-dom";

// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/swiper-bundle.min.css";
import "swiper/swiper.min.css";

import BenefitCard from "../";

//Css file
import "./Slider.css";

// import Swiper core and required modules
import SwiperCore, { Pagination, Navigation } from "swiper";

// install Swiper modules
SwiperCore.use([Pagination, Navigation]);

const Slider = () => {
  //state to populate with featured object from API
  const [featured, setFeatured] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [featuredById, setFeaturedById] = useState();
  const onCloseRequest = () => setIsOpen(false);

  // hook to fetch data with Axios,it only runs once, takes an url and a function as params

  const handleClick = (item) => {
    AxiosGetData(`/jp-coin/featured/${item.featuredId}`, setFeaturedById);
    setIsOpen(true);
  };

  useEffect(() => {
    AxiosGetData("/...", setFeatured);

  }, []);

  return (
    <Swiper
      slidesPerView={1}
      spaceBetween={30}
      slidesPerGroup={1}
      loop={true}
      loopFillGroupWithBlank={true}
      pagination={{ clickable: true }}
      navigation={true}
      breakpoints={{
        768: {
          slidesPerView: 3,
          spaceBetween: 30,
          slidesPerGroup: 3,
        },
      }}
      className="mySwiper"
    >
      {featured.map((item) => (
        <SwiperSlide key={item.featuredId} onClick={() => handleClick(item)}>
          <Link to={item.type === "offer" ? `/jp-coin/offers/${item.featuredId}` : "/"}>
            <BenefitCard benefit={item} />
          </Link>
        </SwiperSlide>
      ))}
      {featuredById && featuredById.type === "news" && (
        <>
          <Modal
            isOpen={isOpen}
            onCloseRequest={onCloseRequest}
            className="slider__modalContainer"
          >
            <img src={featuredById.image} alt={featuredById.title} />
            <h1 className="slider__modalTitle">{featuredById.title}</h1>
            <p className="slider__modalDescription">
              Lorem ipsum dolor sit, amet consectetur adipisicing elit. Hic
              blanditiis aperiam fuga ex, ratione recusandae ut harum, nam
              doloremque veniam necessitatibus, fugiat delectus placeat possimus
              totam sequi. Minus, at vitae.
            </p>
          </Modal>
        </>
      )}
      ;
    </Swiper>
  );
};

export default Slider;</code>```

答:
I think your issue may be coming from handleClick and not useEffect. When you click on any of your items (regardless if it has type "news" or "offer") your click handler will call AxiosGetData and then try to perform state updates (setFeatureById and setIsOpen) to show the modal. But for "offer" items you are also redirecting to a detail page, so your Slider component becomes unmounted before the state updates can occur which is probably why you are getting the memory leak warning. If you want to prevent state updates from happening for "offer" items you can change handleClick to:

  const handleClick = (item) => {
    if (item.type === 'news') {
      AxiosGetData(`/jp-coin/featured/${item.featuredId}`, setFeaturedById);
      setIsOpen(true);
    }
  };
```

Body:
Im doing a Carrousel that when it opens a "news" you can see a description in a modal, that works perfect, but when you click on a offer you redirect to another page with the info about that product.

It's working but when you do it, in the consolo shows the error of memory leak
"react-dom.development.js:67 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

I'm knew using useEffect and I don't know how to avoid this.

Thanks for your time

This is the "AxiosCollection"

import axios from "axios";
const baseURL = "http://localhost:8080";

function AxiosGetData(url, setData) {
  axios
    .get(`${baseURL}${url}`, {
      headers: {
        "Content-type": "application/json",
      },
    })
    .then((response) => {
      setData(response.data);
    })
    .catch((error) => {
      return error;
    });
}

export {
  AxiosGetData
};

import React, { useState, useEffect } from "react";
import { AxiosGetData } from "../AxiosCollection/AxiosCollection";
import Modal from "../Modal/Modal";
import { Link } from "react-router-dom";

// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/swiper-bundle.min.css";
import "swiper/swiper.min.css";

import BenefitCard from "../";

//Css file
import "./Slider.css";

// import Swiper core and required modules
import SwiperCore, { Pagination, Navigation } from "swiper";

// install Swiper modules
SwiperCore.use([Pagination, Navigation]);

const Slider = () => {
  //state to populate with featured object from API
  const [featured, setFeatured] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [featuredById, setFeaturedById] = useState();
  const onCloseRequest = () => setIsOpen(false);

  // hook to fetch data with Axios,it only runs once, takes an url and a function as params

  const handleClick = (item) => {
    AxiosGetData(`/jp-coin/featured/${item.featuredId}`, setFeaturedById);
    setIsOpen(true);
  };

  useEffect(() => {
    AxiosGetData("/...", setFeatured);

  }, []);

  return (
    <Swiper
      slidesPerView={1}
      spaceBetween={30}
      slidesPerGroup={1}
      loop={true}
      loopFillGroupWithBlank={true}
      pagination={{ clickable: true }}
      navigation={true}
      breakpoints={{
        768: {
          slidesPerView: 3,
          spaceBetween: 30,
          slidesPerGroup: 3,
        },
      }}
      className="mySwiper"
    >
      {featured.map((item) => (
        <SwiperSlide key={item.featuredId} onClick={() => handleClick(item)}>
          <Link to={item.type === "offer" ? `/jp-coin/offers/${item.featuredId}` : "/"}>
            <BenefitCard benefit={item} />
          </Link>
        </SwiperSlide>
      ))}
      {featuredById && featuredById.type === "news" && (
        <>
          <Modal
            isOpen={isOpen}
            onCloseRequest={onCloseRequest}
            className="slider__modalContainer"
          >

{featuredById.title}

              Lorem ipsum dolor sit, amet consectetur adipisicing elit. Hic
              blanditiis aperiam fuga ex, ratione recusandae ut harum, nam
              doloremque veniam necessitatibus, fugiat delectus placeat possimus
              totam sequi. Minus, at vitae.

          </Modal>
        </>
      )}
      ;
    </Swiper>
  );
};

export default Slider;


问:
Unable to load SQLite.Interop.dll C#
I am working on a project using SQLite - getting above error when trying to open the Connection, using SQLite for the first time.

Followed below links amongst others but error still persists - any pointers appreciated

Visual Studio C# - SQLite.Interop.dll not found

Unable to load DLL 'SQLite.Interop.dll'

Package.config

```<code><packages>
<package id="EntityFramework" version="6.4.4" targetFramework="net471"/>
<package id="System.Data.SQLite" version="1.0.112.2"targetFramework="net471" />
<package id="System.Data.SQLite.Core" version="1.0.112.2"targetFramework="net471" />
<package id="System.Data.SQLite.EF6" version="1.0.112.2"targetFramework="net471" />
<package id="System.Data.SQLite.Linq" version="1.0.112.2"targetFramework="net471" />
</packages>
</code>```

Now getting below Error:-

It's any CPU

答: Your post-build step is wrong, I think. You should copy the folder x86, not only its contents. Also, since presumably your application runs in 64 bit mode, you also need to copy the x64 folder. So in the end, you have two folders x86 and x64 below the folder with your main executable, both of them containing a file called SQLite.interop.dll.

Title: Unable to load SQLite.Interop.dll C#

Body:
I am working on a project using SQLite - getting above error when trying to open the Connection, using SQLite for the first time.

Followed below links amongst others but error still persists - any pointers appreciated

Visual Studio C# - SQLite.Interop.dll not found

Unable to load DLL 'SQLite.Interop.dll'

Package.config

<packages>
<package id="EntityFramework" version="6.4.4" targetFramework="net471"/>
<package id="System.Data.SQLite" version="1.0.112.2"targetFramework="net471" />
<package id="System.Data.SQLite.Core" version="1.0.112.2"targetFramework="net471" />
<package id="System.Data.SQLite.EF6" version="1.0.112.2"targetFramework="net471" />
<package id="System.Data.SQLite.Linq" version="1.0.112.2"targetFramework="net471" />
</packages>

Now getting below Error:-

It's any CPU


问:
Add standard deviation text overlay on ggplot geom_point()
A plot:

```<code>library(tidyverse)
diamonds |>
  filter(x > 0) |>
  ggplot(aes(x = x, y = log(price))) +
  geom_point()
</code>```

Looks like this:

The standard deviation of log(diamonds$Price) (filtered where x > 0) is 1.014611:

```<code>diamonds |>
  filter(x > 0) |>
  pull(price) |>
  log() |>
  sd() # 1.014611
</code>```

I wouldlike to overlay this on top of my plot somewhere and call it just 'sd'. In this case it would say 'sd = 1.014611'. Can I do this?

[EDIT]

Bonus if across facets. Tried:

```<code>annotations <- diamonds |>
  filter(x > 0) |>
  group_by(cut) |>
  summarise(sd_log_price = paste0("sd = ", round(sd(log(price)), 2)))

diamonds |>
  filter(x > 0) |>
  ggplot(aes(x = x, y = log(price))) +
  geom_point() +
  geom_text(label = annotations$sd_log_price) + # Error: Aesthetics must be either length 1 or the same as the data (53932): label
  facet_wrap(. ~ cut)
</code>```

But this throws the error in the comment.

答:
There are a number of nearly synonymous ways of getting text onto a plot (e.g. ggplot2::annotate(), ggplot2::geom_text()).

Note here that I used the {magrittr} pipe (%>%) instead of the new native pipe (|>) to make use of the . function of the former in the paste0() to create the annotation.

library(tidyverse)

annotation <- diamonds |>
  filter(x > 0) |>
  pull(price) |>
  log() |>
  sd() |>
  round(6) %>%
  paste0("sd = ", .)

diamonds |>
  filter(x > 0) |>
  ggplot(aes(x = x, y = log(price))) +
  geom_point() +
  geom_text(aes(label = annotation, x = -Inf, y = Inf), hjust = -0.5, vjust = 2, size = 6)
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
A plot:

library(tidyverse)
diamonds |>
  filter(x > 0) |>
  ggplot(aes(x = x, y = log(price))) +
  geom_point()

Looks like this:

The standard deviation of log(diamonds$Price) (filtered where x > 0) is 1.014611:

diamonds |>
  filter(x > 0) |>
  pull(price) |>
  log() |>
  sd() # 1.014611

I wouldlike to overlay this on top of my plot somewhere and call it just 'sd'. In this case it would say 'sd = 1.014611'. Can I do this?

[EDIT]

Bonus if across facets. Tried:

annotations <- diamonds |>
  filter(x > 0) |>
  group_by(cut) |>
  summarise(sd_log_price = paste0("sd = ", round(sd(log(price)), 2)))

diamonds |>
  filter(x > 0) |>
  ggplot(aes(x = x, y = log(price))) +
  geom_point() +
  geom_text(label = annotations$sd_log_price) + # Error: Aesthetics must be either length 1 or the same as the data (53932): label
  facet_wrap(. ~ cut)

But this throws the error in the comment.

Body:
There are a number of nearly synonymous ways of getting text onto a plot (e.g. ggplot2::annotate(), ggplot2::geom_text()).

Note here that I used the {magrittr} pipe (%>%) instead of the new native pipe (|>) to make use of the . function of the former in the paste0() to create the annotation.

library(tidyverse)

annotation <- diamonds |>
  filter(x > 0) |>
  pull(price) |>
  log() |>
  sd() |>
  round(6) %>%
  paste0("sd = ", .)

diamonds |>
  filter(x > 0) |>
  ggplot(aes(x = x, y = log(price))) +
  geom_point() +
  geom_text(aes(label = annotation, x = -Inf, y = Inf), hjust = -0.5, vjust = 2, size = 6)

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
How to serve a file with "Content-Encoding: gzip" header?
I have a game that I want run on my apache server.

When I try to view a game activity instance I redirect to the index.html file of the uploaded game.

Here is the code in view.php:

```<code>    $fp = get_file_packer('application/zip');
    $dest = $CFG->dirroot.'/mod/game/games/'.$file->get_filename().'_extracted';
    // Extract the stored_file instance into this destination.
    $files = $fp->extract_to_pathname($file, $dest);

    $fullurl = moodle_url::make_file_url('/mod/game/games/',$file->get_filename().'_extracted/index.html');
    redirect($fullurl);
</code>```

Here is the .htaccess file for the unity web gl build:

```<code>IfModule mod_mime.c

RemoveType .gz
AddEncoding gzip .gz
AddType application/octet-stream .data.gz
AddType application/wasm .wasm.gz
AddType application/javascript .js.gz
AddType application/octet-stream .symbols.json.gz

AddType applicationwasm .wasm

AddEncoding gzip .unityweb

IfModule
</code>```

After redirecting the game won't load at all and there is one error in the console which is:

'Failed to load resource: the server responded with a status of 500 (Internal Server Error)'

答: I noticed that I didn't have decompression fallback enabled in my publishing settings on my unity project, that resolved my issue.</p>

Body:
I have a game that I want run on my apache server.

When I try to view a game activity instance I redirect to the index.html file of the uploaded game.

Here is the code in view.php:

    $fp = get_file_packer('application/zip');
    $dest = $CFG->dirroot.'/mod/game/games/'.$file->get_filename().'_extracted';
    // Extract the stored_file instance into this destination.
    $files = $fp->extract_to_pathname($file, $dest);

    $fullurl = moodle_url::make_file_url('/mod/game/games/',$file->get_filename().'_extracted/index.html');
    redirect($fullurl);

Here is the .htaccess file for the unity web gl build:

IfModule mod_mime.c

RemoveType .gz
AddEncoding gzip .gz
AddType application/octet-stream .data.gz
AddType application/wasm .wasm.gz
AddType application/javascript .js.gz
AddType application/octet-stream .symbols.json.gz

AddType applicationwasm .wasm

AddEncoding gzip .unityweb

IfModule

After redirecting the game won't load at all and there is one error in the console which is:

'Failed to load resource: the server responded with a status of 500 (Internal Server Error)'


问:
C, 2D Array, How to find specific number in all 8 directions
You are allowed to enter only 0 and 1 as values in the arrays. Then in place of all elements having a value of 0, enter the number of elements with a value of 1 around that element in all eight directions. And on the end print the 2d array and the values with 1 change to *.

Here is an example how it's supposed to look like:

Here is my code

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

int main()
{
int n,m;
scanf("%d%d", &n, &m);
int a[n][m];
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        scanf("%d", &a[i][j]);
        if(a[i][j]==1){
            a[i][j]=9;
        }
    }
}
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        int counter=0;
        if(a[i][j]==9){
            printf("*\t");
        }else if(a[i][j]==0){
        if(a[i+1][j+1]==9 && i!=n && j!=m) counter++;
        if(a[i-1][j-1]==9 && i!=0 && j!=0) counter++;
        if(a[i+1][j-1]==9 && i!=n && j!=0) counter++;
        if(a[i-1][j+1]==9 && i!=0 && j!=m) counter++;
        if(a[i][j+1]==9 && j!=m) counter++;
        if(a[i][j-1]==9 && j!=0) counter++;
        if(a[i+1][j]==9 && i!=n) counter++;
        if(a[i-1][j]==9 && i!=0) counter++;
        a[i][j]=counter;
        counter=0;
        printf("%d\t", a[i][j]);
        }
    }
    printf("\n");
 }

return 0;
}
</code>```

答:
Not sure what the question is, but there are bugs in the code -
you are accessing out of array boundaries by doing, for example, this:

```<code>if(a[i-1][j-1]==9 && i!=0 && j!=0)
</code>```

When i and j are zeros you are reading the value of a[-1][-1]. Changing the order of conditions and checking i and j first would guard against such an access.
Same happens when you access the "borders" of the matrix.
And, the "i!=n && j!=m" condition is always true within the loops - you iterate as long as i<n and j<m.

But aside of that, some of these accesses in fact read from within the array, but from a wrong location.
Here is an example that shows that:

Given the matrix of 2x2

```<code>0 1
1 0
</code>```

This is the result your code produced:

```<code>2   *
*   3
</code>```

Where obviously, '3' is wrong.

Why it happened?
The 2D array is in fact stored as a 1D array in memory, like this:

```<code>0  1  1  0  // this is your data

0  1  2  3  // this is the index in the array (offset from the array start)
</code>```

And each element is located at an offset of row*columns+column from the array start (i.e. this is the formula to find the index in 1D array given i and j).
When you count the '1'-neighbours for the last element (a[1][1] in this example), you count the two obvious results (at a[1][0] and a[0][1]), but then you hit this condition:

```<code>if(a[i-1][j+1]==9 && i!=0 && j!=m)
</code>```

For this last cell, i is 1 and j is 1, so the second part of the condition is true.
But what about a[i-1][j+1]==9 ?
This references a memory at row*columns+column, right? I.e. (i-1)*2+(j+1), because that's what you tried to access. Substituting i and j with 1 and 1, and you get offset 2 in the 1D array above.
Which is 1 in the input matrix (or actually 9 since you've replaced it).
So you count it twice.

Guarding better against "stepping out" of the matrix (but not necessarily out of the actual array) will solve this bug.

Body:
You are allowed to enter only 0 and 1 as values in the arrays. Then in place of all elements having a value of 0, enter the number of elements with a value of 1 around that element in all eight directions. And on the end print the 2d array and the values with 1 change to *.

Here is an example how it's supposed to look like:

Here is my code

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n,m;
scanf("%d%d", &n, &m);
int a[n][m];
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        scanf("%d", &a[i][j]);
        if(a[i][j]==1){
            a[i][j]=9;
        }
    }
}
for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
        int counter=0;
        if(a[i][j]==9){
            printf("*\t");
        }else if(a[i][j]==0){
        if(a[i+1][j+1]==9 && i!=n && j!=m) counter++;
        if(a[i-1][j-1]==9 && i!=0 && j!=0) counter++;
        if(a[i+1][j-1]==9 && i!=n && j!=0) counter++;
        if(a[i-1][j+1]==9 && i!=0 && j!=m) counter++;
        if(a[i][j+1]==9 && j!=m) counter++;
        if(a[i][j-1]==9 && j!=0) counter++;
        if(a[i+1][j]==9 && i!=n) counter++;
        if(a[i-1][j]==9 && i!=0) counter++;
        a[i][j]=counter;
        counter=0;
        printf("%d\t", a[i][j]);
        }
    }
    printf("\n");
 }

return 0;
}

Body:
Not sure what the question is, but there are bugs in the code -
you are accessing out of array boundaries by doing, for example, this:

if(a[i-1][j-1]==9 && i!=0 && j!=0)

When i and j are zeros you are reading the value of a[-1][-1]. Changing the order of conditions and checking i and j first would guard against such an access.
Same happens when you access the "borders" of the matrix.
And, the "i!=n && j!=m" condition is always true within the loops - you iterate as long as i<n and j<m.

But aside of that, some of these accesses in fact read from within the array, but from a wrong location.
Here is an example that shows that:

Given the matrix of 2x2

0 1
1 0

This is the result your code produced:

2   *
*   3

Where obviously, '3' is wrong.

Why it happened?
The 2D array is in fact stored as a 1D array in memory, like this:

0  1  1  0  // this is your data

0  1  2  3  // this is the index in the array (offset from the array start)

And each element is located at an offset of row*columns+column from the array start (i.e. this is the formula to find the index in 1D array given i and j).
When you count the '1'-neighbours for the last element (a[1][1] in this example), you count the two obvious results (at a[1][0] and a[0][1]), but then you hit this condition:

if(a[i-1][j+1]==9 && i!=0 && j!=m)

For this last cell, i is 1 and j is 1, so the second part of the condition is true.
But what about a[i-1][j+1]==9 ?
This references a memory at row*columns+column, right? I.e. (i-1)*2+(j+1), because that's what you tried to access. Substituting i and j with 1 and 1, and you get offset 2 in the 1D array above.
Which is 1 in the input matrix (or actually 9 since you've replaced it).
So you count it twice.

Guarding better against "stepping out" of the matrix (but not necessarily out of the actual array) will solve this bug.


问:
Interacting like a Mealy machine in sequential VHDL
We're working on testing a circuit that writes to memory, so the test bench needs to read bytes from memory.  However the memory is intended to be read by a Mealy machine. The protocol for the reader is this:

It requests a read by setting oReadRequest high and setting the address bus.

It waits until the next clock period.

If before the end of that next clock period, the request has been acknowledged by iReading being high, then the reader can find the result on the data bus, and has the option of setting oReadRequest to low, or putting a new address on the address bus.

If by the end of that next clock period the request has not been acknowledged, the reader keeps the address the same and oReadRequest high and then it's back to step 2.

This is easy enough to implement in concurrent VHDL with a Mealy machine. But for the test benches I'd like to have a procedure that can read a byte, which means using only sequential statements.

Here is what we have. And it works. (At least it works in pre-synthesis testing.)  But it seems wrong somehow to have a wait based on time.  Our clock period is 10ns.  The 3 ns seems completely arbitrary.

```<code>    procedure readByte(
        signal iReading : in std_ulogic;
        signal iData : in NineBitByte;
        address : in ByteAddress;
        signal oReadRequest : out std_ulogic;
        signal oReadAddress : out ByteAddress;
        result : out NineBitByte) is
    begin

        loop
            -- Request a byte.
            oReadAddress <= address;
            oReadRequest <= '1';

            wait until rising_edge( clock );

            -- Wait for a little while
            -- to give the memory arbiter time to react
            -- to the request.
            wait for 3 ns;

            -- Is it acknowledged?
            exit when iReading = '1';
        end loop;

        result := iData;
        -- Tentatively reset the request line.
        -- A subsequent read in this cycle might
        -- overturn this assignment.
        oReadRequest <= '0';
    end procedure;
</code>```

We are using VHDL-93 in case that makes a difference.

So the specific question is whether there is a way to write the procedure without putting in arbitrary time delays.

The more general question is whether there is a way to write sequential VHDL to emulate a Mealy machine without knowing how fast the other process will react.  With concurrent assignments, an input such as iReading that might change partway trough a clock cycle can be continuously monitored and changes reacted to at any time in the clock cycle. In the code I have above, I picked a specific time in each clock cycle to observe this input.

答:
[Answering my own question.]

The key idea that I was missing is that it is possible to wait on more than one signal.  A Mealy machine needs to react not only to the clock edge, but also to other signals.  Usually this is handled using concurrency, with different processes waiting on different signals. To handle it without concurrency requires one process to wait on multiple signals.

In the particular example that I had, it gets a bit complicated, especially if I try to encapsulate the behaviour in a procedure. I found I had to write two procedures, one for bytes that are not read immediately after another has been read, and one for bytes that are to be read immediately after another has been read.  The behaviour of the procedures now depends on whether another byte (after the one that the procedure obtains) needs to be read as soon as possible or not, so I had to add two more parameters moreToRead and nextAddress. The key line is wait on iReading, clock in the second procedure.

```<code>-- Example usage: To read 3 bytes in a row.
--   readFirstByte( iReading, iData, addr, '1', addr+1,
--                  oReadRequest, oReadAddress, byte0 ) ;
--   readSubsequentByte( iReading, iData, addr+1, '1', addr+2,
--                  oReadRequest, oReadAddress, byte1 ) ;
--   readSubsequentByte( sReading, sData, addr+2, '0', anything,
--                  oReadRequest, oReadAddress, byte2 ) ;
procedure readFirstByte(
    signal iReading : in std_ulogic;
    signal iData : in NineBitByte;
    address : in ByteAddress;
    moreToRead : in std_ulogic ;
    nextAddress : in ByteAddress;
    signal oReadRequest : out std_ulogic;
    signal oReadAddress : out ByteAddress;
    result : out NineBitByte)
is
begin
    -- Request a byte.
    oReadRequest <= '1';
    oReadAddress <= address;
    wait until rising_edge( clock );
    readSubsequenByte( iReading, iData, address moreToRead, nextAddress, oRequestRead, oReadAddress, result ) ;
end ;

procedure readSubsequentByte(
    signal iReading : in std_ulogic;
    signal iData : in NineBitByte;
    address : in ByteAddress;
    moreToRead : in std_ulogic ;
    nextAddress : in ByteAddress;
    signal oReadRequest : out std_ulogic;
    signal oReadAddress : out ByteAddress;
    result : out NineBitByte)
is

    -- Precondition:
    --   oReadRequest = '1' and oAddress = address
    --  was true at the previous clock edge.

    -- Postcondition: rising_edge(clock)
    -- and result = iData
    -- and (iReading = '1' is true and has been true for some
    --     time before this clock edge)
    --     (oReadRequest = moreToRead and oAddress =  nextAddress
    --      is true and was true at the previous clock edge)

    variable readComplete : boolean ;
begin
    loop
        if iReading then
            --Tentatively assume the read is complete
            readComplete := true ;
            --Tentatively request the next byte if one is needed.
            oReadRequest <= moreToRead ;
            oReadAdress <= nextAddress ;
        else
            --Tentatively assume the read is not complete
            readComplete := false ;
            --Tentatively request the same byte.
            oReadRequest <= '1' ;
            oReadAddress <= address ;
        end if
        wait on iReading, clock ;
        exit when rising_edge( clock ) and readComplete and iReading = '1' ;
    end loop ;
    result := iData ;
end ;
</code>```

Now, if the iReading input changes in the middle of a clock cycle, the reading process reacts to that by changing its outputs immediately.

Body:
We're working on testing a circuit that writes to memory, so the test bench needs to read bytes from memory.  However the memory is intended to be read by a Mealy machine. The protocol for the reader is this:

It requests a read by setting oReadRequest high and setting the address bus.

It waits until the next clock period.

If before the end of that next clock period, the request has been acknowledged by iReading being high, then the reader can find the result on the data bus, and has the option of setting oReadRequest to low, or putting a new address on the address bus.

If by the end of that next clock period the request has not been acknowledged, the reader keeps the address the same and oReadRequest high and then it's back to step 2.

This is easy enough to implement in concurrent VHDL with a Mealy machine. But for the test benches I'd like to have a procedure that can read a byte, which means using only sequential statements.

Here is what we have. And it works. (At least it works in pre-synthesis testing.)  But it seems wrong somehow to have a wait based on time.  Our clock period is 10ns.  The 3 ns seems completely arbitrary.

    procedure readByte(
        signal iReading : in std_ulogic;
        signal iData : in NineBitByte;
        address : in ByteAddress;
        signal oReadRequest : out std_ulogic;
        signal oReadAddress : out ByteAddress;
        result : out NineBitByte) is
    begin

        loop
            -- Request a byte.
            oReadAddress <= address;
            oReadRequest <= '1';

            wait until rising_edge( clock );

            -- Wait for a little while
            -- to give the memory arbiter time to react
            -- to the request.
            wait for 3 ns;

            -- Is it acknowledged?
            exit when iReading = '1';
        end loop;

        result := iData;
        -- Tentatively reset the request line.
        -- A subsequent read in this cycle might
        -- overturn this assignment.
        oReadRequest <= '0';
    end procedure;

We are using VHDL-93 in case that makes a difference.

So the specific question is whether there is a way to write the procedure without putting in arbitrary time delays.

The more general question is whether there is a way to write sequential VHDL to emulate a Mealy machine without knowing how fast the other process will react.  With concurrent assignments, an input such as iReading that might change partway trough a clock cycle can be continuously monitored and changes reacted to at any time in the clock cycle. In the code I have above, I picked a specific time in each clock cycle to observe this input.

Body:
[Answering my own question.]

The key idea that I was missing is that it is possible to wait on more than one signal.  A Mealy machine needs to react not only to the clock edge, but also to other signals.  Usually this is handled using concurrency, with different processes waiting on different signals. To handle it without concurrency requires one process to wait on multiple signals.

In the particular example that I had, it gets a bit complicated, especially if I try to encapsulate the behaviour in a procedure. I found I had to write two procedures, one for bytes that are not read immediately after another has been read, and one for bytes that are to be read immediately after another has been read.  The behaviour of the procedures now depends on whether another byte (after the one that the procedure obtains) needs to be read as soon as possible or not, so I had to add two more parameters moreToRead and nextAddress. The key line is wait on iReading, clock in the second procedure.

-- Example usage: To read 3 bytes in a row.
--   readFirstByte( iReading, iData, addr, '1', addr+1,
--                  oReadRequest, oReadAddress, byte0 ) ;
--   readSubsequentByte( iReading, iData, addr+1, '1', addr+2,
--                  oReadRequest, oReadAddress, byte1 ) ;
--   readSubsequentByte( sReading, sData, addr+2, '0', anything,
--                  oReadRequest, oReadAddress, byte2 ) ;
procedure readFirstByte(
    signal iReading : in std_ulogic;
    signal iData : in NineBitByte;
    address : in ByteAddress;
    moreToRead : in std_ulogic ;
    nextAddress : in ByteAddress;
    signal oReadRequest : out std_ulogic;
    signal oReadAddress : out ByteAddress;
    result : out NineBitByte)
is
begin
    -- Request a byte.
    oReadRequest <= '1';
    oReadAddress <= address;
    wait until rising_edge( clock );
    readSubsequenByte( iReading, iData, address moreToRead, nextAddress, oRequestRead, oReadAddress, result ) ;
end ;

procedure readSubsequentByte(
    signal iReading : in std_ulogic;
    signal iData : in NineBitByte;
    address : in ByteAddress;
    moreToRead : in std_ulogic ;
    nextAddress : in ByteAddress;
    signal oReadRequest : out std_ulogic;
    signal oReadAddress : out ByteAddress;
    result : out NineBitByte)
is

    -- Precondition:
    --   oReadRequest = '1' and oAddress = address
    --  was true at the previous clock edge.

    -- Postcondition: rising_edge(clock)
    -- and result = iData
    -- and (iReading = '1' is true and has been true for some
    --     time before this clock edge)
    --     (oReadRequest = moreToRead and oAddress =  nextAddress
    --      is true and was true at the previous clock edge)

    variable readComplete : boolean ;
begin
    loop
        if iReading then
            --Tentatively assume the read is complete
            readComplete := true ;
            --Tentatively request the next byte if one is needed.
            oReadRequest <= moreToRead ;
            oReadAdress <= nextAddress ;
        else
            --Tentatively assume the read is not complete
            readComplete := false ;
            --Tentatively request the same byte.
            oReadRequest <= '1' ;
            oReadAddress <= address ;
        end if
        wait on iReading, clock ;
        exit when rising_edge( clock ) and readComplete and iReading = '1' ;
    end loop ;
    result := iData ;
end ;

Now, if the iReading input changes in the middle of a clock cycle, the reading process reacts to that by changing its outputs immediately.


问:
Inserting strings every so many lines with awk
I am trying to insert command strings and having difficulty with my syntax. I'm trying to get the "mv" every other line, "sleep" every third line and "wait" every 4th line. Here is what I got and been playing with different combinations. Any help would be appreciated.</p>
```<code>awk '{ print; print "mv $NEWEST $RNAME"; }' curl.txt > mv.txt
sleep 2
wait
awk 'NR==3{ print "sleep 2"; }1' mv.txt > sleep.txt
sleep 2
wait
awk 'NR==4{ print "wait"; }1' sleep.txt > wait.txt
</code>```

答:
I don't really understand what you are trying to do, but wouldn't this be enough?

awk '{ printf "%s\n%s\n%s\n%s\n", $0, "mv $NEWEST $RNAME", "sleep 2", "wait" }' curl.txt
```

Body:
I am trying to insert command strings and having difficulty with my syntax. I'm trying to get the "mv" every other line, "sleep" every third line and "wait" every 4th line. Here is what I got and been playing with different combinations. Any help would be appreciated.

awk '{ print; print "mv $NEWEST $RNAME"; }' curl.txt > mv.txt
sleep 2
wait
awk 'NR==3{ print "sleep 2"; }1' mv.txt > sleep.txt
sleep 2
wait
awk 'NR==4{ print "wait"; }1' sleep.txt > wait.txt


问:
How to get rid of double instances of quotations around a string?
I was wondering how you could convert the following list such that the strings contained in the list are properly formatted.

```<code>["'34872'", "'Johnathan'", "'Bonzo'", "'100'"]
</code>```

Ideal output:

```<code>["34872", "Johnathan", "Bonzo", "100"]
</code>```

答:
You can use ast.literal_eval in a list comprehension

```<code>>>> from ast import literal_eval
>>> data = ["'34872'", "'Johnathan'", "'Bonzo'", "'100'"]
>>> [literal_eval(i) for i in data]
['34872', 'Johnathan', 'Bonzo', '100']
</code>```

Otherwise you can use simple string replacement

```<code>>>> [i.replace("'", "") for i in data]
['34872', 'Johnathan', 'Bonzo', '100']
</code>```

Body:
I was wondering how you could convert the following list such that the strings contained in the list are properly formatted.

["'34872'", "'Johnathan'", "'Bonzo'", "'100'"]

Ideal output:

["34872", "Johnathan", "Bonzo", "100"]

Body:
You can use ast.literal_eval in a list comprehension

>>> from ast import literal_eval
>>> data = ["'34872'", "'Johnathan'", "'Bonzo'", "'100'"]
>>> [literal_eval(i) for i in data]
['34872', 'Johnathan', 'Bonzo', '100']

Otherwise you can use simple string replacement

>>> [i.replace("'", "") for i in data]
['34872', 'Johnathan', 'Bonzo', '100']


问:
Does mod_wsgi (daemon) sites hand off content to apache to serve to the client?
I have Django deployed with mod_wsgi in daemon mode for apache2.2. So after Django churns out the content, does it hand off everything to apache from there to have it served in its optimised glory or is Django still somehow taxed in this serving step?</p>

答:
WSGI interface says (http://www.python.org/dev/peps/pep-0333/) that your WSGI application (Django in this case) is called, and must return the content.

Django called your view function.  Your view function returned a rendered template.  Django returned results of rendering the template.  And, on your behalf, it invoked the start_response callable.

Working backwards another step, Apache invoked mod_wsgi.  mod_wsgi (following the WSGI rules) created the environment and handed this to Django, along with astart_response callable that Django can use.

When Django called start_response, mod_wsgi was obligated to collect that response and do something with it.  It hands it to Apache to be fed down to the browser.

Note that Django may be done in a pretty big hurry.  Apache, however, is stuck trickling the initial page down to the browser.  Then, the browser starts asking for .JS libraries, .CSS files, and all those images.  Ideally Apache handles all the rest of these follow-on requests.

You might be asking "does mod_wsgi buffer for me?"  The answer varies with version.  Pre 2.0 mod_wsgi could accumulate a buffer for you.  mod_wsgi 2.0 and up doesn't buffer, it assumes that the application is capable of buffering, or has included middleware for buffering.

http://code.google.com/p/modwsgi/wiki/ChangesInVersion0200

Generally, your Django template is rendered in one buffer and handed to mod_wsgi in one piece, ready for Apache to apply output filters and trickle it down to a browser.

OwnerDisplayName: Glenn

ContentLicense: CC BY-SA 2.5


问:
Use Zapier to Remove Duplicates (Based on single column) from Google Sheet
I need to remove duplicates from a Google Sheet based on a single column.
Within Sheets this functionality exists but I cannot find a way to do this as part of a Zapier automation (zap).</p>

答:
In this case that sounds more like a feature within the App that you are trying to use, within sheets this can be done doing the following:

Highlight the data you'd like to include, and click Data > Data Cleanup > Remove duplicates.

I verified on Zapier and they seem to provide similar actions on this blog.


问:
How do I scan a string for numbers, and convert the numbers to an integer form which I can access?
For instance, if a character array contains "86*20/20/(10)" I wish to be able to keep 86 in an int variable which I can manipulate I do not want to just count the number of numbers, I need the whole number as itself too. Also, is it possible to take the whole array and do "-'0'" to convert the whole thing to a number?</p>
```<code>int is_operand(char item)
{
  if (item != '(' && item != ')' && item != '+' && item != '-' && item != '/' && item != '*' && item != '%')
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

void expressionQ(char *infix, Queue* qPtr)
{
// Write your code here
    // this is used to iterate the list
  int i = 0;
  int j = 0;
  int num;
  char num2;
  char* result;
  printf("This %c\n", infix[0]);
  num = infix[0] - '0';
  printf("testingHERE %d", num);
//   while (infix[i] != '\0')
//   {
//     if (is_operand(infix[i]))
//     {
//       num = infix[i];
//       i++;
//       // while (is_operand(infix[i]))
//       // {
//       //   num2 = infix[i];
//       //   result = malloc(strlen(&num) + strlen(&num2)+1);
//       //   strcpy(result, &num);
//       //   strcat(result, &num2);
//       //   i++;

//       }
//     }
//     i++;
//   }
//   // printf("Tests %c\n", result[0]);
// }
</code>```

答:
Write some functions that accept (or expect) a specific valid input.

```<code>void skip_whitespace( char ** s )
{
  while (**s and isspace( **s )) *s += 1;
}

bool accept_operator( char desired_operator, char ** s )
{
  skip_whitespace( s );
  if (*s == desired_operator)
  {
    *s += 1;
    return true;
  }
  return false;
}

int expect_number( char ** s )
{
  // success only if NON-whitespace was scanned,
  // so let us get rid of any leading whitespace ourselves
  char * first_non_ws = *s;
  skip_whitespace( &first_non_ws );

  // now we can try to extract a number
  int result = strtol( first_non_ws, s, 10 );
  if (first_non_ws == *s)
  {
    fprintf( stderr, "Expected a number at \"%s\"\n", *s );
    halt( 1 );
  }
  return result;
}
</code>```

You can then get information by asking for it:

```<code>char s[1000] = "12 * 3";

char * p = s;
int n1 = expect_number( &p );  // extracts '12'
if (accept_operator( '*', &p )) ... // successfully extracts '*'
</code>```

Your next problem will be properly handling the operators. You should google around “recursive descent parser”. Here is a freebie for add/subtract:

```<code>int term( char ** s )
{
  int lhs = factor( s );
  while (true)
  {
    if      (accept_operator( '+', s )) lhs += factor( s );
    else if (accept_operator( '-', s )) lhs -= factor( s );
    else break;
  }
  return lhs;
}
</code>```

Unless you are doing something with lower operator precedence than addition, that should be the first thing your expression() function calls.

```<code>int expression( char ** s )
{
  return term( s );
}
</code>```

And the last thing should be parentheses, which should either:

accept an open parenthesis, call expression(), and accept a close parenthesis, or

expect a number

Now you can parse stuff in your code easily enough:

```<code>char s[1000] = "86*20/20/(10)";
char * p = s;
int result = expression( &p );

// if it matters, check to make sure there isn’t any other input left unread
skip_whitespace( &p );
if (*p)
{
  fprintf( stderr, "Expression not properly terminated!\n" );
  halt( 1 );
}
</code>```

Recursive Descent isn’t the only way to do this stuff, but it is the most direct.

The other good way to handle infix expressions is using Shunting Yard. That, however, requires a bit more setup and post-processing.

You must first properly tokenize things into an array/list/whatever

Tokenization is identifying and storing objects

You must pre-verify that the infix expression is properly-formed

Because SY is terrible at validation

You must afterwards compute the result!

SY is an infix→postfix (RPN) converter. It doesn’t actually process the RPN expression.

Both RD and SY are very, very easy, but I suspect you are just trying to get through a simple homework assignment, and RD is really just the easier path for you, methinks.

Body:
For instance, if a character array contains "86*20/20/(10)" I wish to be able to keep 86 in an int variable which I can manipulate I do not want to just count the number of numbers, I need the whole number as itself too. Also, is it possible to take the whole array and do "-'0'" to convert the whole thing to a number?

int is_operand(char item)
{
  if (item != '(' && item != ')' && item != '+' && item != '-' && item != '/' && item != '*' && item != '%')
  {
    return 1;
  }
  else
  {
    return 0;
  }
}

void expressionQ(char *infix, Queue* qPtr)
{
// Write your code here
    // this is used to iterate the list
  int i = 0;
  int j = 0;
  int num;
  char num2;
  char* result;
  printf("This %c\n", infix[0]);
  num = infix[0] - '0';
  printf("testingHERE %d", num);
//   while (infix[i] != '\0')
//   {
//     if (is_operand(infix[i]))
//     {
//       num = infix[i];
//       i++;
//       // while (is_operand(infix[i]))
//       // {
//       //   num2 = infix[i];
//       //   result = malloc(strlen(&num) + strlen(&num2)+1);
//       //   strcpy(result, &num);
//       //   strcat(result, &num2);
//       //   i++;

//       }
//     }
//     i++;
//   }
//   // printf("Tests %c\n", result[0]);
// }

Body:
Write some functions that accept (or expect) a specific valid input.

void skip_whitespace( char ** s )
{
  while (**s and isspace( **s )) *s += 1;
}

bool accept_operator( char desired_operator, char ** s )
{
  skip_whitespace( s );
  if (*s == desired_operator)
  {
    *s += 1;
    return true;
  }
  return false;
}

int expect_number( char ** s )
{
  // success only if NON-whitespace was scanned,
  // so let us get rid of any leading whitespace ourselves
  char * first_non_ws = *s;
  skip_whitespace( &first_non_ws );

  // now we can try to extract a number
  int result = strtol( first_non_ws, s, 10 );
  if (first_non_ws == *s)
  {
    fprintf( stderr, "Expected a number at \"%s\"\n", *s );
    halt( 1 );
  }
  return result;
}

You can then get information by asking for it:

char s[1000] = "12 * 3";

char * p = s;
int n1 = expect_number( &p );  // extracts '12'
if (accept_operator( '*', &p )) ... // successfully extracts '*'

Your next problem will be properly handling the operators. You should google around “recursive descent parser”. Here is a freebie for add/subtract:

int term( char ** s )
{
  int lhs = factor( s );
  while (true)
  {
    if      (accept_operator( '+', s )) lhs += factor( s );
    else if (accept_operator( '-', s )) lhs -= factor( s );
    else break;
  }
  return lhs;
}

Unless you are doing something with lower operator precedence than addition, that should be the first thing your expression() function calls.

int expression( char ** s )
{
  return term( s );
}

And the last thing should be parentheses, which should either:

accept an open parenthesis, call expression(), and accept a close parenthesis, or

expect a number

Now you can parse stuff in your code easily enough:

char s[1000] = "86*20/20/(10)";
char * p = s;
int result = expression( &p );

// if it matters, check to make sure there isn’t any other input left unread
skip_whitespace( &p );
if (*p)
{
  fprintf( stderr, "Expression not properly terminated!\n" );
  halt( 1 );
}

Recursive Descent isn’t the only way to do this stuff, but it is the most direct.

The other good way to handle infix expressions is using Shunting Yard. That, however, requires a bit more setup and post-processing.

You must first properly tokenize things into an array/list/whatever

Tokenization is identifying and storing objects

You must pre-verify that the infix expression is properly-formed

Because SY is terrible at validation

You must afterwards compute the result!

SY is an infix→postfix (RPN) converter. It doesn’t actually process the RPN expression.

Both RD and SY are very, very easy, but I suspect you are just trying to get through a simple homework assignment, and RD is really just the easier path for you, methinks.


问:
Simple operation to waste time?
I'm looking for a simple operation / routine which can "waste" time if repeated continuously.

I'm researching how gprof profiles applications, so this "time waster" needs to waste time in the user space and should not require external libraries. IE, calling sleep(20) will "waste" 20 seconds of time, but gprof will not record this time because it occurred within another library.

Any recommendations for simple tasks which can be repeated to waste time?

答:
The simplest way to "waste" time without yielding CPU is a tight loop.

If you don't need to restrict the duration of your waste (say, you control it by simply terminating the process when done), then go C style*:

```<code>for (;;) {}
</code>```

(Be aware, though, that the standard allows the implementation to assume that programs will eventually terminate, so technically speaking this loop — at least in C++0x — has Undefined Behaviour and could be optimised out!**

Otherwise, you could time it manually:

```<code>time_t s = time(0);
while (time(0) - s < 20) {}
</code>```

Or, instead of repeatedly issuing the time syscall (which will lead to some time spent in the kernel), if on a GNU-compatible system you could make use of signal.h "alarms" to end the loop:

```<code>alarm(20);
while (true) {}
</code>```

There's even a very similar example on the documentation page for "Handler Returns".

(Of course, these approaches will all send you to 100% CPU for the intervening time and make fluffy unicorns fall out of your ears.)

* {} rather than trailing ; used deliberately, for clarity. Ultimately, there's no excuse for writing a semicolon in a context like this; it's a terrible habit to get into, and becomes a maintenance pitfall when you use it in "real" code.

** See [n3290: 1.10/2] and [n3290: 1.10/24].

Title: Simple operation to waste time?

Body:
The simplest way to "waste" time without yielding CPU is a tight loop.

If you don't need to restrict the duration of your waste (say, you control it by simply terminating the process when done), then go C style*:

for (;;) {}

(Be aware, though, that the standard allows the implementation to assume that programs will eventually terminate, so technically speaking this loop — at least in C++0x — has Undefined Behaviour and could be optimised out!**

Otherwise, you could time it manually:

time_t s = time(0);
while (time(0) - s < 20) {}

Or, instead of repeatedly issuing the time syscall (which will lead to some time spent in the kernel), if on a GNU-compatible system you could make use of signal.h "alarms" to end the loop:

alarm(20);
while (true) {}

There's even a very similar example on the documentation page for "Handler Returns".

(Of course, these approaches will all send you to 100% CPU for the intervening time and make fluffy unicorns fall out of your ears.)

* {} rather than trailing ; used deliberately, for clarity. Ultimately, there's no excuse for writing a semicolon in a context like this; it's a terrible habit to get into, and becomes a maintenance pitfall when you use it in "real" code.

** See [n3290: 1.10/2] and [n3290: 1.10/24].


问:
Groupby A column and bring up the A value, only if the B values differ from the other ones, including nulls
I have this example, dataset:

```<code> A   B
11   A
11   V
11   C
12   A
12   A
12   A
12   A
13   A
13   A
13   B
13   B
14   C
14   C
14
14
</code>```

And I want it to return, the grouped A values, that has different values on the B column. So in this example, the expected output is:

```<code>[11, 13,14]
</code>```

I made an attempt at formulating the code, and I succeeded but it is terrible and  unoptimized. And I was looking for alternatives so I could iterate faster through my much bigger dataset. Would appreciate some help.

Here is my code:

```<code>user_mult_camps = []

for i in  df['A'].unique():
    filt = (df['A'] == i)
    df2 = df.loc[filt]
    x=df2['B'].unique()
    if len(x) > 1:
        user_mult_camps.append(i)
        print(i)
</code>```

答:
You could groupby "A" and use nunique to count the number of unique "B"s per "A". Then evaluate if it's greater than 1 to filter the "A"s that have more than one corresponding "B":

```<code>msk = df.groupby('A')['B'].nunique()>1
out = msk.index[msk].tolist()
</code>```

Output:

```<code>[11]
</code>```

If you want to count NaN as well, then set dropna parameter in nunique to False:

```<code>df2['B'] = df2['B'].fillna(value=np.nan)
msk = df2.groupby('A')['B'].nunique(dropna=False)>1
</code>```

Then the output:

```<code>[11, 13, 14]
</code>```

Body:
I have this example, dataset:

 A   B
11   A
11   V
11   C
12   A
12   A
12   A
12   A
13   A
13   A
13   B
13   B
14   C
14   C
14
14

And I want it to return, the grouped A values, that has different values on the B column. So in this example, the expected output is:

[11, 13,14]

I made an attempt at formulating the code, and I succeeded but it is terrible and  unoptimized. And I was looking for alternatives so I could iterate faster through my much bigger dataset. Would appreciate some help.

Here is my code:

user_mult_camps = []

for i in  df['A'].unique():
    filt = (df['A'] == i)
    df2 = df.loc[filt]
    x=df2['B'].unique()
    if len(x) > 1:
        user_mult_camps.append(i)
        print(i)

Body:
You could groupby "A" and use nunique to count the number of unique "B"s per "A". Then evaluate if it's greater than 1 to filter the "A"s that have more than one corresponding "B":

msk = df.groupby('A')['B'].nunique()>1
out = msk.index[msk].tolist()

Output:

[11]

If you want to count NaN as well, then set dropna parameter in nunique to False:

df2['B'] = df2['B'].fillna(value=np.nan)
msk = df2.groupby('A')['B'].nunique(dropna=False)>1

Then the output:

[11, 13, 14]


问:
How do I add ~/bin to my path?
I've been having trouble modifying my path to add Sublime Text 2. I've added a ~/bin directory and run this command:

```<code>ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" ~/bin/subl
</code>```

The subl link appears in ~/bin. But I need to add the ~/bin directory to my path. I'm fairly new at this, and I don't know where my path is. I've looked around, and found that the likely files are either .profile, .bash_profile or .bashrc

I don't have a .bash_profile. To .profile and .bashrc I added

```<code>PATH=$PATH:~/bin/subl
export PATH
</code>```

Is that the right thing to add? And if so, where should I add it?

When I echo $PATH, I get:

```<code>/Users/<username>/.rvm/gems/ruby-1.9.3-p194@rails3tutorial2ndEd/bin:/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/<username>/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/<username>/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
</code>```

When I type subl, I get:

```<code>-bash: subl: command not found
</code>```

Thanks!

p.s. I had previously installed Macports, which modified my .profile file. Not sure if this has anything to do with it - I now don't know what the default .profile looks like.

答:
On MacOS 11, this command worked for me to establish a symlink for Sublime Merge. The main difference seems to be calling ln with the -sv instead of -s:

```<code>ln -sv "/Applications/Sublime Merge.app/Contents/SharedSupport/bin/smerge" /usr/local/bin/smerge
</code>```

Title: How do I add ~/bin to my path?

Body:
I've been having trouble modifying my path to add Sublime Text 2. I've added a ~/bin directory and run this command:

ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" ~/bin/subl

The subl link appears in ~/bin. But I need to add the ~/bin directory to my path. I'm fairly new at this, and I don't know where my path is. I've looked around, and found that the likely files are either .profile, .bash_profile or .bashrc

I don't have a .bash_profile. To .profile and .bashrc I added

PATH=$PATH:~/bin/subl
export PATH

Is that the right thing to add? And if so, where should I add it?

When I echo $PATH, I get:

/Users/<username>/.rvm/gems/ruby-1.9.3-p194@rails3tutorial2ndEd/bin:/Users/<username>/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/<username>/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/<username>/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

When I type subl, I get:

-bash: subl: command not found

Thanks!

p.s. I had previously installed Macports, which modified my .profile file. Not sure if this has anything to do with it - I now don't know what the default .profile looks like.

Body:
On MacOS 11, this command worked for me to establish a symlink for Sublime Merge. The main difference seems to be calling ln with the -sv instead of -s:

ln -sv "/Applications/Sublime Merge.app/Contents/SharedSupport/bin/smerge" /usr/local/bin/smerge