问:
JS Onclick function is not working properly
Html:

```<code><div class="prog shrink" id="prog">
  <div class="div1">
    <img src="svg/close.svg" class="collapse" id="collapse">
    <div class="progNum" style="--i: 'Program 1'">
      <div>
        <h1>1</h1>
      </div>
    </div>
  </div>
  <div class="div2">
    <h1>Program 01:</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu ipsum in elit congue blandit. Nullam vitae lobortis lorem, sagittis convallis felis. Praesent tincidunt tristique. Nullam vitae lobortis lorem, sagittis convallis felis. </p>
    <div class="btns"> <button class="btn btn1 showDiv3"> <img src="svg/dash.svg"> </button> <button class="btn btn2"> <span>Source code</span> <img src="svg/arrow.svg"> </button>
    </div>
  </div>
  <div class="div3">
    <div class="h-div3">
      <h1>C++</h1>
      <img src="svg/close.svg" class="div3-close">
    </div>
    <div class="d-link-div3"> <span>Download</span> <a href="">Turbo C++ Code</a> <a href="">Dev C++ Code</a>
    </div>
    <div class="c-link-div3"> <span>Compiler</span> <a href="">Compile</a>
    </div>
    <div class="view-div3"> <span>View Code</span> <a href="">View Code</a>
    </div>
  </div>
</div>
</code>```

When a user click on div.prog shrink the class name changes to div.prog expand

I want to add the class shrink and remove the class expand when a user click on img.collapse#collapse

I tried:

```<code>var closeBtn = document.getElementById('collapse');
var prog = document.getElementById('prog');
closeBtn.onclick = function(){
   console.log('close button clicked..');
   prog.classList.remove('expand');
   prog.classList.add('shrink');
}
</code>```

The output statement is displaying on the console but the div is not returning to its initial state.

Full code :

var progElements = document.getElementsByClassName('prog');
var closeBtn = document.getElementById('collapse');
for (let i = 0; i < progElements.length; i++) {
  progElements[i].onclick = function() {
    this.classList.add('expand');
    this.classList.remove('shrink');
    for (let j = 0; j < progElements.length; j++) {
      if (i !== j) {
        if (!progElements[j].classList.contains('shrink')) {
          progElements[j].classList.add('shrink');
          progElements[j].classList.remove('expand');
        }
      }
    }
  }
}

var showDiv3 = document.getElementsByClassName('showDiv3');
var div3 = document.getElementsByClassName('div3');
var div3Close = document.getElementsByClassName('div3-close');

for (let i = 0; i < div3.length; i++) {
  showDiv3[i].onclick = function() {
    div3[i].style.display = 'block';
    div3[i].style.zIndex = '100';
  }
  div3Close[i].onclick = function() {
    div3[i].style.display = 'none';
  }
}

var closeBtn = document.getElementById('collapse');
var prog = document.getElementById('prog');
closeBtn.onclick = function() {
  console.log('close button clicked..');
  prog.classList.remove('expand');
  prog.classList.add('shrink');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&family=Roboto+Condensed:wght@300;400;700&family=Source+Sans+Pro:wght@300;400;600;700;900&display=swap");
* {
  outline: 0px solid #0f0;
  font-family: "Poppins", sans-serif;
  user-select: none;
}

.container {
  position: relative;
  transform: translateX(60px);
  width: calc(100vw - 60px);
  height: 100vh;
  overflow: scroll;
  background: #152644;
}

.container .title {
  text-align: center;
  width: 100%;
  height: 66px;
  background: #11101d;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container .title h1 {
  color: #fff;
  font-size: 35px;
  font-weight: 700;
  font-family: "Poppins", sans-serif;
  background: var(--rainbow);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.container .content {
  position: relative;
  height: calc(100% - 66px);
  width: 100%;
  overflow: scroll;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: flex-start;
}

.home-content {
  border: 0px solid #fff;
}

.home-content h1 {
  color: #fff;
  border: 0px solid #aaa;
}

.home-content .hc-links {
  border: 0px solid #f0f;
}

.home-content .hc-links div {
  border: 0px solid #0ff;
}

.home-content .hc-links div h1 {
  border: 0px solid #faa;
}

.home-content .hc-links div a {
  border: 0px solid #ff0;
}

.home-content .fback {
  border: 0;
}

.content::-webkit-scrollbar {
  display: none;
}

.content .prog.shrink {
  margin: 16px;
  width: 125px;
  height: 125px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 -5px 5px rgba(250, 250, 255, 0.05), inset 0 -5px 5px rgba(250, 250, 255, 0.05), 0 5px 5px rgba(0, 0, 0, 0.3), inset 0 5px 5px rgba(0, 0, 0, 0.3);
}

.content .prog.expand {
  position: relative;
  margin: 20px auto;
  width: 75%;
  background-color: #007bff;
  border-radius: 20px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 20;
  box-shadow: 0 -5px 10px rgba(0, 0, 0, 0.3), 0 5px 10px rgba(0, 0, 0, 0.3);
}

.prog.shrink .div1 {
  height: 125px;
  width: 125px;
  background: #11101d;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.expand .div1 {
  height: 200px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.shrink .div1 .collapse {
  display: none;
}

.prog.expand .div1 .collapse {
  border: 1px solid #00f;
  position: absolute;
  top: 10px;
  left: 10px;
  height: 40px;
  filter: invert(1);
  background: #778;
  border-radius: 5px;
}

.prog.shrink .div1 .progNum {
  padding: 7px;
  position: relative;
  height: 75px;
  width: 75px;
  background: rgba(250, 250, 255, 0.45);
  border-radius: 50%;
  transform: translateY(-15px);
}

.prog.shrink .div1 .progNum::after {
  content: var(--i);
  position: absolute;
  bottom: -28px;
  left: 50%;
  transform: translateX(-50%);
  color: #0088ff;
  font-size: 15px;
  font-weight: 500;
  font-family: "Poppins", sans-serif;
  opacity: 0.8;
}

.prog.expand .div1 .progNum {
  background: #0088ff;
  height: 125px;
  width: 125px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px;
  box-shadow: 0 0 20px rgba(0, 0, 255, 0.2);
}

.prog.shrink .div1 .progNum>div {
  background: #11101d;
  height: 100%;
  width: 100%;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.expand .div1 .progNum>div {
  background: #def;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.shrink .div1 .progNum>div>h1 {
  font-size: 2.5em;
  color: #0088ff;
  font-weight: bold;
  opacity: 0.8;
}

.prog.expand .div1 .progNum>div>h1 {
  font-size: 52px;
}

.prog.shrink div2 {
  display: none;
}

.prog.expand .div2 {
  padding: 20px;
  width: calc(100% - 250px);
}

.prog.expand .div2 h1 {
  color: #fff;
  font-size: 30px;
  font-family: "Poppins", sans-serif;
}

.prog.expand .div2 p {
  color: rgba(255, 255, 255, 0.8);
  height: 100px;
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 17px;
}

.prog.expand .div2 .btns {
  width: 100%;
  display: flex;
}

.prog.expand .div2 .btns .btn {
  padding: 10px 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #0bc42a;
  border: none;
  border-radius: 5px;
  color: #fff;
}

.prog.expand .div2 .btns .btn1 {
  padding: 10px;
}

.prog.expand .div2 .btns .btn2 {
  margin-left: 20px;
}

.prog.expand .div2 .btns .btn2 span {
  font-size: 20px;
}

.prog.expand .div2 .btns .btn img {
  filter: invert(1);
}

.prog.expand .div3 {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 10px;
  background: #11101d;
}

.prog.expand .div3 .h-div3 {
  margin-left: -10px;
  margin-top: -10px;
  width: calc(100% + 20px);
  min-height: 50px;
  background: #007bff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
}

.prog.expand .div3 .h-div3 h1 {
  font-size: 30px;
  color: #fff;
}

.prog.expand .div3 .h-div3 img {
  filter: invert(1);
  height: 30px;
}

.prog.expand .div3 .d-link-div3 {
  margin-top: 20px;
  position: relative;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: row;
  padding: 15px 0;
}

.prog.expand .div3 .d-link-div3 span {
  background: #11101d;
  padding: 0 5px;
  position: absolute;
  top: -11px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 15px;
  color: rgba(250, 250, 255, 0.3);
}

.prog.expand .div3 .d-link-div3 a {
  margin: 5px 5px;
  padding: 8px;
  width: 100%;
  background: #007bff;
  color: #fff;
  font-size: 16px;
  text-decoration: none;
  border-radius: 4px;
  text-align: center;
  font-family: "Poppins", sans-serif;
  font-weight: 500;
}

.prog.expand .div3 .c-link-div3 {
  position: relative;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  margin-top: 0px;
  min-height: 50px;
}

.prog.expand .div3 .c-link-div3 span {
  background: #11101d;
  padding: 0 5px;
  position: absolute;
  top: -11px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 15px;
  color: rgba(250, 250, 255, 0.3);
}

.prog.expand .div3 .c-link-div3 a {
  display: block;
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 8px;
  width: 100%;
  background: #007bff;
  color: #fff;
  font-size: 16px;
  text-decoration: none;
  border-radius: 4px;
  text-align: center;
  letter-spacing: 1px;
  font-family: "Poppins", sans-serif;
  font-weight: 500;
}

.prog.expand .div3 .view-div3 {
  position: relative;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  margin-top: 0px;
  min-height: 50px;
}

.prog.expand .div3 .view-div3 span {
  background: #11101d;
  padding: 0 5px;
  position: absolute;
  top: -11px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 15px;
  color: rgba(250, 250, 255, 0.3);
}

.prog.expand .div3 .view-div3 a {
  display: block;
  margin-top: 20px;
  margin-bottom: 10px;
  padding: 8px;
  width: 100%;
  background: #007bff;
  color: #fff;
  font-size: 16px;
  text-decoration: none;
  border-radius: 4px;
  text-align: center;
  letter-spacing: 1px;
  font-family: "Poppins", sans-serif;
  font-weight: 500;
}

@media screen and (max-width: 700px) {
  .home-content {
    position: absolute;
    top: 45%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 10px 22px;
    min-width: 270px;
    min-height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    background: #11101d;
    border-radius: 8px;
    box-shadow: 0 -5px 5px rgba(250, 250, 255, 0.05), inset 0 -5px 5px rgba(250, 250, 255, 0.05), 0 5px 5px rgba(0, 0, 0, 0.3), inset 0 5px 5px rgba(0, 0, 0, 0.3);
  }
  .home-content h1 {
    margin-top: 15px;
    font-size: 32px;
    font-family: "Poppins", sans-serif;
  }
  .home-content .hc-links {
    position: relative;
    margin-top: 10px;
    margin-bottom: 25px;
    width: 100%;
    border-radius: 8px;
  }
  .home-content .hc-links div {
    padding: 12px;
    margin-top: 15px;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(20px);
    border-radius: 10px;
  }
  .home-content .hc-links div:nth-child(2) {
    margin-bottom: 10px;
  }
  .home-content .hc-links div h1 {
    font-size: 25px;
    color: #def;
    margin-bottom: 5px;
  }
  .home-content .hc-links div a {
    white-space: nowrap;
    text-decoration: none;
    color: #fff;
    background: #007bff;
    font-size: 16px;
    padding: 8px;
    text-align: center;
    border-radius: 5px;
  }
  .container .content {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: row;
  }
  .content .prog.shrink {
    margin: 6px;
    margin-bottom: 12px;
  }
  .content .prog.expand {
    position: relative;
    top: 0;
    left: 0;
    transform: translate(0, 0);
    width: 250px;
    min-height: 370px;
    border-radius: 10px;
    overflow: hidden;
    margin: 10px;
    background: #11101d;
    flex-direction: column;
  }
  .prog.expand .div1 {
    position: relative;
    top: 0px;
    width: 100%;
    height: 100px;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    background: #007bff;
  }
  .prog.expand .div1 .collapse {
    height: 32px;
    filter: invert(0);
    opacity: 1;
    position: absolute;
    right: 10px;
  }
  .prog.expand .div1 .progNum {
    position: absolute;
    bottom: -37px;
    left: 15px;
    background: #11101d;
    height: 75px;
    width: 75px;
    padding: 7px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .prog.expand .div1 .progNum>div {
    background: #eee;
    border-radius: 50%;
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .prog.expand .div1 .progNum>div>h1 {
    font-size: 2.5em;
    color: #000;
    opacity: 0.6;
  }
  .prog.expand .div2 {
    padding: 8px 16px;
    display: block;
    position: relative;
    left: 0;
    top: 0;
    min-height: 270px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: #fff;
  }
  .prog.expand .div2 h1 {
    transform: translateY(-10px);
    align-self: flex-end;
    margin-right: 0px;
    font-size: 24px;
    font-weight: 700;
    color: #fff;
    font-family: "Roboto Condensed", sans-serif;
    text-transform: uppercase;
  }
  .prog.expand .div2 p {
    transform: translateY(-10px);
    margin-top: 10px;
    margin-bottom: 0px;
    font-size: 16.5px;
    color: rgba(250, 250, 255, 0.8);
    height: 160px;
    overflow-y: scroll;
    font-family: "Source Sans Pro", sans-serif;
    word-break: break-all;
  }
  .prog.expand .div2 .btns {
    display: flex;
    justify-content: flex-start;
  }
  .prog.expand .div2 .btns .btn {
    border: none;
    border-radius: 4px;
  }
  .prog.expand .div2 .btns .btn1 {
    padding: 4px 5px;
  }
  .prog.expand .div2 .btns .btn1 img {
    height: 28px;
  }
  .prog.expand .div2 .btns .btn2 {
    margin-left: 10px;
    padding: 5px 10px;
  }
  .prog.expand .div2 .btns .btn2 span {
    font-size: 20px;
    margin-right: 10px;
    color: #fff;
    font-family: "Source Sans Pro", sans-serif;
    font-weight: 500;
  }
  .prog.expand .div2 .btns .btn2 img {
    height: 25px;
  }
  .prog.expand .div3 .d-link-div3 {
    flex-direction: column;
    align-items: center;
  }
  .prog.expand .div3 .d-link-div3 a {
    margin: 7px 0;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>C++ programs</title>
  <link rel="stylesheet" href="css/sideBar.css">
  <link rel="stylesheet" href="css/main.css">

C++programs

                         11th class

                      11th class

                         12th class

                      12th class

                         Others

                      Others

                         Feedback

                      Feedback

                         More

                      More

                         FAQ

                      FAQ

                         Darkmode

C++ programs

1

Program 01:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu ipsum in elit congue blandit. Nullam vitae lobortis lorem, sagittis convallis felis. Praesent tincidunt tristique. Nullam vitae lobortis lorem, sagittis convallis felis.

              <button class="btn btn1 showDiv3">

                                </button>
              <button class="btn btn2">
                                   Source code

                                </button>

C++

              Download
              Turbo C++ Code
              Dev C++ Code

              Compiler
              Compile

              View Code
              View Code

2

Program 02:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu ipsum in elit congue blandit. Nullam vitae lobortis lorem, sagittis convallis felis. Praesent tincidunt tristique. Nullam vitae lobortis lorem, sagittis convallis felis.

              <button class="btn btn1">

                     </button>
              <button class="btn btn2">
                        Source code

                     </button>

```

I want to close the div by changing its class from prog expand to  prog shrink

Can anyone tell how can I achieve that ...

Full project :  link

答:
First you need to have a unique id for example id="prog-one" id="prog-two".

Secondly you need to set the data-target attribute so you can target specific div to toggle(add/remove) classes like this.

Finally you have to get all the collapse image and add the event listener.

var closeBtns = document.querySelectorAll('.collapse');
    closeBtns.forEach(closeBtn => {
      closeBtn.addEventListener('click', function({target}) {
        const targetId = target.getAttribute('data-target');
        const targetDOM = document.getElementById(targetId);
      console.log('close button clicked..');
      targetDOM.classList.remove('expand');
      targetDOM.classList.add('shrink');
    })
    })```
</div>
</div>
</p>
<p>Here is the code pen link. LINK ONE LINKTWO</p>
<p>[UPDATED]</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>var progElements = document.getElementsByClassName("prog");
var closeBtn = document.getElementById("collapse");
for (let i = 0; i < progElements.length; i++) {
  progElements[i].onclick = function ({ target }) {
    if (target.getAttribute("class") === "collapse") return;
    this.classList.add("expand");
    this.classList.remove("shrink");
    console.log("running");
    for (let j = 0; j < progElements.length; j++) {
      if (i !== j) {
        if (!progElements[j].classList.contains("shrink")) {
          progElements[j].classList.add("shrink");
          progElements[j].classList.remove("expand");
        }
      }
    }
  };
}

var showDiv3 = document.getElementsByClassName("showDiv3");
var div3 = document.getElementsByClassName("div3");
var div3Close = document.getElementsByClassName("div3-close");

for (let i = 0; i < div3.length; i++) {
  showDiv3[i].onclick = function () {
    div3[i].style.display = "block";
    div3[i].style.zIndex = "100";
  };
  div3Close[i].onclick = function () {
    div3[i].style.display = "none";
  };
}

var closeBtns = document.querySelectorAll(".collapse");
closeBtns.forEach((closeBtn) => {
  closeBtn.addEventListener("click", function ({ target }) {
    const targetId = target.getAttribute("data-target");
    const targetDOM = document.getElementById(targetId);
    console.log("close button clicked..");
    targetDOM.className = "prog shrink";
  });
});</code>```

Body:
Html:

1

Program 01:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu ipsum in elit congue blandit. Nullam vitae lobortis lorem, sagittis convallis felis. Praesent tincidunt tristique. Nullam vitae lobortis lorem, sagittis convallis felis.

 <button class="btn btn1 showDiv3">  </button> <button class="btn btn2"> Source code  </button>

C++

 Download Turbo C++ Code Dev C++ Code

 Compiler Compile

 View Code View Code

When a user click on div.prog shrink the class name changes to div.prog expand

I want to add the class shrink and remove the class expand when a user click on img.collapse#collapse

I tried:

var closeBtn = document.getElementById('collapse');
var prog = document.getElementById('prog');
closeBtn.onclick = function(){
   console.log('close button clicked..');
   prog.classList.remove('expand');
   prog.classList.add('shrink');
}

The output statement is displaying on the console but the div is not returning to its initial state.

Full code :

var progElements = document.getElementsByClassName('prog');
var closeBtn = document.getElementById('collapse');
for (let i = 0; i < progElements.length; i++) {
  progElements[i].onclick = function() {
    this.classList.add('expand');
    this.classList.remove('shrink');
    for (let j = 0; j < progElements.length; j++) {
      if (i !== j) {
        if (!progElements[j].classList.contains('shrink')) {
          progElements[j].classList.add('shrink');
          progElements[j].classList.remove('expand');
        }
      }
    }
  }
}

var showDiv3 = document.getElementsByClassName('showDiv3');
var div3 = document.getElementsByClassName('div3');
var div3Close = document.getElementsByClassName('div3-close');

for (let i = 0; i < div3.length; i++) {
  showDiv3[i].onclick = function() {
    div3[i].style.display = 'block';
    div3[i].style.zIndex = '100';
  }
  div3Close[i].onclick = function() {
    div3[i].style.display = 'none';
  }
}

var closeBtn = document.getElementById('collapse');
var prog = document.getElementById('prog');
closeBtn.onclick = function() {
  console.log('close button clicked..');
  prog.classList.remove('expand');
  prog.classList.add('shrink');
}

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&family=Roboto+Condensed:wght@300;400;700&family=Source+Sans+Pro:wght@300;400;600;700;900&display=swap");
* {
  outline: 0px solid #0f0;
  font-family: "Poppins", sans-serif;
  user-select: none;
}

.container {
  position: relative;
  transform: translateX(60px);
  width: calc(100vw - 60px);
  height: 100vh;
  overflow: scroll;
  background: #152644;
}

.container .title {
  text-align: center;
  width: 100%;
  height: 66px;
  background: #11101d;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container .title h1 {
  color: #fff;
  font-size: 35px;
  font-weight: 700;
  font-family: "Poppins", sans-serif;
  background: var(--rainbow);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.container .content {
  position: relative;
  height: calc(100% - 66px);
  width: 100%;
  overflow: scroll;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  align-content: flex-start;
}

.home-content {
  border: 0px solid #fff;
}

.home-content h1 {
  color: #fff;
  border: 0px solid #aaa;
}

.home-content .hc-links {
  border: 0px solid #f0f;
}

.home-content .hc-links div {
  border: 0px solid #0ff;
}

.home-content .hc-links div h1 {
  border: 0px solid #faa;
}

.home-content .hc-links div a {
  border: 0px solid #ff0;
}

.home-content .fback {
  border: 0;
}

.content::-webkit-scrollbar {
  display: none;
}

.content .prog.shrink {
  margin: 16px;
  width: 125px;
  height: 125px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 -5px 5px rgba(250, 250, 255, 0.05), inset 0 -5px 5px rgba(250, 250, 255, 0.05), 0 5px 5px rgba(0, 0, 0, 0.3), inset 0 5px 5px rgba(0, 0, 0, 0.3);
}

.content .prog.expand {
  position: relative;
  margin: 20px auto;
  width: 75%;
  background-color: #007bff;
  border-radius: 20px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 20;
  box-shadow: 0 -5px 10px rgba(0, 0, 0, 0.3), 0 5px 10px rgba(0, 0, 0, 0.3);
}

.prog.shrink .div1 {
  height: 125px;
  width: 125px;
  background: #11101d;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.expand .div1 {
  height: 200px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.shrink .div1 .collapse {
  display: none;
}

.prog.expand .div1 .collapse {
  border: 1px solid #00f;
  position: absolute;
  top: 10px;
  left: 10px;
  height: 40px;
  filter: invert(1);
  background: #778;
  border-radius: 5px;
}

.prog.shrink .div1 .progNum {
  padding: 7px;
  position: relative;
  height: 75px;
  width: 75px;
  background: rgba(250, 250, 255, 0.45);
  border-radius: 50%;
  transform: translateY(-15px);
}

.prog.shrink .div1 .progNum::after {
  content: var(--i);
  position: absolute;
  bottom: -28px;
  left: 50%;
  transform: translateX(-50%);
  color: #0088ff;
  font-size: 15px;
  font-weight: 500;
  font-family: "Poppins", sans-serif;
  opacity: 0.8;
}

.prog.expand .div1 .progNum {
  background: #0088ff;
  height: 125px;
  width: 125px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px;
  box-shadow: 0 0 20px rgba(0, 0, 255, 0.2);
}

.prog.shrink .div1 .progNum>div {
  background: #11101d;
  height: 100%;
  width: 100%;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.expand .div1 .progNum>div {
  background: #def;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.prog.shrink .div1 .progNum>div>h1 {
  font-size: 2.5em;
  color: #0088ff;
  font-weight: bold;
  opacity: 0.8;
}

.prog.expand .div1 .progNum>div>h1 {
  font-size: 52px;
}

.prog.shrink div2 {
  display: none;
}

.prog.expand .div2 {
  padding: 20px;
  width: calc(100% - 250px);
}

.prog.expand .div2 h1 {
  color: #fff;
  font-size: 30px;
  font-family: "Poppins", sans-serif;
}

.prog.expand .div2 p {
  color: rgba(255, 255, 255, 0.8);
  height: 100px;
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 17px;
}

.prog.expand .div2 .btns {
  width: 100%;
  display: flex;
}

.prog.expand .div2 .btns .btn {
  padding: 10px 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #0bc42a;
  border: none;
  border-radius: 5px;
  color: #fff;
}

.prog.expand .div2 .btns .btn1 {
  padding: 10px;
}

.prog.expand .div2 .btns .btn2 {
  margin-left: 20px;
}

.prog.expand .div2 .btns .btn2 span {
  font-size: 20px;
}

.prog.expand .div2 .btns .btn img {
  filter: invert(1);
}

.prog.expand .div3 {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 10px;
  background: #11101d;
}

.prog.expand .div3 .h-div3 {
  margin-left: -10px;
  margin-top: -10px;
  width: calc(100% + 20px);
  min-height: 50px;
  background: #007bff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
}

.prog.expand .div3 .h-div3 h1 {
  font-size: 30px;
  color: #fff;
}

.prog.expand .div3 .h-div3 img {
  filter: invert(1);
  height: 30px;
}

.prog.expand .div3 .d-link-div3 {
  margin-top: 20px;
  position: relative;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: row;
  padding: 15px 0;
}

.prog.expand .div3 .d-link-div3 span {
  background: #11101d;
  padding: 0 5px;
  position: absolute;
  top: -11px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 15px;
  color: rgba(250, 250, 255, 0.3);
}

.prog.expand .div3 .d-link-div3 a {
  margin: 5px 5px;
  padding: 8px;
  width: 100%;
  background: #007bff;
  color: #fff;
  font-size: 16px;
  text-decoration: none;
  border-radius: 4px;
  text-align: center;
  font-family: "Poppins", sans-serif;
  font-weight: 500;
}

.prog.expand .div3 .c-link-div3 {
  position: relative;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  margin-top: 0px;
  min-height: 50px;
}

.prog.expand .div3 .c-link-div3 span {
  background: #11101d;
  padding: 0 5px;
  position: absolute;
  top: -11px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 15px;
  color: rgba(250, 250, 255, 0.3);
}

.prog.expand .div3 .c-link-div3 a {
  display: block;
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 8px;
  width: 100%;
  background: #007bff;
  color: #fff;
  font-size: 16px;
  text-decoration: none;
  border-radius: 4px;
  text-align: center;
  letter-spacing: 1px;
  font-family: "Poppins", sans-serif;
  font-weight: 500;
}

.prog.expand .div3 .view-div3 {
  position: relative;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  margin-top: 0px;
  min-height: 50px;
}

.prog.expand .div3 .view-div3 span {
  background: #11101d;
  padding: 0 5px;
  position: absolute;
  top: -11px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 15px;
  color: rgba(250, 250, 255, 0.3);
}

.prog.expand .div3 .view-div3 a {
  display: block;
  margin-top: 20px;
  margin-bottom: 10px;
  padding: 8px;
  width: 100%;
  background: #007bff;
  color: #fff;
  font-size: 16px;
  text-decoration: none;
  border-radius: 4px;
  text-align: center;
  letter-spacing: 1px;
  font-family: "Poppins", sans-serif;
  font-weight: 500;
}

@media screen and (max-width: 700px) {
  .home-content {
    position: absolute;
    top: 45%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 10px 22px;
    min-width: 270px;
    min-height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    background: #11101d;
    border-radius: 8px;
    box-shadow: 0 -5px 5px rgba(250, 250, 255, 0.05), inset 0 -5px 5px rgba(250, 250, 255, 0.05), 0 5px 5px rgba(0, 0, 0, 0.3), inset 0 5px 5px rgba(0, 0, 0, 0.3);
  }
  .home-content h1 {
    margin-top: 15px;
    font-size: 32px;
    font-family: "Poppins", sans-serif;
  }
  .home-content .hc-links {
    position: relative;
    margin-top: 10px;
    margin-bottom: 25px;
    width: 100%;
    border-radius: 8px;
  }
  .home-content .hc-links div {
    padding: 12px;
    margin-top: 15px;
    display: flex;
    flex-direction: column;
    align-items: stretch;
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(20px);
    border-radius: 10px;
  }
  .home-content .hc-links div:nth-child(2) {
    margin-bottom: 10px;
  }
  .home-content .hc-links div h1 {
    font-size: 25px;
    color: #def;
    margin-bottom: 5px;
  }
  .home-content .hc-links div a {
    white-space: nowrap;
    text-decoration: none;
    color: #fff;
    background: #007bff;
    font-size: 16px;
    padding: 8px;
    text-align: center;
    border-radius: 5px;
  }
  .container .content {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: row;
  }
  .content .prog.shrink {
    margin: 6px;
    margin-bottom: 12px;
  }
  .content .prog.expand {
    position: relative;
    top: 0;
    left: 0;
    transform: translate(0, 0);
    width: 250px;
    min-height: 370px;
    border-radius: 10px;
    overflow: hidden;
    margin: 10px;
    background: #11101d;
    flex-direction: column;
  }
  .prog.expand .div1 {
    position: relative;
    top: 0px;
    width: 100%;
    height: 100px;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    background: #007bff;
  }
  .prog.expand .div1 .collapse {
    height: 32px;
    filter: invert(0);
    opacity: 1;
    position: absolute;
    right: 10px;
  }
  .prog.expand .div1 .progNum {
    position: absolute;
    bottom: -37px;
    left: 15px;
    background: #11101d;
    height: 75px;
    width: 75px;
    padding: 7px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .prog.expand .div1 .progNum>div {
    background: #eee;
    border-radius: 50%;
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .prog.expand .div1 .progNum>div>h1 {
    font-size: 2.5em;
    color: #000;
    opacity: 0.6;
  }
  .prog.expand .div2 {
    padding: 8px 16px;
    display: block;
    position: relative;
    left: 0;
    top: 0;
    min-height: 270px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: #fff;
  }
  .prog.expand .div2 h1 {
    transform: translateY(-10px);
    align-self: flex-end;
    margin-right: 0px;
    font-size: 24px;
    font-weight: 700;
    color: #fff;
    font-family: "Roboto Condensed", sans-serif;
    text-transform: uppercase;
  }
  .prog.expand .div2 p {
    transform: translateY(-10px);
    margin-top: 10px;
    margin-bottom: 0px;
    font-size: 16.5px;
    color: rgba(250, 250, 255, 0.8);
    height: 160px;
    overflow-y: scroll;
    font-family: "Source Sans Pro", sans-serif;
    word-break: break-all;
  }
  .prog.expand .div2 .btns {
    display: flex;
    justify-content: flex-start;
  }
  .prog.expand .div2 .btns .btn {
    border: none;
    border-radius: 4px;
  }
  .prog.expand .div2 .btns .btn1 {
    padding: 4px 5px;
  }
  .prog.expand .div2 .btns .btn1 img {
    height: 28px;
  }
  .prog.expand .div2 .btns .btn2 {
    margin-left: 10px;
    padding: 5px 10px;
  }
  .prog.expand .div2 .btns .btn2 span {
    font-size: 20px;
    margin-right: 10px;
    color: #fff;
    font-family: "Source Sans Pro", sans-serif;
    font-weight: 500;
  }
  .prog.expand .div2 .btns .btn2 img {
    height: 25px;
  }
  .prog.expand .div3 .d-link-div3 {
    flex-direction: column;
    align-items: center;
  }
  .prog.expand .div3 .d-link-div3 a {
    margin: 7px 0;
  }
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>C++ programs</title>
  <link rel="stylesheet" href="css/sideBar.css">
  <link rel="stylesheet" href="css/main.css">

C++programs

                         11th class

                      11th class

                         12th class

                      12th class

                         Others

                      Others

                         Feedback

                      Feedback

                         More

                      More

                         FAQ

                      FAQ

                         Darkmode

C++ programs

1

Program 01:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu ipsum in elit congue blandit. Nullam vitae lobortis lorem, sagittis convallis felis. Praesent tincidunt tristique. Nullam vitae lobortis lorem, sagittis convallis felis.

              <button class="btn btn1 showDiv3">

                                </button>
              <button class="btn btn2">
                                   Source code

                                </button>

C++

              Download
              Turbo C++ Code
              Dev C++ Code

              Compiler
              Compile

              View Code
              View Code

2

Program 02:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eu ipsum in elit congue blandit. Nullam vitae lobortis lorem, sagittis convallis felis. Praesent tincidunt tristique. Nullam vitae lobortis lorem, sagittis convallis felis.

              <button class="btn btn1">

                     </button>
              <button class="btn btn2">
                        Source code

                     </button>

I want to close the div by changing its class from prog expand to  prog shrink

Can anyone tell how can I achieve that ...

Full project :  link

Body:
First you need to have a unique id for example id="prog-one" id="prog-two".

Secondly you need to set the data-target attribute so you can target specific div to toggle(add/remove) classes like this.
<img src="svg/close.svg" class="collapse" data-target="prog-two" id="collapse">

Finally you have to get all the collapse image and add the event listener.

var closeBtns = document.querySelectorAll('.collapse');
    closeBtns.forEach(closeBtn => {
      closeBtn.addEventListener('click', function({target}) {
        const targetId = target.getAttribute('data-target');
        const targetDOM = document.getElementById(targetId);
      console.log('close button clicked..');
      targetDOM.classList.remove('expand');
      targetDOM.classList.add('shrink');
    })
    })

Here is the code pen link. LINK ONE LINKTWO

[UPDATED]

var progElements = document.getElementsByClassName("prog");
var closeBtn = document.getElementById("collapse");
for (let i = 0; i < progElements.length; i++) {
  progElements[i].onclick = function ({ target }) {
    if (target.getAttribute("class") === "collapse") return;
    this.classList.add("expand");
    this.classList.remove("shrink");
    console.log("running");
    for (let j = 0; j < progElements.length; j++) {
      if (i !== j) {
        if (!progElements[j].classList.contains("shrink")) {
          progElements[j].classList.add("shrink");
          progElements[j].classList.remove("expand");
        }
      }
    }
  };
}

var showDiv3 = document.getElementsByClassName("showDiv3");
var div3 = document.getElementsByClassName("div3");
var div3Close = document.getElementsByClassName("div3-close");

for (let i = 0; i < div3.length; i++) {
  showDiv3[i].onclick = function () {
    div3[i].style.display = "block";
    div3[i].style.zIndex = "100";
  };
  div3Close[i].onclick = function () {
    div3[i].style.display = "none";
  };
}

var closeBtns = document.querySelectorAll(".collapse");
closeBtns.forEach((closeBtn) => {
  closeBtn.addEventListener("click", function ({ target }) {
    const targetId = target.getAttribute("data-target");
    const targetDOM = document.getElementById(targetId);
    console.log("close button clicked..");
    targetDOM.className = "prog shrink";
  });
});


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: How do I find Legendre's Symbol?

Body:
Given a 1024 bit modulo and several long integers, I wanted to find out which of these values is a quadratic residue.

The Legendre Symbol is supposed to return -1,0, or 1 and yet my code returns values several orders of magnitude larger than these.

 p = 101524035174539890485408575671085261788758965189060164484385690801466167356667036677932998889725476582421738788500738738503134356158197247473850273565349249573867251280253564698939768700489401960767007716413932851838937641880157263936985954881657889497583485535527613578457628399173971810541670838543309159139

ints = [25081841204695904475894082974192007718642931811040324543182130088804239047149283334700530600468528298920930150221871666297194395061462592781551275161695411167049544771049769000895119729307495913024360169904315078028798025169985966732789207320203861858234048872508633514498384390497048416012928086480326832803, 45471765180330439060504647480621449634904192839383897212809808339619841633826534856109999027962620381874878086991125854247108359699799913776917227058286090426484548349388138935504299609200377899052716663351188664096302672712078508601311725863678223874157861163196340391008634419348573975841578359355931590555, 17364140182001694956465593533200623738590196990236340894554145562517924989208719245429557645254953527658049246737589538280332010533027062477684237933221198639948938784244510469138826808187365678322547992099715229218615475923754896960363138890331502811292427146595752813297603265829581292183917027983351121325, 14388109104985808487337749876058284426747816961971581447380608277949200244660381570568531129775053684256071819837294436069133592772543582735985855506250660938574234958754211349215293281645205354069970790155237033436065434572020652955666855773232074749487007626050323967496732359278657193580493324467258802863, 4379499308310772821004090447650785095356643590411706358119239166662089428685562719233435615196994728767593223519226235062647670077854687031681041462632566890129595506430188602238753450337691441293042716909901692570971955078924699306873191983953501093343423248482960643055943413031768521782634679536276233318, 85256449776780591202928235662805033201684571648990042997557084658000067050672130152734911919581661523957075992761662315262685030115255938352540032297113615687815976039390537716707854569980516690246592112936796917504034711418465442893323439490171095447109457355598873230115172636184525449905022174536414781771, 50576597458517451578431293746926099486388286246142012476814190030935689430726042810458344828563913001012415702876199708216875020997112089693759638454900092580746638631062117961876611545851157613835724635005253792316142379239047654392970415343694657580353333217547079551304961116837545648785312490665576832987, 96868738830341112368094632337476840272563704408573054404213766500407517251810212494515862176356916912627172280446141202661640191237336568731069327906100896178776245311689857997012187599140875912026589672629935267844696976980890380730867520071059572350667913710344648377601017758188404474812654737363275994871, 4881261656846638800623549662943393234361061827128610120046315649707078244180313661063004390750821317096754282796876479695558644108492317407662131441224257537276274962372021273583478509416358764706098471849536036184924640593888902859441388472856822541452041181244337124767666161645827145408781917658423571721, 18237936726367556664171427575475596460727369368246286138804284742124256700367133250078608537129877968287885457417957868580553371999414227484737603688992620953200143688061024092623556471053006464123205133894607923801371986027458274343737860395496260538663183193877539815179246700525865152165600985105257601565]

def Legendre(arr,modulo):
    exponent = ((modulo-1)/2)
    for i in range(len(arr)):
      candidate = int(pow(int(arr[i]),int(exponent),modulo))
      print("{} : {}\n".format(candidate,arr[i]))

Legendre(ints,p)

Body:
p-1 and -1 are congruent modulo p. The expression pow(a, (p-1)//2, p) will return 0, 1, or p-1. If it's p-1, your function should replace that with -1.

Here is a fixed version:

def Legendre(arr, p):
    e = (p - 1) // 2
    results = [pow(a, e, p) for a in arr]
    return [(r-p if r > 1 else r) for r in results]

There is a legendre_symbol function in sympy: https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.residue_ntheory.legendre_symbol

Comparing our fixed version of Legendre with sympy's legendre_symbol:

from sympy import legendre_symbol

p = 101524035174539890485408575671085261788758965189060164484385690801466167356667036677932998889725476582421738788500738738503134356158197247473850273565349249573867251280253564698939768700489401960767007716413932851838937641880157263936985954881657889497583485535527613578457628399173971810541670838543309159139

arr = [25081841204695904475894082974192007718642931811040324543182130088804239047149283334700530600468528298920930150221871666297194395061462592781551275161695411167049544771049769000895119729307495913024360169904315078028798025169985966732789207320203861858234048872508633514498384390497048416012928086480326832803, 45471765180330439060504647480621449634904192839383897212809808339619841633826534856109999027962620381874878086991125854247108359699799913776917227058286090426484548349388138935504299609200377899052716663351188664096302672712078508601311725863678223874157861163196340391008634419348573975841578359355931590555, 17364140182001694956465593533200623738590196990236340894554145562517924989208719245429557645254953527658049246737589538280332010533027062477684237933221198639948938784244510469138826808187365678322547992099715229218615475923754896960363138890331502811292427146595752813297603265829581292183917027983351121325, 14388109104985808487337749876058284426747816961971581447380608277949200244660381570568531129775053684256071819837294436069133592772543582735985855506250660938574234958754211349215293281645205354069970790155237033436065434572020652955666855773232074749487007626050323967496732359278657193580493324467258802863, 4379499308310772821004090447650785095356643590411706358119239166662089428685562719233435615196994728767593223519226235062647670077854687031681041462632566890129595506430188602238753450337691441293042716909901692570971955078924699306873191983953501093343423248482960643055943413031768521782634679536276233318, 85256449776780591202928235662805033201684571648990042997557084658000067050672130152734911919581661523957075992761662315262685030115255938352540032297113615687815976039390537716707854569980516690246592112936796917504034711418465442893323439490171095447109457355598873230115172636184525449905022174536414781771, 50576597458517451578431293746926099486388286246142012476814190030935689430726042810458344828563913001012415702876199708216875020997112089693759638454900092580746638631062117961876611545851157613835724635005253792316142379239047654392970415343694657580353333217547079551304961116837545648785312490665576832987, 96868738830341112368094632337476840272563704408573054404213766500407517251810212494515862176356916912627172280446141202661640191237336568731069327906100896178776245311689857997012187599140875912026589672629935267844696976980890380730867520071059572350667913710344648377601017758188404474812654737363275994871, 4881261656846638800623549662943393234361061827128610120046315649707078244180313661063004390750821317096754282796876479695558644108492317407662131441224257537276274962372021273583478509416358764706098471849536036184924640593888902859441388472856822541452041181244337124767666161645827145408781917658423571721, 18237936726367556664171427575475596460727369368246286138804284742124256700367133250078608537129877968287885457417957868580553371999414227484737603688992620953200143688061024092623556471053006464123205133894607923801371986027458274343737860395496260538663183193877539815179246700525865152165600985105257601565]

our_results = Legendre(arr, p)
sympy_results = [legendre_symbol(a, p) for a in arr]

print(our_results)
print(sympy_results)
# [-1, -1, -1, -1, -1, 1, -1, -1, -1, -1]
# [-1, -1, -1, -1, -1, 1, -1, -1, -1, -1]


问:
Database Schema Name for General Database Tables
When designing databases, I have been following the conventions of the Microsoft AdventureWorks sample database. They use schemas to logically separate groups of tables, e.g. Person, Production or Sales. It makes a lot of sense from a security point of view as well as from an organizational pov.

However, I have some tables that are used in multiple schemas. For example, a Country table that contains all countries. It wouldn't make sense to assign a sepecific schema to it, e.g. Person.Country or Production.Country as it is used in tables of different schemas.

Therefore, which schema do I assign it to?

答: you can use the "dbo" schema, its the default schema for sql-server and many others.</p>


问:
Recieving sqlalchemy.exc.AmbiguousForeignKeysError when querying instances of 'Following' object
```<code>import flask_bcrypt
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

class User(db.Model):
    # __tablename__ = 'user'
    public_id = db.Column(db.String(20), primary_key=True)
    name = db.Column(db.String(50))
    email = db.Column(db.String(100))
    password = db.Column(db.String(100))
    private = db.Column(db.Boolean)
    admin = db.Column(db.Boolean)
    bio = db.Column(db.String(300))
    location = db.Column(db.String(300))
    website = db.Column(db.String(300))
    posts = db.relationship('Post', backref='user')
    like = db.relationship('Like', backref='user')
    comment = db.relationship('Comment', backref='user')
    following = db.relationship('Following', backref='user')

    def __init__(self, public_id, name, email, password, admin, private, bio, location, website):  #
        self.public_id = public_id
        self.name = name
        self.email = email
        self.password = password
        self.private = private
        self.admin = admin
        self.bio = bio
        self.location = location
        self.website = website

class Following(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    following = db.Column(db.String(20), db.ForeignKey('user.public_id'))
    followed = db.Column(db.String(20), db.ForeignKey('user.public_id'))

    def __init__(self, following, followed):
        self.following = following
        self.followed = followed

@app.route('/friends', methods=["GET"])
def get_all_friends():
    friends = Following.query.all()
    return jsonify(friends)
</code>```

I recieve this error when using the friends endpoint: sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship User.following - there are multiple foreign key paths linking the tables.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

Does anyone have any idea how to fix this error?

答:
Your two ForeignKeys in the 'Following' table are conflicting with each other because they link to the same 'User' table and SQLAlchemy doesn't know which ForeignKey to link with User.following. One way to solve this is by adding a 'foreign_keys' argument to the relationships. In your case, you should be able to modify the existing relationship and add a second one. (in your 'User' model)

```<code>following = db.relationship('Following', backref='user', foreign_keys="Following.following")
followed = db.relationship('Following', foreign_keys="Following.followed")
</code>```

For more information, see here.

Body:
import flask_bcrypt
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os

class User(db.Model):
    # __tablename__ = 'user'
    public_id = db.Column(db.String(20), primary_key=True)
    name = db.Column(db.String(50))
    email = db.Column(db.String(100))
    password = db.Column(db.String(100))
    private = db.Column(db.Boolean)
    admin = db.Column(db.Boolean)
    bio = db.Column(db.String(300))
    location = db.Column(db.String(300))
    website = db.Column(db.String(300))
    posts = db.relationship('Post', backref='user')
    like = db.relationship('Like', backref='user')
    comment = db.relationship('Comment', backref='user')
    following = db.relationship('Following', backref='user')

    def __init__(self, public_id, name, email, password, admin, private, bio, location, website):  #
        self.public_id = public_id
        self.name = name
        self.email = email
        self.password = password
        self.private = private
        self.admin = admin
        self.bio = bio
        self.location = location
        self.website = website

class Following(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    following = db.Column(db.String(20), db.ForeignKey('user.public_id'))
    followed = db.Column(db.String(20), db.ForeignKey('user.public_id'))

    def __init__(self, following, followed):
        self.following = following
        self.followed = followed

@app.route('/friends', methods=["GET"])
def get_all_friends():
    friends = Following.query.all()
    return jsonify(friends)

I recieve this error when using the friends endpoint: sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship User.following - there are multiple foreign key paths linking the tables.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

Does anyone have any idea how to fix this error?

Body:
Your two ForeignKeys in the 'Following' table are conflicting with each other because they link to the same 'User' table and SQLAlchemy doesn't know which ForeignKey to link with User.following. One way to solve this is by adding a 'foreign_keys' argument to the relationships. In your case, you should be able to modify the existing relationship and add a second one. (in your 'User' model)

following = db.relationship('Following', backref='user', foreign_keys="Following.following")
followed = db.relationship('Following', foreign_keys="Following.followed")

For more information, see here.


问:
How to unravel type dependency? (X uses undefined class Y)
I'm trying to implement simplistic fast memory management for my delegate type, but encountered circular dependency which I can't solve myself.

```<code>// Size of single bucket of delegates
static constexpr size_t _alloc_buffer_bucket_size = 128;

template <typename TFunc, typename... Args>
struct bucket;

template <typename TFunc, typename... Args>
class Delegate final : public IDelegate
{
    . . .

    static void* operator new (size_t size)
    {
        auto bckt = _current_bucket; // gives compilation error here
    }
private:

    // Size of single bucket of delegates
    static constexpr size_t _alloc_buffer_bucket_size = 128;
    struct bucket
    {
        // stores currently occupied slots in bucket.
        size_t allocated_slots = 0;
        // when this bucket is filling with values, this
        size_t current_slot = 0;
        std::array<Delegate<TFunc, Args...>, _alloc_buffer_bucket_size> slots = {};
    };
    // Vector of buckets.
    inline static std::vector<bucket*> _alloc_buffer = { new bucket(), };
    // This is a pointer to currently filling bucket. New delegates are added here
    // by delegate allocator.
    // When this bucket reaches _alloc_buffer_bucket_size of items, this pointer is
    // replaced with either newly allocated bucket or existing and empty bucket.
    inline static bucket* _current_bucket = &(_alloc_buffer[0]);
};
</code>```

This gives me "'Delegate<void (*)(void)>::bucket::slots' uses undefined class 'std::array<Delegate<void (*)(void)>,128>'".
How can I break this circular dependency? I've tried using more pointers, moving bucket outside of Delegate scope, but this error remains.

答:
By moving the definition of the bucket struct outside of the scope of Delegate and assigning the _alloc_buffer and _current_bucket variables outside of the class scope, we can achieve compilation.  I was able to get it compiling as such:

// Size of single bucket of delegates
static constexpr std::size_t _alloc_buffer_bucket_size = 128;

template <typename TFunc, typename... Args>
struct bucket;

template <typename TFunc, typename... Args>
class Delegate final : public IDelegate
{
public:
    Delegate() = default;
    static void* operator new (std::size_t size)
    {
        auto bckt = _current_bucket; // gives compilation error here
        return nullptr; // added to get rid of the error
    }
private:
    // Vector of buckets.
    static std::vector<bucket<TFunc, Args...>*> _alloc_buffer;
    // This is a pointer to currently filling bucket. New delegates are added here
    // by delegate allocator.
    // When this bucket reaches _alloc_buffer_bucket_size of items, this pointer is
    // replaced with either newly allocated bucket or existing and empty bucket.
    static bucket<TFunc, Args...>* _current_bucket;
};

template <typename TFunc, typename... Args>
struct bucket
{
    // stores currently occupied slots in bucket.
    std::size_t allocated_slots = 0;
    // when this bucket is filling with values, this
    std::size_t current_slot = 0;
    std::array<Delegate<TFunc, Args...>, _alloc_buffer_bucket_size> slots = {};
};

template <typename TFunc, typename... Args>
std::vector<bucket<TFunc, Args...>*> Delegate<TFunc, Args...>::_alloc_buffer = { new bucket<TFunc, Args...>(), };

template <typename TFunc, typename... Args>
bucket<TFunc, Args...>* Delegate<TFunc, Args...>::_current_bucket = &(_alloc_buffer[0]);
```

By splitting up the declaration and definition of the static variables and by splitting out the bucket type, the Delegate class is defined by the time we go to actually use it.  See it in action here: https://godbolt.org/z/bx7hh1av9

Edit: Tested this minimum sample on MSVC and Clang.

Body:
I'm trying to implement simplistic fast memory management for my delegate type, but encountered circular dependency which I can't solve myself.

// Size of single bucket of delegates
static constexpr size_t _alloc_buffer_bucket_size = 128;

template <typename TFunc, typename... Args>
struct bucket;

template <typename TFunc, typename... Args>
class Delegate final : public IDelegate
{
    . . .

    static void* operator new (size_t size)
    {
        auto bckt = _current_bucket; // gives compilation error here
    }
private:

    // Size of single bucket of delegates
    static constexpr size_t _alloc_buffer_bucket_size = 128;
    struct bucket
    {
        // stores currently occupied slots in bucket.
        size_t allocated_slots = 0;
        // when this bucket is filling with values, this
        size_t current_slot = 0;
        std::array<Delegate<TFunc, Args...>, _alloc_buffer_bucket_size> slots = {};
    };
    // Vector of buckets.
    inline static std::vector<bucket*> _alloc_buffer = { new bucket(), };
    // This is a pointer to currently filling bucket. New delegates are added here
    // by delegate allocator.
    // When this bucket reaches _alloc_buffer_bucket_size of items, this pointer is
    // replaced with either newly allocated bucket or existing and empty bucket.
    inline static bucket* _current_bucket = &(_alloc_buffer[0]);
};

This gives me "'Delegate<void (*)(void)>::bucket::slots' uses undefined class 'std::array<Delegate<void (*)(void)>,128>'".
How can I break this circular dependency? I've tried using more pointers, moving bucket outside of Delegate scope, but this error remains.

Body:
By moving the definition of the bucket struct outside of the scope of Delegate and assigning the _alloc_buffer and _current_bucket variables outside of the class scope, we can achieve compilation.  I was able to get it compiling as such:

// Size of single bucket of delegates
static constexpr std::size_t _alloc_buffer_bucket_size = 128;

template <typename TFunc, typename... Args>
struct bucket;

template <typename TFunc, typename... Args>
class Delegate final : public IDelegate
{
public:
    Delegate() = default;
    static void* operator new (std::size_t size)
    {
        auto bckt = _current_bucket; // gives compilation error here
        return nullptr; // added to get rid of the error
    }
private:
    // Vector of buckets.
    static std::vector<bucket<TFunc, Args...>*> _alloc_buffer;
    // This is a pointer to currently filling bucket. New delegates are added here
    // by delegate allocator.
    // When this bucket reaches _alloc_buffer_bucket_size of items, this pointer is
    // replaced with either newly allocated bucket or existing and empty bucket.
    static bucket<TFunc, Args...>* _current_bucket;
};

template <typename TFunc, typename... Args>
struct bucket
{
    // stores currently occupied slots in bucket.
    std::size_t allocated_slots = 0;
    // when this bucket is filling with values, this
    std::size_t current_slot = 0;
    std::array<Delegate<TFunc, Args...>, _alloc_buffer_bucket_size> slots = {};
};

template <typename TFunc, typename... Args>
std::vector<bucket<TFunc, Args...>*> Delegate<TFunc, Args...>::_alloc_buffer = { new bucket<TFunc, Args...>(), };

template <typename TFunc, typename... Args>
bucket<TFunc, Args...>* Delegate<TFunc, Args...>::_current_bucket = &(_alloc_buffer[0]);

By splitting up the declaration and definition of the static variables and by splitting out the bucket type, the Delegate class is defined by the time we go to actually use it.  See it in action here: https://godbolt.org/z/bx7hh1av9

Edit: Tested this minimum sample on MSVC and Clang.


问:
Run search function on each keypress
I have this function that when I click on submit or press Enter that uses the value in the input and scans for it in the child of each div, and if it finds one it hides all and shows only that div.

However I want to make this function run/scan with each keypress so that it continuously updates the list of results and not only when you submit.

I tried .on('keypress), keyup, keydown, keypress with no luck so far.

```<code>$('.search-form').on('submit',function(){return false;});
    $('.hidden-submit-button').on('click', function(e){
    var query = $.trim($(this).prevAll('.search-input').val()).toLowerCase();
    $('div.team_single-member .person-name').each(function(){
      var $this = $(this);
        if($this.text().toLowerCase().indexOf(query) === -1)
            $this.closest('div.team_single-member-wrap').hide();
        else $this.closest('div.team_single-member-wrap').show();
    });
});
</code>```

答:
To do what you require you can change the event handler to listen for the input event on the .search-input directly.

Also note that you can use a case-insensitive version of the :contains selector to make your code more succinct:

jQuery.expr[':'].icontains = (a, i, m) => jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;

$('.search-form').on('submit', e => e.preventDefault());

$('.search-input').on('input', e => {
  var query = e.currentTarget.value.trim().toLowerCase();
  $('div.team_single-member .person-name').hide().filter(`:icontains(${query})`).show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<form class="search-form">
  <input type="text" class="search-input" />
</form>

<div class="team_single-member">
  <p class="person-name">Foo</p>
</div>
<div class="team_single-member">
  <p class="person-name">Bar</p>
</div>
<div class="team_single-member">
  <p class="person-name">Fizz</p>
</div>
<div class="team_single-member">
  <p class="person-name">Buzz</p>
</div>  </code>```

Title: Run search function on each keypress

Body:
I have this function that when I click on submit or press Enter that uses the value in the input and scans for it in the child of each div, and if it finds one it hides all and shows only that div.

However I want to make this function run/scan with each keypress so that it continuously updates the list of results and not only when you submit.

I tried .on('keypress), keyup, keydown, keypress with no luck so far.

$('.search-form').on('submit',function(){return false;});
    $('.hidden-submit-button').on('click', function(e){
    var query = $.trim($(this).prevAll('.search-input').val()).toLowerCase();
    $('div.team_single-member .person-name').each(function(){
      var $this = $(this);
        if($this.text().toLowerCase().indexOf(query) === -1)
            $this.closest('div.team_single-member-wrap').hide();
        else $this.closest('div.team_single-member-wrap').show();
    });
});

Body:
To do what you require you can change the event handler to listen for the input event on the .search-input directly.

Also note that you can use a case-insensitive version of the :contains selector to make your code more succinct:

jQuery.expr[':'].icontains = (a, i, m) => jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;

$('.search-form').on('submit', e => e.preventDefault());

$('.search-input').on('input', e => {
  var query = e.currentTarget.value.trim().toLowerCase();
  $('div.team_single-member .person-name').hide().filter(`:icontains(${query})`).show();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<form class="search-form">
  <input type="text" class="search-input" />
</form>

<div class="team_single-member">
  <p class="person-name">Foo</p>
</div>
<div class="team_single-member">
  <p class="person-name">Bar</p>
</div>
<div class="team_single-member">
  <p class="person-name">Fizz</p>
</div>
<div class="team_single-member">
  <p class="person-name">Buzz</p>
</div>


问:
Consuming an IAsyncEnumerable
I have one web API application that has a function that needs to stream some data. Then I have another web application that basically acts like a proxy for that. This other application does a whole lot of other stuff like handling authorization and such. It needs to connect to the API endpoint and pass the stream through potentially doing some addition processing for each row of data. In one case it will need to write out that data into an Excel file, for example.

Unfortunately, I see a lot of tutorials on how to create an IAsyncEnumerable, but not any about actually connecting to an endpoint that exposes one.

Ideally, I would like to actually wrap my IAsyncEnumerable and return it with some other stuff. This is what I basically do with other non-streamed endpoints already:

```<code>public class NonStreamedResult : BaseResult
{
    public SomeMetaData MetaData {get; set; }
    // here Data is usually small, so returning it all at once is no big deal
    public IEnumerable<SomeData> Data {get; set; }
}

//....controller
public async Task<NonStreamedResult> GetNonStreamedData()
</code>```

And on the consuming side, I'm using an HttpClient, awaiting an HttpResponseMessage and using ReadAsAsync<T> to turn that response into an object.

However, if I try to do this:

```<code>public class StreamedResult : BaseResult
{
    public SomeOtherMetaData MetaData {get; set; }
    // Here data could be huge, so we don't want to have to hold it all in memory at once
    public IAsyncEnumerable<SomeData> Data {get; set; }
}

//....controller
public async Task<StreamedResult> GetStreamedData()
</code>```

I will get an error when it tries to deserialize because it doesn't know what concrete class to convert the IAsyncEnumerable into.

So what's the right way to connect to an endpoint that is using an IAsyncEnumerable without loading the entire response into memory (obviously) so that I can eventually return another IAsyncEnumerable from the proxy app?

It would be nice if I could still pass it wrapped, but it's not the end of the world if I have to work with just the naked IAsyncEnumerable

Note that I'm using the Microsoft.Bcl.AsyncInterfaces NuGet package since I'm still targeting an earlier version of the .NET framework.

答:
I'm still targeting an earlier version of the .NET framework.

That's not going to work well. Unbuffered IAsyncEnumerable<T> support was added in ASP.NET 6.

If you can't upgrade, then you'll need to write your own streaming JSON parser and your own streaming JSON serializer wrapped up in a custom formatter that flushes periodically. This is a non-trivial amount of work. The remainder of my answer assumes you will move to .NET 6.

It would be nice if I could still pass it wrapped, but it's not the end of the world if I have to work with just the naked IAsyncEnumerable

Wrapped can't possibly work. Just consider the situation where you define multiple IAsyncEnumerable<T> properties. When dealing with IAsyncEnumerable<T> in ASP.NET 6, you must return it as a top-level type. Metadata can be represented as headers.

To consume, first ensure that you set the HttpClient completion options so that the HTTP operation is considered "complete" when the headers are received, and then you can take the response body stream and pass it to JsonSerializer.DeserializeAsyncEnumerable. After retrieving each item from the downstream API, you can do whatever processing you need and then yield it to be streamed to your client.

Title: Consuming an IAsyncEnumerable

Body:
I have one web API application that has a function that needs to stream some data. Then I have another web application that basically acts like a proxy for that. This other application does a whole lot of other stuff like handling authorization and such. It needs to connect to the API endpoint and pass the stream through potentially doing some addition processing for each row of data. In one case it will need to write out that data into an Excel file, for example.

Unfortunately, I see a lot of tutorials on how to create an IAsyncEnumerable, but not any about actually connecting to an endpoint that exposes one.

Ideally, I would like to actually wrap my IAsyncEnumerable and return it with some other stuff. This is what I basically do with other non-streamed endpoints already:

public class NonStreamedResult : BaseResult
{
    public SomeMetaData MetaData {get; set; }
    // here Data is usually small, so returning it all at once is no big deal
    public IEnumerable<SomeData> Data {get; set; }
}

//....controller
public async Task<NonStreamedResult> GetNonStreamedData()

And on the consuming side, I'm using an HttpClient, awaiting an HttpResponseMessage and using ReadAsAsync<T> to turn that response into an object.

However, if I try to do this:

public class StreamedResult : BaseResult
{
    public SomeOtherMetaData MetaData {get; set; }
    // Here data could be huge, so we don't want to have to hold it all in memory at once
    public IAsyncEnumerable<SomeData> Data {get; set; }
}

//....controller
public async Task<StreamedResult> GetStreamedData()

I will get an error when it tries to deserialize because it doesn't know what concrete class to convert the IAsyncEnumerable into.

So what's the right way to connect to an endpoint that is using an IAsyncEnumerable without loading the entire response into memory (obviously) so that I can eventually return another IAsyncEnumerable from the proxy app?

It would be nice if I could still pass it wrapped, but it's not the end of the world if I have to work with just the naked IAsyncEnumerable

Note that I'm using the Microsoft.Bcl.AsyncInterfaces NuGet package since I'm still targeting an earlier version of the .NET framework.


问:
How to create a diagonal matrix in R?
I have an excel file which contains 250 sheets( 1st sheet contains 250 rows and 11 columns,2nd sheet contains 249 rows and 11 columns, 3rd sheet contains 248 rows and 11 columns and so on). I need only the values of 11th column from all sheets for creating diagonal matrix. I think , First I have to import 11th column values from excel file to R . Based on these values I have to create a diagonal matrix . Please help me</p>

答:
You can use the Diagonal function from the Matrix library; just pass in the dimension and value (which seem to be what is in column 11 of your spreadsheet):

```<code>> library(Matrix)
> v = Diagonal(n=5, x=5.5)
> v
  5 x 5 diagonal matrix of class "ddiMatrix"
       [,1] [,2] [,3] [,4] [,5]
  [1,]  5.5    .    .    .    .
  [2,]    .  5.5    .    .    .
  [3,]    .    .  5.5    .    .
  [4,]    .    .    .  5.5    .
  [5,]    .    .    .    .  5.5
</code>```

(Note: Matrix needs to be explicitly imported via call to Library, though not separately installed because it seems to be included in the the R install)

ContentLicense: CC BY-SA 3.0

Title: How to create a diagonal matrix in R?

Body:
You can use the Diagonal function from the Matrix library; just pass in the dimension and value (which seem to be what is in column 11 of your spreadsheet):

> library(Matrix)
> v = Diagonal(n=5, x=5.5)
> v
  5 x 5 diagonal matrix of class "ddiMatrix"
       [,1] [,2] [,3] [,4] [,5]
  [1,]  5.5    .    .    .    .
  [2,]    .  5.5    .    .    .
  [3,]    .    .  5.5    .    .
  [4,]    .    .    .  5.5    .
  [5,]    .    .    .    .  5.5

(Note: Matrix needs to be explicitly imported via call to Library, though not separately installed because it seems to be included in the the R install)


问:
Create Spark dataframe from groupby and known sequence vector
I have the following dataframe

| Col1 | Col2 | Value  |
|------|------|--------|
| Key1 | Key2 | 45.0   |
| Key2 | Key2 | 34.0   |
| Key2 | Key3 | 121.0  |
```
<p>and I have the sequence of values <code>[1,2,3]</code>. I would like to generate the following dataframe</p>
<pre class="lang-none prettyprint-override"><code>| Col1 | Col2 | Value  |
|------|------|--------|
| Key1 | Key2 |  1     |
| Key1 | Key2 |  2     |
| Key1 | Key2 |  3     |
| Key2 | Key2 |  1     |
| Key2 | Key2 |  2     |
| Key2 | Key2 |  3     |
| Key2 | Key3 |  1     |
| Key2 | Key3 |  2     |
| Key2 | Key3 |  3     |
</code>```

The pairs of (Col1,Col2) are generate from a groupBy and, in my new dataframe, I would like each pair returned by the GroupBy to be repeated three times, once for each value of the sequence. I will then use the combination of (Col1,Col2,Value) to left join that dataframe with another one.

One solution I have thought about could be to take the union of three different dataframe, each of them with rows containing distinct (Col1,Col2) with the given value of the sequence, that is

```<code>df.groupBy(['Col1','Col2']).agg(F.lit(1).alias('Value')).union(df.groupBy(['Col1','Col2']).agg(F.lit(2).alias('Value')))
</code>```

I would like to find a more elegant solution as this one looks very similar to what I would do in SQL.

答:
Simply create a literal array column and explode it:</p>
```<code>from pyspark.sql import functions as F

df = spark.createDataFrame([
    ("Key1", "Key2", 45.0), ("Key2", "Key2", 34.0),
    ("Key2", "Key3", 121.0)], ("Col1", "Col2", "Value"))

values = [1, 2, 3]
df1 = df.withColumn("Value", F.explode(F.array(*[F.lit(x) for x in values])))

df1.show()
#+----+----+-----+
#|Col1|Col2|Value|
#+----+----+-----+
#|Key1|Key2|    1|
#|Key1|Key2|    2|
#|Key1|Key2|    3|
#|Key2|Key2|    1|
#|Key2|Key2|    2|
#|Key2|Key2|    3|
#|Key2|Key3|    1|
#|Key2|Key3|    2|
#|Key2|Key3|    3|
#+----+----+-----+
</code>```

Body:
I have the following dataframe

| Col1 | Col2 | Value  |
|------|------|--------|
| Key1 | Key2 | 45.0   |
| Key2 | Key2 | 34.0   |
| Key2 | Key3 | 121.0  |

and I have the sequence of values [1,2,3]. I would like to generate the following dataframe

| Col1 | Col2 | Value  |
|------|------|--------|
| Key1 | Key2 |  1     |
| Key1 | Key2 |  2     |
| Key1 | Key2 |  3     |
| Key2 | Key2 |  1     |
| Key2 | Key2 |  2     |
| Key2 | Key2 |  3     |
| Key2 | Key3 |  1     |
| Key2 | Key3 |  2     |
| Key2 | Key3 |  3     |

The pairs of (Col1,Col2) are generate from a groupBy and, in my new dataframe, I would like each pair returned by the GroupBy to be repeated three times, once for each value of the sequence. I will then use the combination of (Col1,Col2,Value) to left join that dataframe with another one.

One solution I have thought about could be to take the union of three different dataframe, each of them with rows containing distinct (Col1,Col2) with the given value of the sequence, that is

df.groupBy(['Col1','Col2']).agg(F.lit(1).alias('Value')).union(df.groupBy(['Col1','Col2']).agg(F.lit(2).alias('Value')))

I would like to find a more elegant solution as this one looks very similar to what I would do in SQL.

Body:
Simply create a literal array column and explode it:

from pyspark.sql import functions as F

df = spark.createDataFrame([
    ("Key1", "Key2", 45.0), ("Key2", "Key2", 34.0),
    ("Key2", "Key3", 121.0)], ("Col1", "Col2", "Value"))

values = [1, 2, 3]
df1 = df.withColumn("Value", F.explode(F.array(*[F.lit(x) for x in values])))

df1.show()
#+----+----+-----+
#|Col1|Col2|Value|
#+----+----+-----+
#|Key1|Key2|    1|
#|Key1|Key2|    2|
#|Key1|Key2|    3|
#|Key2|Key2|    1|
#|Key2|Key2|    2|
#|Key2|Key2|    3|
#|Key2|Key3|    1|
#|Key2|Key3|    2|
#|Key2|Key3|    3|
#+----+----+-----+


问:
Error: Access to XMLHttpRequest at https://storage.googleapis.com/url from origin has been blocked by CORS policy. In angular when using gcp SignedURl
I using angular and nodejs for my application. Now I have pdf files stored in the gcp cloud storage bucket and by using getSignedUrl method in nodejs I am getting the url of the pdf file.

this is my nodejs code:

```<code>try {
      let file = await bucket.file(fileName);
      let url = await file.getSignedUrl({
        action: "read",
        expires: dd + "-" + mm + "-" + yyyy
      });
      res.send({
        message: "found url",
        data: url,
      });
    } catch (e) {
      console.log(e);
      res.status(400).send({ message: e });
    }
</code>```

Now in angular side I am trying to get this pdf file using the SignedUrl that I getting from nodejs:

angular-service.ts

```<code>  getDataOfUrl(url) {
    let headers = new HttpHeaders();
    headers.set('Accept', 'application/pdf');
    this.http.get(url, { headers: headers, responseType: 'blob' as 'json' }).
    subscribe(data => {
      console.log(data)
    }, (err) => {
      console.log(err)
    })
  }
</code>```

angular.component.ts

```<code>  onFileDownload(filename) {
    let body = {
      fileId: filename+".pdf"
    }
    this.homepageService.downloadFile(body).subscribe(
      (data) =>{
        this.signedUrl = data.data[0];
        this.homepageService.getDataOfUrl(this.signedUrl)
        window.open(data.data[0])
      }, (error) => {
        console.log(error)
      }
    )
  }
</code>```

Now onFileDownload doing two job :

getting the signedUrl and open pdf file in the new tab so that we can download it (this is working fine).

But I posting this question because of this method this.homepageService.getDataOfUrl(this.signedUrl), when I pass the url to get the pdf data in some format so that I can use that data for further use like converting the pdf into image.

I am getting error from that:

Error:

```<code>Access to XMLHttpRequest at 'https://storage.googleapis.com/url' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'https://storage.googleapis.com/humana-author-pubsu…Et3Da%2BkAtV57lVpNuIs6L1%2BkaUKJCHU65rglKLA%3D%3D', ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}

GET https://storage.googleapis.com/url net::ERR_FAILED 200
</code>```

答:
Your bucket is denying access from external sources due to security reasons. In this case the http://localhost:4200 address. This is what CORS is designed to do.

Google has a guide on how to configure CORS for your bucket. You need to do this for your localhost address and any other websites that you plan on having retrieve this data.

Body:
I using angular and nodejs for my application. Now I have pdf files stored in the gcp cloud storage bucket and by using getSignedUrl method in nodejs I am getting the url of the pdf file.

this is my nodejs code:

try {
      let file = await bucket.file(fileName);
      let url = await file.getSignedUrl({
        action: "read",
        expires: dd + "-" + mm + "-" + yyyy
      });
      res.send({
        message: "found url",
        data: url,
      });
    } catch (e) {
      console.log(e);
      res.status(400).send({ message: e });
    }

Now in angular side I am trying to get this pdf file using the SignedUrl that I getting from nodejs:

angular-service.ts

  getDataOfUrl(url) {
    let headers = new HttpHeaders();
    headers.set('Accept', 'application/pdf');
    this.http.get(url, { headers: headers, responseType: 'blob' as 'json' }).
    subscribe(data => {
      console.log(data)
    }, (err) => {
      console.log(err)
    })
  }

angular.component.ts

  onFileDownload(filename) {
    let body = {
      fileId: filename+".pdf"
    }
    this.homepageService.downloadFile(body).subscribe(
      (data) =>{
        this.signedUrl = data.data[0];
        this.homepageService.getDataOfUrl(this.signedUrl)
        window.open(data.data[0])
      }, (error) => {
        console.log(error)
      }
    )
  }

Now onFileDownload doing two job :

getting the signedUrl and open pdf file in the new tab so that we can download it (this is working fine).

But I posting this question because of this method this.homepageService.getDataOfUrl(this.signedUrl), when I pass the url to get the pdf data in some format so that I can use that data for further use like converting the pdf into image.

I am getting error from that:

Error:

Access to XMLHttpRequest at 'https://storage.googleapis.com/url' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'https://storage.googleapis.com/humana-author-pubsu…Et3Da%2BkAtV57lVpNuIs6L1%2BkaUKJCHU65rglKLA%3D%3D', ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}

GET https://storage.googleapis.com/url net::ERR_FAILED 200


问:
VueJS: How can I pass params into a component?
I am new to vueJS.
What I want to do is passing parameters to a component, depending on the selection of the routes. Here is my App.vue:

```<code><template>
  <div id="main">
    <header>
      <h1 style="color:red">{{msg}}</h1>
    </header>

    <div>
      <aside class="sidebar">
        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>
      </aside>
      <SubMenu></SubMenu>

      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
  import SubMenu from './components/SubMenu.vue'
  export default {
    components: {
      'SubMenu': SubMenu
    },
    data() {
      return {
        msg: 'Welcome to Your Vue.js App'      }
    }
  }

</script>

<style>
  @import 'style.css';
  @import 'grid.css';
</style>
</code>```

and the SubMenu component I would like to make dynamic:

```<code><template>
  <div>
    something dynamic
  </div>
</template>
</code>```

How can I pass some parameters to use in the component?
thank you

答:
Your App.vue can be like this:

<template>

{{msg}}

        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>

      <SubMenu :menuTitle="subMenuTitle"></SubMenu>

        <router-view></router-view>

</template>

```
<p>The SubMenu.vue component could be like this:</p>
<pre class="lang-js prettyprint-override"><code><template>
  <div>
    <h2>{{ menuTitle }}</h2>
    something dynamic
  </div>
</template>

<script>
export default {
  name: "SubMenu",
  props: {
    menuTitle: String,
  }
}
</script>
</code>```

In the SubMenu component that was used in App.vue, notice the colon that appears before the menuTitle attribute. When you do that before an attribute, the value of that attribute would be evaluated by Vue and passed to the component. You can pass literal Javascript expressions or items in your App.vue component.

In the SubMenu component, you can use the props in whatever way you can. If the prop's value is an array, you can use the v-for directive with it to create a list of items in the SubMenu.

Body:
I am new to vueJS.
What I want to do is passing parameters to a component, depending on the selection of the routes. Here is my App.vue:

<template>

{{msg}}

        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>

      <SubMenu></SubMenu>

        <router-view></router-view>

</template>

and the SubMenu component I would like to make dynamic:

<template>

    something dynamic

</template>

How can I pass some parameters to use in the component?
thank you

Body:
Your App.vue can be like this:

<template>
  <div id="main">
    <header>
      <h1 style="color:red">{{msg}}</h1>
    </header>

    <div>
      <aside class="sidebar">
        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>
      </aside>
      <SubMenu :menuTitle="subMenuTitle"></SubMenu>

      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
  import SubMenu from './components/SubMenu.vue';

  export default {
    components: {
      SubMenu
    },
    data() {
      return {
        subMenuTitle: "This is the sub menu",
        msg: 'Welcome to Your Vue.js App'
      }
    }
  }

</script>

<style>
  @import 'style.css';
  @import 'grid.css';
</style>

The SubMenu.vue component could be like this:

<template>
  <div>
    <h2>{{ menuTitle }}</h2>
    something dynamic
  </div>
</template>

<script>
export default {
  name: "SubMenu",
  props: {
    menuTitle: String,
  }
}
</script>

In the SubMenu component that was used in App.vue, notice the colon that appears before the menuTitle attribute. When you do that before an attribute, the value of that attribute would be evaluated by Vue and passed to the component. You can pass literal Javascript expressions or items in your App.vue component.

In the SubMenu component, you can use the props in whatever way you can. If the prop's value is an array, you can use the v-for directive with it to create a list of items in the SubMenu.


问:
Creating an Array from a Range in VBA
I'm having a seemingly basic problem but can't find any resources addressing it.

Simply put, I just want to load the contents of a Range of cells (all one column) into an Array.

I am able to accomplish this by means of

```<code>DirArray = Array(Range("A1"), Range("A2"))
</code>```

But for some reason, I cannot create the array when expressed this way:

```<code>DirArray = Array(Range("A1:A2"))
</code>```

My real Range is much longer (and may vary in length), so I don't want to have to individually enumerate the cells this way. Can anyone tell me how to properly load a whole Range into an Array?

With the latter code:

```<code>MsgBox UBound(DirArray, 1)
</code>```

And

```<code>MsgBox UBound(DirArray)
</code>```

Return 0, whereas with the former they return 1.

答:
Transpose is a great advice.
I have multiple arrays in my app. Some global, some local, some loaded from ranges and some created programatically.

I had numerous problems with dimensioning. Now, with transpose they are all one dimension.

I did have to modify code slightly, because one version runs on Excel 2003 and another (slower) on 2010.

Caution: You will have to Transpose the array again, when saving it to a range.

Title: Creating an Array from a Range in VBA

Body:
I'm having a seemingly basic problem but can't find any resources addressing it.

Simply put, I just want to load the contents of a Range of cells (all one column) into an Array.

I am able to accomplish this by means of

DirArray = Array(Range("A1"), Range("A2"))

But for some reason, I cannot create the array when expressed this way:

DirArray = Array(Range("A1:A2"))

My real Range is much longer (and may vary in length), so I don't want to have to individually enumerate the cells this way. Can anyone tell me how to properly load a whole Range into an Array?

With the latter code:

MsgBox UBound(DirArray, 1)

And

MsgBox UBound(DirArray)

Return 0, whereas with the former they return 1.


问:
Npm error 403 when downloading dependencies from Artifactory
I am trying to run a job with a Node.js project. One of the steps is rtnpminstall which runs the npm install command. The rtnpminstall command is run by the Artifactory plugin on Jenkins. The error says.

```<code>npm ERR! code E403
npm ERR! 403 403 Forbidden - GET
 https://<artifactoryurl>/artifactory/api/npm/<npm registry>/<dependency name>
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.
</code>```

But when I run using npm install -g, it works fine.

When I can click on the dependency link in the jenkins job log, it downloads fine.

I am trying to see what could be the issue as we do not want to use -g option.

My guess is there night be no write permission on project folder on jenkins agent.

答:
As Muhammed Kashif wrote in his note above -

403 error means that the user does not have permissions and mostly the Deploy/Cache permission because the dependencies are downloaded from the remote source and need to be cached.

This confusing "403" message comes from Artifactory -

not from the remote repository - because without the Deploy/Cache permissions

the user is forbidden from saving artifacts in the cache.

JFrog actually has a page describing this situation, but

only after reading Muhammed's comment I understood what they meant :)

Body:
I am trying to run a job with a Node.js project. One of the steps is rtnpminstall which runs the npm install command. The rtnpminstall command is run by the Artifactory plugin on Jenkins. The error says.

npm ERR! code E403
npm ERR! 403 403 Forbidden - GET
 https://<artifactoryurl>/artifactory/api/npm/<npm registry>/<dependency name>
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.

But when I run using npm install -g, it works fine.

When I can click on the dependency link in the jenkins job log, it downloads fine.

I am trying to see what could be the issue as we do not want to use -g option.

My guess is there night be no write permission on project folder on jenkins agent.


问:
Can't execute drop index in psycopg2 connect in python
I'm trying to use psycopg2 in python to drop index in postgresql:

```<code>connection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database)
cur = connection.cursor()
statement = "DROP INDEX IF EXISTS idx_my_id"
cur.execute(statement)
connection.commit()
</code>```

Same statement can be done in pgAdmin4 in one second. But in python, the execution never finished.

"pg_stat_activity" shows wait_event_type is Lock and wait_event is relation.

What went wrong?

答:
won't fit in comments put it here. maybe because you don't commit your connections?

add this to your code , close all the connections and try again:

```<code>connection.set_session(autocommit=True)
</code>```

Body:
I'm trying to use psycopg2 in python to drop index in postgresql:

connection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database)
cur = connection.cursor()
statement = "DROP INDEX IF EXISTS idx_my_id"
cur.execute(statement)
connection.commit()

Same statement can be done in pgAdmin4 in one second. But in python, the execution never finished.

"pg_stat_activity" shows wait_event_type is Lock and wait_event is relation.

What went wrong?

Body:
won't fit in comments put it here. maybe because you don't commit your connections?

add this to your code , close all the connections and try again:

connection.set_session(autocommit=True)


问:
Is there any other API to pull transaction data using Invoice data?
I am using REST APIs. I am trying to pull the transaction data especially transaction_id using Invoice_id.

In transaction search, I am able to see the transaction_id and invoice_id. However, I am unable to find the link to pull the transaction_id details using Invoice_id.

Is there any other API to pull transaction data using Invoice data?

答:
No, PayPal isn't a database service. For historical transactions, best approach is to use the web account interface Reports function to download CSV files of the data and import this into your own database.

For keeping it current, store new transaction records immediately when a new transaction is created via the capture API call. Use a server-side create/capture if you aren't already (see the optional bullet #5 in the Integrate Checkout guide)


问:
How do I highlight text in PHP with conditions?
I have some numbers, and depending on the number's value I need to highlight a string which is in a table. The table is not in database.

Does anyone know how to highlight text in php?

答:
Presentation, like highlighting, is done in CSS, not PHP.

My advice would be to create a CSS class which has a background-color defined to be used as highlighting. Then, in PHP, you can conditionally wrap your string in  tags which have that class, so the text would be highlighted.

CSS:

```<code>.highlight {
   background-color: #FF0;
}
</code>```

PHP:

```<code>if (highlightCondition) {
   echo '<span class="highlight">' . $string . '</span>';
} else {
   echo $string;
}
</code>```

Body:
Presentation, like highlighting, is done in CSS, not PHP.

My advice would be to create a CSS class which has a background-color defined to be used as highlighting. Then, in PHP, you can conditionally wrap your string in <span> tags which have that class, so the text would be highlighted.

CSS:

.highlight {
   background-color: #FF0;
}

PHP:

if (highlightCondition) {
   echo '<span class="highlight">' . $string . '</span>';
} else {
   echo $string;
}


问:
How to convert to 1-dimensional list a list of a string that is list that contains int elements
Can't figure out how to make a proper 1-dimensional list out of

```<code>a = ['[2,5911,3391,10687,9796,15870,11533]']
a[1:-1]

</code>```

i want to get
[2,5911,3391,10687,9796,15870,11533]

Slices don't seem to work there

Is there any elegant way to do it without writing 2 for loops
Appreciate all the help

Body:
Can't figure out how to make a proper 1-dimensional list out of

a = ['[2,5911,3391,10687,9796,15870,11533]']
a[1:-1]

i want to get
[2,5911,3391,10687,9796,15870,11533]

Slices don't seem to work there

Is there any elegant way to do it without writing 2 for loops
Appreciate all the help

Body:
You have to first get the string a[0] then remove the brakets: a[0][1:-1] then you can use .split() like so:

a = ['[2,5911,3391,10687,9796,15870,11533]']
a = a[0][1:-1].split(',')
print(a)

Output:

['2', '5911', '3391', '10687', '9796', '15870', '11533']

You can also get the integers (if that's what you're after) using a list comprehension like so:

a = ['[2,5911,3391,10687,9796,15870,11533]']
a = [int(item) for item in a[0][1:-1].split(',')]
print(a)

Output:

[2, 5911, 3391, 10687, 9796, 15870, 11533]