问:
price depend on selection of radio input
I tried but can't get it after this so please help me with this.

I want to set the adult price in such a way that if private is selected than with ATV is 100 and without ATV is 10

but if shared is selected than with ATV is 50 and without ATV is 5

for children, if private is selected then with ATV is 50 and without ATV is 5
but if shared is selected then with ATV is 25 and without 3

function calculateTotal() {
        const privateAdultPrice = 0;
        const sharedAdultPrice = 0;
        const privateChildrenPrice = 0;
        const sharedChildrenPrice = 0;

        const withAtvAdultPrice = 100;
        const withAtvChildrenPrice = 80;

        const noAtvPrice = 10;

        const adults = +document.querySelector('#adults').value;
        const children = +document.querySelector('#children').value;

        const isPrivate = document.getElementById('private').checked;
        const isWithAtv = document.getElementById('withatv').checked;

        const adultTripPrice = isPrivate ? privateAdultPrice : sharedAdultPrice;
        const childrenTripPrice = isPrivate ? privateChildrenPrice : sharedChildrenPrice;
        const adultVehiclePrice = isWithAtv ? withAtvAdultPrice : noAtvPrice;
        const childrenVehiclePrice = isWithAtv ? withAtvChildrenPrice : noAtvPrice;

        const adultPrice = adults * (adultTripPrice + adultVehiclePrice)
        const childrenPrice = children * (childrenTripPrice + childrenVehiclePrice)

        return adultPrice + childrenPrice;

      }
      function updateTotal() {
        const total = calculateTotal();
        console.log(total);
        document.querySelector('#totalPrice').innerHTML = total;
      }

      function increaseCount(e, el) {
        var input = el.previousElementSibling;
        var value = parseInt(input.value, 10);
        value = isNaN(value) ? 0 : value;
        value++;
        input.value = value;
        updateTotal();
      }

      function decreaseCount(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 1) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      function decreaseCount2(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 0) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      var MainImg = document.getElementById('MainImg');
      var smallimg = document.getElementsByClassName('small-img');

      smallimg[0].onclick = function () {
        MainImg.src = smallimg[0].src;
      };
      smallimg[1].onclick = function () {
        MainImg.src = smallimg[1].src;
      };
      smallimg[2].onclick = function () {
        MainImg.src = smallimg[2].src;
      };
      smallimg[3].onclick = function () {
        MainImg.src = smallimg[3].src;
      };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <!-- Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <style>
      .small-img-group {
        display: flex;
        justify-content: space-between;
      }

      .small-img-col {
        flex-basis: 24%;
        cursor: pointer;
      }

      .counter1 {
        float: left;
        display: flex;
        justify-content: space-between;
        overflow-x: hidden;
        overflow-y: hidden;
      }

      .counter2 {
        float: left;
        display: flex;
        justify-content: space-between;
        overflow-x: hidden;
        overflow-y: hidden;
        padding-left: 15px;
      }

      .up,
      .down {
        display: inline-block;
        color: rgb(0, 0, 0);
        font-size: 20px;
        margin: 1px 1px;
        cursor: pointer;
        width: 15px;
        line-height: 14px;
        height: 16px;
        text-align: center;
        font-weight: bold;
        border: 1px solid #000;
        user-select: none;
      }

      .up:hover,
      .down:hover {
        color: #fd0b3f;
        text-align: center;
      }

      .adults {
        padding-right: 5px;
      }

      .children {
        padding-right: 5px;
      }

      input {
        appearance: none;
        height: 21px;
        text-align: center;
        width: 42px;
        line-height: 24px;
        font-size: 15px;
        border-radius: 5px;
      }

      .container {
        display: flex;
        width: 2000px
      }

      input[type='radio'] {
        display: none;
      }

      label[for='private'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
        margin-right: 10px;
      }

      label[for='shared'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
      }
      label[for='withatv'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
        margin-right: 10px;
      }

      label[for='withoutatv'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
      }

      input[type='radio']:checked + label {
        background-color: orangered;
        color: white;
      }

      input[type='radio']:checked + label:before {
        height: 16px;
        width: 16px;
        border: 10px solid white;
        background-color: orangered;
      }
    </style>
  </head>

  <body>
    <section class="container sproduct my-5 pt-5">
      <div class="row mt-5">
        <div class="col-lg-5 col-md-12 col-12">
          <img
            class="img-fluid w-100 pb-1"
            src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
            alt=""
            id="MainImg"
            width="450"
          />

          <div class="small-img-group">
            <div class="small-img-col">
              <img
                src="https://media.tacdn.com/media/attractions-splice-spp-674x446/09/99/99/87.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
          </div>
        </div>
        <div class="col-lg-6 col-md-12 col-12">
          <h6>Home / Morning Safari</h6>
          <h3>Morning Safari</h3>
          <h2><label> Total:</label><label id="totalPrice"class="total Price"></label></h2>
          <div class="counter1">
            <label class="Adults">Adults</label>
            <div class="down" onclick="decreaseCount(event, this)">-</div>
            <input id="adults" type="text" value="1" readonly />
            <div class="up" onclick="increaseCount(event, this)">+</div>
          </div>
          <div class="counter2">
            <label class="Children">Children</label>
            <div class="down" onclick="decreaseCount2(event, this)">-</div>
            <input id="children" type="text" value="0" readonly />
            <div class="up" onclick="increaseCount(event, this)">+</div>
          </div>
          <div class="container" style="padding-left: 0; padding-top: 5px">
            <div>
              <input
                type="radio"
                name="occupancy"
                id="private"
                checked="checked"
                onclick="updateTotal()"
              />
              <label for="private">Private</label>
              <input
                type="radio"
                name="occupancy"
                id="shared"
                onclick="updateTotal()"
              />
              <label for="shared">Shared</label>
            </div>
            <div>
              <input
                type="radio"
                name="atv"
                id="withatv"
                checked="checked"
                onclick="updateTotal()"
              />
              <label for="withatv">With ATV</label>
              <input
                type="radio"
                name="atv"
                id="withoutatv"
                onclick="updateTotal()"
              />
              <label for="withoutatv">Without ATV</label>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
      crossorigin="anonymous"
    ></script>
    <script>

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

hi
I tried but can't get it after this so please help me with this.

I want to set the adult price in such a way that if private is selected then with ATV is 100 and without ATV is 10

but if shared is selected than with ATV is 50 and without ATV is 5

for children, if private is selected then with ATV is 50 and without ATV is 5
but if shared is selected then with ATV is 25 and without 3

答:
Now, your price is based on conditions.

So, the way to calculate is a little different. Translating your words, in JS code it'd be something like:

```<code>const adultTripPrice = isPrivate && isWithAtv ? 100 : isPrivate ? 10 : isWithAtv ? 50 : 5;
const childrenTripPrice = isPrivate && isWithAtv ? 50 : isPrivate ? 5 : isWithAtv ? 25 : 3;

const adultPrice = adults * (adultTripPrice)
const childrenPrice = children * (childrenTripPrice)
</code>```

It evaluates for adults

isPrivate and isWithATV then 100

isPrivate (but not isWithATV) then 10

isWithATV (but not isPrivate) then 50

Not isPrivate neither isWithATV then 5.

And then multiplies that number for the number of Adults.  (the same logic applies to Children)

The updated code would be like:

function calculateTotal() {
        const privateAdultPrice = 0;
        const sharedAdultPrice = 0;
        const privateChildrenPrice = 0;
        const sharedChildrenPrice = 0;

        const withAtvAdultPrice = 100;
        const withAtvChildrenPrice = 80;

        const noAtvPrice = 10;

        const adults = +document.querySelector('#adults').value;
        const children = +document.querySelector('#children').value;

        const isPrivate = document.getElementById('private').checked;
        const isWithAtv = document.getElementById('withatv').checked;

        const adultTripPrice = isPrivate && isWithAtv ? 100 : isPrivate ? 10 : isWithAtv ? 50 : 5;
        const childrenTripPrice = isPrivate && isWithAtv ? 50 : isPrivate ? 5 : isWithAtv ? 25 : 3;
        const adultPrice = adults * (adultTripPrice)
        const childrenPrice = children * (childrenTripPrice)

        return adultPrice + childrenPrice;

      }
      function updateTotal() {
        const total = calculateTotal();
        console.log(total);
        document.querySelector('#totalPrice').innerHTML = total;
      }

      function increaseCount(e, el) {
        var input = el.previousElementSibling;
        var value = parseInt(input.value, 10);
        value = isNaN(value) ? 0 : value;
        value++;
        input.value = value;
        updateTotal();
      }

      function decreaseCount(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 1) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      function decreaseCount2(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 0) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      var MainImg = document.getElementById('MainImg');
      var smallimg = document.getElementsByClassName('small-img');

      smallimg[0].onclick = function () {
        MainImg.src = smallimg[0].src;
      };
      smallimg[1].onclick = function () {
        MainImg.src = smallimg[1].src;
      };
      smallimg[2].onclick = function () {
        MainImg.src = smallimg[2].src;
      };
      smallimg[3].onclick = function () {
        MainImg.src = smallimg[3].src;
      };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <!-- Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <style>
      .small-img-group {
        display: flex;
        justify-content: space-between;
      }

      .small-img-col {
        flex-basis: 24%;
        cursor: pointer;
      }

      .counter1 {
        float: left;
        display: flex;
        justify-content: space-between;
        overflow-x: hidden;
        overflow-y: hidden;
      }

      .counter2 {
        float: left;
        display: flex;
        justify-content: space-between;
        overflow-x: hidden;
        overflow-y: hidden;
        padding-left: 15px;
      }

      .up,
      .down {
        display: inline-block;
        color: rgb(0, 0, 0);
        font-size: 20px;
        margin: 1px 1px;
        cursor: pointer;
        width: 15px;
        line-height: 14px;
        height: 16px;
        text-align: center;
        font-weight: bold;
        border: 1px solid #000;
        user-select: none;
      }

      .up:hover,
      .down:hover {
        color: #fd0b3f;
        text-align: center;
      }

      .adults {
        padding-right: 5px;
      }

      .children {
        padding-right: 5px;
      }

      input {
        appearance: none;
        height: 21px;
        text-align: center;
        width: 42px;
        line-height: 24px;
        font-size: 15px;
        border-radius: 5px;
      }

      .container {
        display: flex;
        width: 2000px
      }

      input[type='radio'] {
        display: none;
      }

      label[for='private'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
        margin-right: 10px;
      }

      label[for='shared'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
      }
      label[for='withatv'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
        margin-right: 10px;
      }

      label[for='withoutatv'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
      }

      input[type='radio']:checked + label {
        background-color: orangered;
        color: white;
      }

      input[type='radio']:checked + label:before {
        height: 16px;
        width: 16px;
        border: 10px solid white;
        background-color: orangered;
      }
    </style>
  </head>

  <body>
    <section class="container sproduct my-5 pt-5">
      <div class="row mt-5">
        <div class="col-lg-5 col-md-12 col-12">
          <img
            class="img-fluid w-100 pb-1"
            src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
            alt=""
            id="MainImg"
            width="450"
          />

          <div class="small-img-group">
            <div class="small-img-col">
              <img
                src="https://media.tacdn.com/media/attractions-splice-spp-674x446/09/99/99/87.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
          </div>
        </div>
        <div class="col-lg-6 col-md-12 col-12">
          <h6>Home / Morning Safari</h6>
          <h3>Morning Safari</h3>
          <h2><label> Total:</label><label id="totalPrice"class="total Price"></label></h2>
          <div class="counter1">
            <label class="Adults">Adults</label>
            <div class="down" onclick="decreaseCount(event, this)">-</div>
            <input id="adults" type="text" value="1" readonly />
            <div class="up" onclick="increaseCount(event, this)">+</div>
          </div>
          <div class="counter2">
            <label class="Children">Children</label>
            <div class="down" onclick="decreaseCount2(event, this)">-</div>
            <input id="children" type="text" value="0" readonly />
            <div class="up" onclick="increaseCount(event, this)">+</div>
          </div>
          <div class="container" style="padding-left: 0; padding-top: 5px">
            <div>
              <input
                type="radio"
                name="occupancy"
                id="private"
                checked="checked"
                onclick="updateTotal()"
              />
              <label for="private">Private</label>
              <input
                type="radio"
                name="occupancy"
                id="shared"
                onclick="updateTotal()"
              />
              <label for="shared">Shared</label>
            </div>
            <div>
              <input
                type="radio"
                name="atv"
                id="withatv"
                checked="checked"
                onclick="updateTotal()"
              />
              <label for="withatv">With ATV</label>
              <input
                type="radio"
                name="atv"
                id="withoutatv"
                onclick="updateTotal()"
              />
              <label for="withoutatv">Without ATV</label>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
      crossorigin="anonymous"
    ></script>
    <script>

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

Body:
I tried but can't get it after this so please help me with this.

I want to set the adult price in such a way that if private is selected than with ATV is 100 and without ATV is 10

but if shared is selected than with ATV is 50 and without ATV is 5

for children, if private is selected then with ATV is 50 and without ATV is 5
but if shared is selected then with ATV is 25 and without 3

function calculateTotal() {
        const privateAdultPrice = 0;
        const sharedAdultPrice = 0;
        const privateChildrenPrice = 0;
        const sharedChildrenPrice = 0;

        const withAtvAdultPrice = 100;
        const withAtvChildrenPrice = 80;

        const noAtvPrice = 10;

        const adults = +document.querySelector('#adults').value;
        const children = +document.querySelector('#children').value;

        const isPrivate = document.getElementById('private').checked;
        const isWithAtv = document.getElementById('withatv').checked;

        const adultTripPrice = isPrivate ? privateAdultPrice : sharedAdultPrice;
        const childrenTripPrice = isPrivate ? privateChildrenPrice : sharedChildrenPrice;
        const adultVehiclePrice = isWithAtv ? withAtvAdultPrice : noAtvPrice;
        const childrenVehiclePrice = isWithAtv ? withAtvChildrenPrice : noAtvPrice;

        const adultPrice = adults * (adultTripPrice + adultVehiclePrice)
        const childrenPrice = children * (childrenTripPrice + childrenVehiclePrice)

        return adultPrice + childrenPrice;

      }
      function updateTotal() {
        const total = calculateTotal();
        console.log(total);
        document.querySelector('#totalPrice').innerHTML = total;
      }

      function increaseCount(e, el) {
        var input = el.previousElementSibling;
        var value = parseInt(input.value, 10);
        value = isNaN(value) ? 0 : value;
        value++;
        input.value = value;
        updateTotal();
      }

      function decreaseCount(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 1) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      function decreaseCount2(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 0) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      var MainImg = document.getElementById('MainImg');
      var smallimg = document.getElementsByClassName('small-img');

      smallimg[0].onclick = function () {
        MainImg.src = smallimg[0].src;
      };
      smallimg[1].onclick = function () {
        MainImg.src = smallimg[1].src;
      };
      smallimg[2].onclick = function () {
        MainImg.src = smallimg[2].src;
      };
      smallimg[3].onclick = function () {
        MainImg.src = smallimg[3].src;
      };

<!DOCTYPE html>

    <title>Title</title>

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />

Home / Morning Safari

Morning Safari

 Total:

            Adults

-

            <input id="adults" type="text" value="1" readonly />

+

            Children

-

            <input id="children" type="text" value="0" readonly />

+

              <input
                type="radio"
                name="occupancy"
                id="private"
                checked="checked"
                onclick="updateTotal()"
              />
              Private
              <input
                type="radio"
                name="occupancy"
                id="shared"
                onclick="updateTotal()"
              />
              Shared

              <input
                type="radio"
                name="atv"
                id="withatv"
                checked="checked"
                onclick="updateTotal()"
              />
              With ATV
              <input
                type="radio"
                name="atv"
                id="withoutatv"
                onclick="updateTotal()"
              />
              Without ATV

hi
I tried but can't get it after this so please help me with this.

I want to set the adult price in such a way that if private is selected then with ATV is 100 and without ATV is 10

but if shared is selected than with ATV is 50 and without ATV is 5

for children, if private is selected then with ATV is 50 and without ATV is 5
but if shared is selected then with ATV is 25 and without 3

Body:
Now, your price is based on conditions.

So, the way to calculate is a little different. Translating your words, in JS code it'd be something like:

const adultTripPrice = isPrivate && isWithAtv ? 100 : isPrivate ? 10 : isWithAtv ? 50 : 5;
const childrenTripPrice = isPrivate && isWithAtv ? 50 : isPrivate ? 5 : isWithAtv ? 25 : 3;

const adultPrice = adults * (adultTripPrice)
const childrenPrice = children * (childrenTripPrice)

It evaluates for adults

isPrivate and isWithATV then 100

isPrivate (but not isWithATV) then 10

isWithATV (but not isPrivate) then 50

Not isPrivate neither isWithATV then 5.

And then multiplies that number for the number of Adults.  (the same logic applies to Children)

The updated code would be like:

function calculateTotal() {
        const privateAdultPrice = 0;
        const sharedAdultPrice = 0;
        const privateChildrenPrice = 0;
        const sharedChildrenPrice = 0;

        const withAtvAdultPrice = 100;
        const withAtvChildrenPrice = 80;

        const noAtvPrice = 10;

        const adults = +document.querySelector('#adults').value;
        const children = +document.querySelector('#children').value;

        const isPrivate = document.getElementById('private').checked;
        const isWithAtv = document.getElementById('withatv').checked;

        const adultTripPrice = isPrivate && isWithAtv ? 100 : isPrivate ? 10 : isWithAtv ? 50 : 5;
        const childrenTripPrice = isPrivate && isWithAtv ? 50 : isPrivate ? 5 : isWithAtv ? 25 : 3;
        const adultPrice = adults * (adultTripPrice)
        const childrenPrice = children * (childrenTripPrice)

        return adultPrice + childrenPrice;

      }
      function updateTotal() {
        const total = calculateTotal();
        console.log(total);
        document.querySelector('#totalPrice').innerHTML = total;
      }

      function increaseCount(e, el) {
        var input = el.previousElementSibling;
        var value = parseInt(input.value, 10);
        value = isNaN(value) ? 0 : value;
        value++;
        input.value = value;
        updateTotal();
      }

      function decreaseCount(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 1) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      function decreaseCount2(e, el) {
        var input = el.nextElementSibling;
        var value = parseInt(input.value, 10);
        if (value > 0) {
          value = isNaN(value) ? 0 : value;
          value--;
          input.value = value;
        }
        updateTotal();
      }

      var MainImg = document.getElementById('MainImg');
      var smallimg = document.getElementsByClassName('small-img');

      smallimg[0].onclick = function () {
        MainImg.src = smallimg[0].src;
      };
      smallimg[1].onclick = function () {
        MainImg.src = smallimg[1].src;
      };
      smallimg[2].onclick = function () {
        MainImg.src = smallimg[2].src;
      };
      smallimg[3].onclick = function () {
        MainImg.src = smallimg[3].src;
      };

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <!-- Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
    <style>
      .small-img-group {
        display: flex;
        justify-content: space-between;
      }

      .small-img-col {
        flex-basis: 24%;
        cursor: pointer;
      }

      .counter1 {
        float: left;
        display: flex;
        justify-content: space-between;
        overflow-x: hidden;
        overflow-y: hidden;
      }

      .counter2 {
        float: left;
        display: flex;
        justify-content: space-between;
        overflow-x: hidden;
        overflow-y: hidden;
        padding-left: 15px;
      }

      .up,
      .down {
        display: inline-block;
        color: rgb(0, 0, 0);
        font-size: 20px;
        margin: 1px 1px;
        cursor: pointer;
        width: 15px;
        line-height: 14px;
        height: 16px;
        text-align: center;
        font-weight: bold;
        border: 1px solid #000;
        user-select: none;
      }

      .up:hover,
      .down:hover {
        color: #fd0b3f;
        text-align: center;
      }

      .adults {
        padding-right: 5px;
      }

      .children {
        padding-right: 5px;
      }

      input {
        appearance: none;
        height: 21px;
        text-align: center;
        width: 42px;
        line-height: 24px;
        font-size: 15px;
        border-radius: 5px;
      }

      .container {
        display: flex;
        width: 2000px
      }

      input[type='radio'] {
        display: none;
      }

      label[for='private'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
        margin-right: 10px;
      }

      label[for='shared'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
      }
      label[for='withatv'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
        margin-right: 10px;
      }

      label[for='withoutatv'] {
        position: relative;
        color: orangered;
        font-size: 20px;
        border: 2px solid orangered;
        border-radius: 5px;
        align-items: left;
        display: flex;
        cursor: pointer;
      }

      input[type='radio']:checked + label {
        background-color: orangered;
        color: white;
      }

      input[type='radio']:checked + label:before {
        height: 16px;
        width: 16px;
        border: 10px solid white;
        background-color: orangered;
      }
    </style>
  </head>

  <body>
    <section class="container sproduct my-5 pt-5">
      <div class="row mt-5">
        <div class="col-lg-5 col-md-12 col-12">
          <img
            class="img-fluid w-100 pb-1"
            src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
            alt=""
            id="MainImg"
            width="450"
          />

          <div class="small-img-group">
            <div class="small-img-col">
              <img
                src="https://media.tacdn.com/media/attractions-splice-spp-674x446/09/99/99/87.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
            <div class="small-img-col">
              <img
                src="https://skylandtourism.com/wp-content/uploads/2018/03/Morning-Safari.jpg"
                width="100%"
                class="small-img"
                alt=""
              />
            </div>
          </div>
        </div>
        <div class="col-lg-6 col-md-12 col-12">
          <h6>Home / Morning Safari</h6>
          <h3>Morning Safari</h3>
          <h2><label> Total:</label><label id="totalPrice"class="total Price"></label></h2>
          <div class="counter1">
            <label class="Adults">Adults</label>
            <div class="down" onclick="decreaseCount(event, this)">-</div>
            <input id="adults" type="text" value="1" readonly />
            <div class="up" onclick="increaseCount(event, this)">+</div>
          </div>
          <div class="counter2">
            <label class="Children">Children</label>
            <div class="down" onclick="decreaseCount2(event, this)">-</div>
            <input id="children" type="text" value="0" readonly />
            <div class="up" onclick="increaseCount(event, this)">+</div>
          </div>
          <div class="container" style="padding-left: 0; padding-top: 5px">
            <div>
              <input
                type="radio"
                name="occupancy"
                id="private"
                checked="checked"
                onclick="updateTotal()"
              />
              <label for="private">Private</label>
              <input
                type="radio"
                name="occupancy"
                id="shared"
                onclick="updateTotal()"
              />
              <label for="shared">Shared</label>
            </div>
            <div>
              <input
                type="radio"
                name="atv"
                id="withatv"
                checked="checked"
                onclick="updateTotal()"
              />
              <label for="withatv">With ATV</label>
              <input
                type="radio"
                name="atv"
                id="withoutatv"
                onclick="updateTotal()"
              />
              <label for="withoutatv">Without ATV</label>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
      crossorigin="anonymous"
    ></script>
    <script>

    </script>
  </body>
</html>


来源: stackexchange

问:
error: 'Flutter/Flutter.h' file not found when flutter run on iOS
I don't know why but I can't build or run the App in my new Macbook, I run the same folder on another Mac or my windows computer and runs perfectly.
here when I run flutter clean, I have to run pub get to solve the issues, Is that normal?

If I create a new project, I can run flutter run normally, so I think that maybe there
I think it may be related to plugins.

Do you know how can I solve this? Thanks

```<code>Flutter Doctor
[✓] Flutter (Channel master, 1.24.0-8.0.pre.343, on macOS 11.0.1 20B29 darwin-x64, locale es-419)
    • Flutter version 1.24.0-8.0.pre.343 at /Users/leo/tools/flutter
    • Framework revision cf6c33e58a (2 days ago), 2020-11-21 14:04:01 -0800
    • Engine revision 23a8e027db
    • Dart version 2.12.0 (build 2.12.0-62.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/leo/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.9.3

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] Connected device (2 available)
    • sdk gphone x86 arm (mobile) • emulator-5554                        • android-x86 • Android 11 (API
      30) (emulator)
    • iPhone 12 Pro Max (mobile)  • F768139D-7B87-4D9E-93B8-14C7D63786B0 • ios         •
      com.apple.CoreSimulator.SimRuntime.iOS-14-2 (simulator)

• No issues found!

Launching lib/main.dart on iPhone 12 Pro Max in debug mode...
Running Xcode build...
Xcode build done.                                           11.4s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    <module-includes>:1:9: note: in file included from <module-includes>:1:
    #import "Headers/vibration-umbrella.h"
            ^
    /Users/leo/Apps/previate_esta/ios/Pods/Target Support Files/vibration/vibration-umbrella.h:13:9: note:
    in file included from /Users/leo/Apps/previate_esta/ios/Pods/Target Support
    Files/vibration/vibration-umbrella.h:13:
    #import "VibrationPlugin.h"
            ^
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/vibration-1.4.0/ios/Classes/VibrationPlugin.h:1:9: error:
    'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^
    <unknown>:0: error: could not build Objective-C module 'vibration'
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/url_launcher-5.5.3/ios/Classes/FLTURLLauncherPlugin.m:7:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/url_launcher-5.5.3/ios/Classes/FLTURLLauncherPlugin.h:5:9
    : fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/shared_preferences-0.5.10/ios/Classes/FLTSharedPreference
    sPlugin.m:5:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/shared_preferences-0.5.10/ios/Classes/FLTSharedPreference
    sPlugin.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/share-0.6.5/ios/Classes/FLTSharePlugin.m:5:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/share-0.6.5/ios/Classes/FLTSharePlugin.h:5:9: fatal
    error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/sensors-0.4.2+4/ios/Classes/FLTSensorsPlugin.m:5:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/sensors-0.4.2+4/ios/Classes/FLTSensorsPlugin.h:5:9: fatal
    error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description

Could not build the application for the simulator.
Error launching application on iPhone 12 Pro Max.
</code>```

答: If you only encounter this problem when running "flutter build ipa", in XCode make sure your Deployment Info under Runner and Pods matches the 'platform' in ios/Podfile.

ContentLicense: CC BY-SA 4.0

Body:
I don't know why but I can't build or run the App in my new Macbook, I run the same folder on another Mac or my windows computer and runs perfectly.
here when I run flutter clean, I have to run pub get to solve the issues, Is that normal?

If I create a new project, I can run flutter run normally, so I think that maybe there
I think it may be related to plugins.

Do you know how can I solve this? Thanks

Flutter Doctor
[✓] Flutter (Channel master, 1.24.0-8.0.pre.343, on macOS 11.0.1 20B29 darwin-x64, locale es-419)
    • Flutter version 1.24.0-8.0.pre.343 at /Users/leo/tools/flutter
    • Framework revision cf6c33e58a (2 days ago), 2020-11-21 14:04:01 -0800
    • Engine revision 23a8e027db
    • Dart version 2.12.0 (build 2.12.0-62.0.dev)

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/leo/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.9.3

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] Connected device (2 available)
    • sdk gphone x86 arm (mobile) • emulator-5554                        • android-x86 • Android 11 (API
      30) (emulator)
    • iPhone 12 Pro Max (mobile)  • F768139D-7B87-4D9E-93B8-14C7D63786B0 • ios         •
      com.apple.CoreSimulator.SimRuntime.iOS-14-2 (simulator)

• No issues found!

Launching lib/main.dart on iPhone 12 Pro Max in debug mode...
Running Xcode build...
Xcode build done.                                           11.4s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **

Xcode's output:
↳
    <module-includes>:1:9: note: in file included from <module-includes>:1:
    #import "Headers/vibration-umbrella.h"
            ^
    /Users/leo/Apps/previate_esta/ios/Pods/Target Support Files/vibration/vibration-umbrella.h:13:9: note:
    in file included from /Users/leo/Apps/previate_esta/ios/Pods/Target Support
    Files/vibration/vibration-umbrella.h:13:
    #import "VibrationPlugin.h"
            ^
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/vibration-1.4.0/ios/Classes/VibrationPlugin.h:1:9: error:
    'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^
    <unknown>:0: error: could not build Objective-C module 'vibration'
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/url_launcher-5.5.3/ios/Classes/FLTURLLauncherPlugin.m:7:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/url_launcher-5.5.3/ios/Classes/FLTURLLauncherPlugin.h:5:9
    : fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/shared_preferences-0.5.10/ios/Classes/FLTSharedPreference
    sPlugin.m:5:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/shared_preferences-0.5.10/ios/Classes/FLTSharedPreference
    sPlugin.h:5:9: fatal error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/share-0.6.5/ios/Classes/FLTSharePlugin.m:5:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/share-0.6.5/ios/Classes/FLTSharePlugin.h:5:9: fatal
    error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    In file included from
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/sensors-0.4.2+4/ios/Classes/FLTSensorsPlugin.m:5:
    /Users/leo/.pub-cache/hosted/pub.dartlang.org/sensors-0.4.2+4/ios/Classes/FLTSensorsPlugin.h:5:9: fatal
    error: 'Flutter/Flutter.h' file not found
    #import <Flutter/Flutter.h>
            ^~~~~~~~~~~~~~~~~~~
    1 error generated.
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description

Could not build the application for the simulator.
Error launching application on iPhone 12 Pro Max.


问:
Unable to return variable from one function and use it in another function
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.</p>
```<code>import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()
</code>```

答:
You might the following rewrite of your code to be interesting.

```<code>import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']
COIN_LIST = ['Penny', 'Nickel', 'Dime', 'Quarter']
VALUE = {'Penny':1,'Nickel':5,'Dime':10,'Quarter':25}

def main():
    coin_tokens = choose_coins()
    add_coins(coin_tokens)

#Choose the number and type of coins
def choose_coins():

    #List of coins to pick from
    global COIN_LIST

    #Choose the number of coins
    num_coins = random.randint(2,4)
    coin_tokens = random.choices(COIN_LIST,k=num_coins)

    print(coin_tokens)
    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    print(coin_tokens)
    global VALUE
    coin_total = sum(VALUE[coin] for coin in coin_tokens)

    print(coin_total)

main()

#Starts the Program
if __name__ == "__main__":
    main()
</code>```

You could further shorten the code to the following.

```<code>import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']
VALUE = {'Penny':1,'Nickel':5,'Dime':10,'Quarter':25}

def main():
    coin_tokens = choose_coins()
    print(coin_tokens)
    total = add_coins(coin_tokens)
    print(total)

#Choose the number and type of coins
def choose_coins():
    return random.choices(list(VALUE),k=random.randint(2,4))

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):
    return sum(VALUE[coin] for coin in coin_tokens)
</code>```

Body:
I am attempting to return a list of coins from one function to another, then split it and sum the results. I'm trying to return one list from a function, then use it in the next. I put the list in as a positional argument in the main function, but it says it isn't defined. I have a return statement in the function, so I'm not sure what's wrong.

import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']

#Controls all other functions
def main():

    choose_coins()
    coin_tokens = choose_coins()

#Choose the number and type of coins
def choose_coins():

    coin_tokens = []

    #List of coins to pick from
    coin_list = ['Penny', 'Nickel', 'Dime', 'Quarter']

    #Choose the number of coins
    num_coins = random.randint(2,4)

    #Add chosen coins to a list
    for i in range(num_coins):

        coins_to_be_counted = random.choice(coin_list)

        coin_tokens.append(coins_to_be_counted)

    print(coin_tokens)

    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    #Iterate through coin_tokens list
    for i in coin_tokens:

        if token == 'Penny':
            coin_total += 1

        elif token == 'Nickel':
            coin_total += 5

        elif token == 'Dime':
            coin_total += 10

        elif token == 'Quarter':
            coin_total += 25

        coin_total = 0

    print(coin_total)

#Starts the Program
if __name__ == "__main__":
    main()

Body:
You might the following rewrite of your code to be interesting.

import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']
COIN_LIST = ['Penny', 'Nickel', 'Dime', 'Quarter']
VALUE = {'Penny':1,'Nickel':5,'Dime':10,'Quarter':25}

def main():
    coin_tokens = choose_coins()
    add_coins(coin_tokens)

#Choose the number and type of coins
def choose_coins():

    #List of coins to pick from
    global COIN_LIST

    #Choose the number of coins
    num_coins = random.randint(2,4)
    coin_tokens = random.choices(COIN_LIST,k=num_coins)

    print(coin_tokens)
    return coin_tokens

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):

    print(coin_tokens)
    global VALUE
    coin_total = sum(VALUE[coin] for coin in coin_tokens)

    print(coin_total)

main()

#Starts the Program
if __name__ == "__main__":
    main()

You could further shorten the code to the following.

import random
import time
import math

CORRECT_LIST = ['Great job!', 'You did it!', 'Right answer.', 'Awesome!']
INCORRECT_LIST = ['Not quite.', 'Try again.', 'Keep trying.', 'Check your math.']
VALUE = {'Penny':1,'Nickel':5,'Dime':10,'Quarter':25}

def main():
    coin_tokens = choose_coins()
    print(coin_tokens)
    total = add_coins(coin_tokens)
    print(total)

#Choose the number and type of coins
def choose_coins():
    return random.choices(list(VALUE),k=random.randint(2,4))

#Add coins using tokens from coin_tokens list
def add_coins(coin_tokens):
    return sum(VALUE[coin] for coin in coin_tokens)


问:
remove duplicate entries in two different JSON file
I have extensive data in many JSON files, but the problem is that they are many duplicate entries and it make lot's of trouble to find them is that any way to remove them with one click

How can I remove duplicate entries from two different JSON files using python?

First File

```<code>[
    {
        "client_id": "1343314236",
        "username": "Nandhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]

</code>```

Second File

```<code>
[
    {
        "client_id": "1343314236",
        "username": "Na1dhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]

</code>```

答:
I created a script to solve your issue. In one folder create a .py file with the following:

```<code>import os
import json

files=os.listdir()
for file in files:
    with open(file, "r") as json_file:
        if os.path.basename(__file__) != file:
            users = json.load(json_file)
            unique_users=  list({ user['client_id'] : user for user in users }.values())
            json_with_no_repetition = open(f"{file}_wo_duplicates.json", "w")
            json_with_no_repetition.write(json.dumps(unique_users, indent=4))
            json_with_no_repetition.close()
</code>```

Then, put all the files within the folder and run the script.

I should recall that you should also try it by yourself and only ask questions when you are stuck in a specific moment.

Body:
I have extensive data in many JSON files, but the problem is that they are many duplicate entries and it make lot's of trouble to find them is that any way to remove them with one click

How can I remove duplicate entries from two different JSON files using python?

First File

[
    {
        "client_id": "1343314236",
        "username": "Nandhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]

Second File

[
    {
        "client_id": "1343314236",
        "username": "Na1dhu_y_z",
        "name": "nadhu Nandhan"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    },
    {
        "client_id": "1725943170",
        "username": "Nodsfne",
        "name": "Konnengal Z"
    }
]

Body:
I created a script to solve your issue. In one folder create a .py file with the following:

import os
import json

files=os.listdir()
for file in files:
    with open(file, "r") as json_file:
        if os.path.basename(__file__) != file:
            users = json.load(json_file)
            unique_users=  list({ user['client_id'] : user for user in users }.values())
            json_with_no_repetition = open(f"{file}_wo_duplicates.json", "w")
            json_with_no_repetition.write(json.dumps(unique_users, indent=4))
            json_with_no_repetition.close()

Then, put all the files within the folder and run the script.

I should recall that you should also try it by yourself and only ask questions when you are stuck in a specific moment.


问:
Call Stored Procedures from Entity Framework return value from temp tables
I am using ASP.NET MVC 4.5 and EF. I imported some stored procedures into my ADO.NET Entity Data Model. I have my .edmx and XX.tt with my StoreProcedure_Result.cs.

But there is a stored procedure that do not have a _result.cs file

This is because the stored procedure returns

```<code> select from #TempTable
</code>```

When I want to import that function to create a complex type, it sees that the function do not return any value..

I thinks that return value from temp tables it is not allowed.

Any ideas how can I solve it?

Thanks

答:
Based on my personal experience, If you use #temp or ##temp table in stored procedure and calling that procedure from MVC Entity framework (.edmx) then it will not work & it will return -1 always.

There can be 2 solutions:

Modify the stored procedure, replace the #temp or ##temp table with some other concrete logic. And then update .edmx then try again to call the procedure.

Or the simple one solution would be call that particular stored procedure using traditional ADO.NET (using the SQLConnection/SQLCommand objects ) and get the returning table value in DataSet or DataTable.

Thanks

ContentLicense: CC BY-SA 3.0

Body:
I am using ASP.NET MVC 4.5 and EF. I imported some stored procedures into my ADO.NET Entity Data Model. I have my .edmx and XX.tt with my StoreProcedure_Result.cs.

But there is a stored procedure that do not have a _result.cs file

This is because the stored procedure returns

 select from #TempTable

When I want to import that function to create a complex type, it sees that the function do not return any value..

I thinks that return value from temp tables it is not allowed.

Any ideas how can I solve it?

Thanks


问:
Python / Websockets : Opening file in socket callback reset the connection
I'm making a website with a python server. I'm using the websockets library.

I would like to add log files to monitor my site activity during it is running.

But if I open a file in the socket callback, the socket connection is always reset on the opening.

```<code>import asyncio
import websockets

async def handler(websocket):
    while True:
        try:
            testFile = open("log", "w") # This line reset socket connection
            testFile.write('anything')
            testFile.close()
            message = await websocket.recv()
            await websocket.send('{"cmd" : "ERROR", "msg" : "This is a test"}')
        except websockets.ConnectionClosedOK:
            break

async def main():
    async with websockets.serve(handler, "", 50000):
        await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())
</code>```

EDIT : If I remove the try except block, I got the following error :

```<code>connection handler failed
Traceback (most recent call last):
  File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 231, in handler
    await self.ws_handler(self)
  File "server2.py", line 52, in handler
    message = await websocket.recv()
  File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 552, in recv
    await self.ensure_open()
  File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 929, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: received 1001 (going away); then sent 1001 (going away)
</code>```

(I have also tried with another socket library (simple_websocket_server) and the issue was the same)

Is there a way to avoid this behavior ? If not, Is there another way to get logs during server execution ?

答: I understood my issue. The weird behavior comes from Windows WSL. I tested the same code on a real Linux and there is no problem. For now, I haven't any solution on Windows WSL.</p>

Body:
I'm making a website with a python server. I'm using the websockets library.

I would like to add log files to monitor my site activity during it is running.

But if I open a file in the socket callback, the socket connection is always reset on the opening.

import asyncio
import websockets

async def handler(websocket):
    while True:
        try:
            testFile = open("log", "w") # This line reset socket connection
            testFile.write('anything')
            testFile.close()
            message = await websocket.recv()
            await websocket.send('{"cmd" : "ERROR", "msg" : "This is a test"}')
        except websockets.ConnectionClosedOK:
            break

async def main():
    async with websockets.serve(handler, "", 50000):
        await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())

EDIT : If I remove the try except block, I got the following error :

connection handler failed
Traceback (most recent call last):
  File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 231, in handler
    await self.ws_handler(self)
  File "server2.py", line 52, in handler
    message = await websocket.recv()
  File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 552, in recv
    await self.ensure_open()
  File "\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\protocol.py", line 929, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedOK: received 1001 (going away); then sent 1001 (going away)

(I have also tried with another socket library (simple_websocket_server) and the issue was the same)

Is there a way to avoid this behavior ? If not, Is there another way to get logs during server execution ?


问:
How to filter a string list containing specific characters in python
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

```<code>letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]
</code>```

Does anybody have an idea of how to do that?

Thank you in advance!

答:
You can use the filter() method in python</p>
```<code>letters = ['R', 'E', 'T', 'O', 'P', 'A']
my_lis = ['jake','jill','tim','vim']

def foo(x):
  for words in x:
    for letter in words:
        print(letter)
        if letter in letters:
            return True
        else:
            return False

final = filter(foo,my_lis)

for x in final:
  print(x)
</code>```

Body:
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]

Does anybody have an idea of how to do that?

Thank you in advance!

Body:
You can use the filter() method in python

letters = ['R', 'E', 'T', 'O', 'P', 'A']
my_lis = ['jake','jill','tim','vim']

def foo(x):
  for words in x:
    for letter in words:
        print(letter)
        if letter in letters:
            return True
        else:
            return False

final = filter(foo,my_lis)

for x in final:
  print(x)


问:
R : y[x] & x[y] when x,y vectors
Silly question but for real i cant undestand what is happening here (Screenshot) ,especially in x[y]. In y[x] i undestand that he is getting the similar objects for x & y. But in x[y] he is getting objects that y is not having

答:
When you ask x[y] (respectively y[x]), you are actually asking the "yth" (resp. "xth") values of x (resp. y).

For instance :

> x <- c(1, 4)
> y <- c(10, 20, 35, 70)
> y[x]
[1] 10 70
```
<p><code>y[x]</code> returns values of <code>y</code> at positions 1 and 4.</p>
<pre class="lang-r prettyprint-override"><code>> y[c(x, 10)]
[1] 10 70 NA
</code>```

y[c(x, 10)] returns values of y at positions 1 and 4 and 10. The 10th value is missing, so it returns NA.

Title: R : y[x] & x[y] when x,y vectors

Body:
When you ask x[y] (respectively y[x]), you are actually asking the "yth" (resp. "xth") values of x (resp. y).

For instance :

> x <- c(1, 4)
> y <- c(10, 20, 35, 70)
> y[x]
[1] 10 70

y[x] returns values of y at positions 1 and 4.

> y[c(x, 10)]
[1] 10 70 NA

y[c(x, 10)] returns values of y at positions 1 and 4 and 10. The 10th value is missing, so it returns NA.


问:
How to set value to input field in react
How to set the value to the input field in react. Data is fetching from firebase.
I was trying to fetch data from the firebase and then data is populated to the input field. But data is sometimes set to input field sometimes not.</p>

答:
You have to fill your data into a local state using useState. Here is the general idea. Can't go into more details without  code example from your side.

For example:

```<code>const [value, setValue] = useState('')
</code>```

Then in your useEffect fetching the data:

```<code>useEffect(() => {
   const data = fetch('gettingdata') // replace by the way you get your data
   setValue(data)
 }, []}
</code>```

Then in your input:

```<code><input value={value} onChange={manageYourValueChange} />
</code>```

Body:
You have to fill your data into a local state using useState. Here is the general idea. Can't go into more details without  code example from your side.

For example:

const [value, setValue] = useState('')

Then in your useEffect fetching the data:

useEffect(() => {
   const data = fetch('gettingdata') // replace by the way you get your data
   setValue(data)
 }, []}

Then in your input:

<input value={value} onChange={manageYourValueChange} />


问:
Migration from Android v1 to V2
Hello everyone I am quite new to Flutter and I got stuck with this problem.

My app apparently is V2 but still, Android studio says that the app has to be migrated.

I did the steps that they suggested but still got the same result
Can anyone suggest what I am doing wrong ?
This is the link with what I have to do:
https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects

this is what I modified.

AndroidManifest.xml

```<code>    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ipill">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.androidtutorialpoint.mymapsappsdirection.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <application
        android:name="${ipill}"
        android:label="ipill"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"

                />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <!-- Specify that the launch screen should continue being displayed -->
            <!-- until Flutter renders its first frame. -->

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <meta-data
            android:name="com.google.android.gms.wallet.api.enabled"
            android:value="true" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value=""/>
    </application>

</manifest>
</code>```

And the file MainActivity.kt contains the following

```<code> package com.example.ipill

import io.flutter.embedding.android.FlutterActivity

class MainActivity: FlutterActivity() {

}
</code>```

I tried also to use the flutter install --ignore-deprecation flag but they says that it is not working.

Any help because I got lost and I really need to make the app work, I found one similar question and I applied what they suggested but it did not work.

This is the log I get

```<code>    FAILURE: Build failed with an exception.
    D:\7_GitHub\Piller2.0\android\app\src\main\AndroidManifest.xml:18:9-32 Error:
    Attribute application@name at AndroidManifest.xml:18:9-32 requires a placeholder substitution but no value for <ipill> is provided.
D:\7_GitHub\Piller2.0\android\app\src\debug\AndroidManifest.xml Error:
    Validation failed, exiting
* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 12s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

答:
I was able to solve this by setting android:name to

android:name="${applicationName}" in android/app/src/main/AndroidManifest.xml

Apparently, even though you were already upgraded to V2 embedding, Flutter 2.10 has stricter checks than previous versions.

Title: Migration from Android v1 to V2

Body:
Hello everyone I am quite new to Flutter and I got stuck with this problem.

My app apparently is V2 but still, Android studio says that the app has to be migrated.

I did the steps that they suggested but still got the same result
Can anyone suggest what I am doing wrong ?
This is the link with what I have to do:
https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects

this is what I modified.

AndroidManifest.xml

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ipill">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.androidtutorialpoint.mymapsappsdirection.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <application
        android:name="${ipill}"
        android:label="ipill"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">

            <meta-data
                android:name="io.flutter.embedding.android.NormalTheme"
                android:resource="@style/NormalTheme"

                />

            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
        <meta-data
            android:name="com.google.android.gms.wallet.api.enabled"
            android:value="true" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value=""/>
    </application>

</manifest>

And the file MainActivity.kt contains the following

 package com.example.ipill

import io.flutter.embedding.android.FlutterActivity

class MainActivity: FlutterActivity() {

}

I tried also to use the flutter install --ignore-deprecation flag but they says that it is not working.

Any help because I got lost and I really need to make the app work, I found one similar question and I applied what they suggested but it did not work.

This is the log I get

    FAILURE: Build failed with an exception.
    D:\7_GitHub\Piller2.0\android\app\src\main\AndroidManifest.xml:18:9-32 Error:
    Attribute application@name at AndroidManifest.xml:18:9-32 requires a placeholder substitution but no value for <ipill> is provided.
D:\7_GitHub\Piller2.0\android\app\src\debug\AndroidManifest.xml Error:
    Validation failed, exiting
* What went wrong:
Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed with multiple errors, see logs

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 12s
Exception: Gradle task assembleDebug failed with exit code 1


问:
Query JOIN or not? (optimization)
i was wondering if to use 2 tables is better then using 1 single table .

Scenario:

i have a simple user table and a simple user_details table. i can JOIN tables and select both records.

But i was wondering if to merge 2 table into 1 single table.

what if i have 2milions users records in both tables?

in terms of speed and exec time is better to have a single table when selecting records?

答:
Joins themselves are not inherently bad; RDBMS are designed to perform joins very efficiently—even with millions or hundreds of millions of records. Normalize first before you start to de-normalize, especially if you're new to DB design. You may ultimately end up incurring more overhead maintaining a de-normalized database than you would to use the appropriate joins.

As to your specific question, it's very difficult to advise because we don't really know what's in the tables. I'll throw out some scenarios, and if one matches yours, then great, otherwise, please give us more details.

If there is, and will always be a one-to-one relationship between user and user_details, then user details likely contains attributes of the same entity and you can consider combining them.

If the relationship is 1-to-1 and the user_details contains LOTS of data for each user that you don't routinely need when querying, it may be faster to keep that in a separate table. I've seen this often as an optimization to reduce the cost of table scans.

If the relationship is 1-to-many, I'd strongly advice against combining them, you'll soon wish you hadn't (as will those who come after you)

If the schema of user_details changes, I've seen this too where there is a core table and an additional attribute table with variable schema. If this is the case, proceed with caution.

Title: Query JOIN or not? (optimization)


问:
Is there a client side function to save record in Suitescript?
I am trying to use the saveRecord entry point of a client side script to redirect to another page.

However, in order to do that, my understanding is that I need to save and submit the record first.

Is there a way to do this (basically replicate what happens when a user presses Netsuite's native 'save' button on a record) using a client side script (i.e. without the user clicking that button)?

I have tried record.submitfields though this does not trigger the function under saveRecord.

答:
What I suggest is that you trigger a save -- and the answer above is fine for that.

However, for the key requirement of

[after save] to redirect to another page.

this is tricker because the save it going to reload the page and thus it will refresh a bunch of things.

a) Are you okay opening a new tab? if so then open a new tab with window.open(yourUrl).

b) Does your new destination require information that might have changed on the original record?  if so then you'll need to wait until the save completes.

The following will help with a=no and / or b=yes.

Before you trigger the save you drop a piece of information with the browser. And you have a piece of client script that will look for that piece of info so that when the page is reloaded you can use that information to load a new page.

The A algorithm will be:

leave a flag with instruction to redirect

trigger save

on load look for a redirect flag

if it is not there then break from this.

if it is there then do B.

The B algorithm will be:

copy the flag into a variable

remove the flag if it is there.

redirect based on the variable

You can use localstorage of the browser as the place to store this flag. You could also use sessionstorage which will expire when session is over.

for a pure NetSuite solution you could check with a suitelet that stores a session variable (N/runtime). A bit more work.

NB: Just remember to remove your flag or at least consider an expiration for that state (so do not follow it if it is "too old").


问:
How to replace NaNs by average of preceding and succeeding values in pandas DataFrame?
If I have some missing values and I would like to replace all NaN with average of preceding and succeeding values, how can I do that ?.

I know I can use pandas.DataFrame.fillna with method='ffill' or method='bfill' options to replace the NaN values by preceding or succeeding values, however I would like to apply the average of those values on the dataframe instead of  iterating over rows and columns.

答:
Maybe late but I just had the same question and the (unique) answer in this page did not satisfy my expectations. That's why I am answering now.
Your post states that you want to replace the NaNs with averages however, the interpolation is not a correct answer for me because it fills the empty cells with a linear equation. If you want to fill it with the averages of the preceding and succeeding rows. This code helped me:

dfb = df.fillna(method='bfill')
dff = df.fillna(method='ffill')
dfmeans = (dfb+dff)/2
dfmeans
```
<p>For the datafrme of the example above, the result looks like</p>
```    A   B
0   1.0 0.250
1   2.1 2.125
2   3.4 2.125
3   4.7 4.000
4   5.6 12.200
5   6.8 14.400
```

Where you can see, at index 2 of the column A they both produce 3.4 because there the interpolation is (2.1 + 4.7)/2 but in column B the values differ.

For a one-line script and it's application to time series, you can see this post: Average between values with unevenly distributed time in Pandas DataFrame

Body:
Maybe late but I just had the same question and the (unique) answer in this page did not satisfy my expectations. That's why I am answering now.
Your post states that you want to replace the NaNs with averages however, the interpolation is not a correct answer for me because it fills the empty cells with a linear equation. If you want to fill it with the averages of the preceding and succeeding rows. This code helped me:

dfb = df.fillna(method='bfill')
dff = df.fillna(method='ffill')
dfmeans = (dfb+dff)/2
dfmeans

For the datafrme of the example above, the result looks like

    A   B
0   1.0 0.250
1   2.1 2.125
2   3.4 2.125
3   4.7 4.000
4   5.6 12.200
5   6.8 14.400

Where you can see, at index 2 of the column A they both produce 3.4 because there the interpolation is (2.1 + 4.7)/2 but in column B the values differ.

For a one-line script and it's application to time series, you can see this post: Average between values with unevenly distributed time in Pandas DataFrame


问:
Return after clearInterval
I have a code that runs setInterval in a function. What I try to achive is to exit from that function after clearInterval occured. I set up a condition to check wheter the interval is cleared. I'm struggling to find a method to return from the main Start() function based on the current state of the code.

Code:

```<code>function Start() {

    var elementX = document.getElementById('moveMeX')
    var elementY = document.getElementById('moveMeY')
    elementY.style.top = "0px"

    var posX = 0
    startPosX = 0
    var posY = 0
    startPosY = 0
    var speed = 1
    var xIsMoving = true
    var yIsMoving = true

    var myIntervalX = setInterval(function() {
        if(startPosX == 0) {
            posX+=speed
            elementX.style.left = posX + 'px'
            if(posX==100) {
                startPosX = 100
            }
        }
        else if (startPosX==100) {
            posX-=speed
            elementX.style.left = posX + 'px'
            if(posX==0) {
                startPosX = 0
            }
        }
    }, 10);

    function stopX() {
        clearInterval(myIntervalX);
        xIsMoving = false
    }

    elementX.addEventListener("mousedown", stopX);
    elementX.addEventListener("mousedown", startY);

    function startY() {
        var myIntervalY = setInterval(function() {
            if(startPosY == 0) {
                posY+=speed
                elementY.style.top = posY + 'px'
                if(posY==100) {
                    startPosY = 100
                }
            }
            else if (startPosY==100) {
                posY-=speed
                elementY.style.top = posY + 'px'
                if(posY==0) {
                    startPosY = 0
                }
            }
        }, 10);

        function stopY() {
            elementY.style.zIndex = "-1";
            clearInterval(myIntervalY);
            yIsMoving = false
        }

        elementY.addEventListener("mousedown", stopY);
    }

    if (xIsMoving === false && yIsMoving === false) {
        console.log('stopped')
        stopped = true
    }
}

Start()
</code>```

Codepen link: https://codepen.io/silentstorm902/pen/podNxVy

答:
The part you state you have a problem with,

```<code>if (xIsMoving === false && yIsMoving === false) {
    console.log('stopped')
    stopped = true
}
</code>```

currently only runs once: when Start() is first called.  At that time, both conditions are false because the variables have their initial declared values of true.

You could create a new setInterval to run this if statement every so often, but it seems unnecessary because your current stopY function is really the place where you know that both xIsMoving and yIsMoving are both false -- because stopY only runs after stopX has run. So just move your statement of stopped=true at the end of the stopY function:

```<code>function stopY() {
    elementY.style.zIndex = "-1";
    clearInterval(myIntervalY);
    yIsMoving = false;
    console.log("stopped");
    stopped = true;
}
</code>```

Title: Return after clearInterval

Body:
I have a code that runs setInterval in a function. What I try to achive is to exit from that function after clearInterval occured. I set up a condition to check wheter the interval is cleared. I'm struggling to find a method to return from the main Start() function based on the current state of the code.

Code:

function Start() {

    var elementX = document.getElementById('moveMeX')
    var elementY = document.getElementById('moveMeY')
    elementY.style.top = "0px"

    var posX = 0
    startPosX = 0
    var posY = 0
    startPosY = 0
    var speed = 1
    var xIsMoving = true
    var yIsMoving = true

    var myIntervalX = setInterval(function() {
        if(startPosX == 0) {
            posX+=speed
            elementX.style.left = posX + 'px'
            if(posX==100) {
                startPosX = 100
            }
        }
        else if (startPosX==100) {
            posX-=speed
            elementX.style.left = posX + 'px'
            if(posX==0) {
                startPosX = 0
            }
        }
    }, 10);

    function stopX() {
        clearInterval(myIntervalX);
        xIsMoving = false
    }

    elementX.addEventListener("mousedown", stopX);
    elementX.addEventListener("mousedown", startY);

    function startY() {
        var myIntervalY = setInterval(function() {
            if(startPosY == 0) {
                posY+=speed
                elementY.style.top = posY + 'px'
                if(posY==100) {
                    startPosY = 100
                }
            }
            else if (startPosY==100) {
                posY-=speed
                elementY.style.top = posY + 'px'
                if(posY==0) {
                    startPosY = 0
                }
            }
        }, 10);

        function stopY() {
            elementY.style.zIndex = "-1";
            clearInterval(myIntervalY);
            yIsMoving = false
        }

        elementY.addEventListener("mousedown", stopY);
    }

    if (xIsMoving === false && yIsMoving === false) {
        console.log('stopped')
        stopped = true
    }
}

Start()

Codepen link: https://codepen.io/silentstorm902/pen/podNxVy

Body:
The part you state you have a problem with,

if (xIsMoving === false && yIsMoving === false) {
    console.log('stopped')
    stopped = true
}

currently only runs once: when Start() is first called.  At that time, both conditions are false because the variables have their initial declared values of true.

You could create a new setInterval to run this if statement every so often, but it seems unnecessary because your current stopY function is really the place where you know that both xIsMoving and yIsMoving are both false -- because stopY only runs after stopX has run. So just move your statement of stopped=true at the end of the stopY function:

function stopY() {
    elementY.style.zIndex = "-1";
    clearInterval(myIntervalY);
    yIsMoving = false;
    console.log("stopped");
    stopped = true;
}


问:
git branching - merging feature branch to release and dev branch
is it possible to merge a feature branch to 2 branches ?
scenario: dev branch is used to push daily changes to UAT for tests. A release branch is created for final push to production. we have feature/bug branches which the dev uses to commit code
IS it possible to first create a PR to the develop branch and ones validated in UAT have this pushed to the release branch? if the development isnt approved then the code remains in the development branch.

to give you more details .. if we want to only merge Feature A and C and not include feature B in the next release .. whats the best way to proceed? is cherry picking the only option we have?

答:
After you merged your feature branch --> dev, you have two possibilities :

if you have one release branch, then rebase release branch on dev :

```<code>git checkout release

git rebase dev
</code>```

or create a new release branch from dev, with the number of version like release/2.2.10

Body:
After you merged your feature branch --> dev, you have two possibilities :

if you have one release branch, then rebase release branch on dev :

git checkout release

git rebase dev

or create a new release branch from dev, with the number of version like release/2.2.10


答:
The current trend is denormalize (i.e. put them in the same table). It usually give better performance, but easier to make inconsistent (programming mistake, that is).

Plan: determine your workload type.

Benchmark: See if the performance gain worth the risk.

Title: Query JOIN or not? (optimization)

Body:
i was wondering if to use 2 tables is better then using 1 single table .

Scenario:

i have a simple user table and a simple user_details table. i can JOIN tables and select both records.

But i was wondering if to merge 2 table into 1 single table.

what if i have 2milions users records in both tables?

in terms of speed and exec time is better to have a single table when selecting records?


问:
SQL joining different rows into one row and changing the output based on the values
I'd like to output two rows into one and change the output based on the values

SQL syntax:

```<code>SELECT *
FROM course
  LEFT OUTER JOIN located ON course.course_id = located.course_id
  LEFT OUTER JOIN city ON city.city_id = located.city_id
</code>```

PHP syntax:

```<code>  while ($row=$result->fetch_assoc()) { ?>
     <div class="col-lg-4 col-md-6" style="margin-bottom: 20px">
          <div class="card bg-black" style="text-align: center;">
               <div class="card-body">
                   <h3 class="card-text text-white"><?= $row['name']?></h3>
                   <p class="text-danger"><?= $row['city_name'];?></p>
               </div>
          </div>
     </div>
   <?php
   }
   ?>
</code>```

The output:

How I'd like it to be:

But if it is only one city it would show the name of the city which happened to be "City 1" or "City 2".

答:
You can do it by grouping the results in SQL and then using a conditional select. For example:

```<code>SELECT
  course.name,
  IF(COUNT(*) > 1, COUNT(*), MIN(city_name)) as city_name
FROM course
  LEFT OUTER JOIN located ON course.course_id = located.course_id
  LEFT OUTER JOIN city ON city.city_id = located.city_id
GROUP BY course.course_id
</code>```

In your case, maybe something like this would be more suitable

```<code>SELECT
  IF(city_count > 1, CONCAT(city_count, ' cities'), city_name) as city_name
FROM course
  LEFT OUTER JOIN
    (SELECT course_id, COUNT(*) as city_count, MIN(city_name) as city_name
      FROM located
        LEFT OUTER JOIN city ON city.city_id = located.city_id
      GROUP BY located.course_id
    ) cities ON course.course_id = cities.course_id
GROUP BY course.course_id
</code>```

Body:
I'd like to output two rows into one and change the output based on the values

SQL syntax:

SELECT *
FROM course
  LEFT OUTER JOIN located ON course.course_id = located.course_id
  LEFT OUTER JOIN city ON city.city_id = located.city_id

PHP syntax:

  while ($row=$result->fetch_assoc()) { ?>

<?= $row['name']?>

<?= $row['city_name'];?>

   <?php
   }
   ?>

The output:

How I'd like it to be:

But if it is only one city it would show the name of the city which happened to be "City 1" or "City 2".

Body:
You can do it by grouping the results in SQL and then using a conditional select. For example:

SELECT
  course.name,
  IF(COUNT(*) > 1, COUNT(*), MIN(city_name)) as city_name
FROM course
  LEFT OUTER JOIN located ON course.course_id = located.course_id
  LEFT OUTER JOIN city ON city.city_id = located.city_id
GROUP BY course.course_id

In your case, maybe something like this would be more suitable

SELECT
  IF(city_count > 1, CONCAT(city_count, ' cities'), city_name) as city_name
FROM course
  LEFT OUTER JOIN
    (SELECT course_id, COUNT(*) as city_count, MIN(city_name) as city_name
      FROM located
        LEFT OUTER JOIN city ON city.city_id = located.city_id
      GROUP BY located.course_id
    ) cities ON course.course_id = cities.course_id
GROUP BY course.course_id


问:
change the time interval in spring app using the code
I have a spring boot applicate that is using many types of date objects it
like:

java.util.Date

java.time.LocalDate

java.time.Instant

I have a sandbox environment, I want to do some tests on it,
but in tests, I need time to be changed by shifting the current_time by one year, in other words, I want to interval the time by 1 year.

example:
let's suppose the date now is 7/feb/2022
if I called any date function, I need it to return 7/feb/2023,

I want to change the date just in the spring app, I don't want to change the whole server time.

Is this doable in spring app for any of the previous date objects?

update:
I am using code like this in all my app

```<code>LocalDate localDate = LocalDate.now();
Date date = new Date()
</code>```

I don't want to change the code in all my app (line by line)

I am looking at changing the date by adding some configurations, not by changing the existing code.

答:
Most of these java objects work well with each other. I'm assuming you are storing the server time in one of these classes. There is a simple function to add a year in LocalDate. Here is what I would do to get one year after the given server time.

```<code>LocalDate serverDate = LocalDate.of(2022, 2, 7);
System.out.println(serverDate);

LocalDate newTestDate = serverDate.plusYears(1);
System.out.println(newTestDate);

2022-02-07
2023-02-07
</code>```

Most of these date objects can convert into the other object with a simple function. Hope this answers your question!

Body:
I have a spring boot applicate that is using many types of date objects it
like:

java.util.Date

java.time.LocalDate

java.time.Instant

I have a sandbox environment, I want to do some tests on it,
but in tests, I need time to be changed by shifting the current_time by one year, in other words, I want to interval the time by 1 year.

example:
let's suppose the date now is 7/feb/2022
if I called any date function, I need it to return 7/feb/2023,

I want to change the date just in the spring app, I don't want to change the whole server time.

Is this doable in spring app for any of the previous date objects?

update:
I am using code like this in all my app

LocalDate localDate = LocalDate.now();
Date date = new Date()

I don't want to change the code in all my app (line by line)

I am looking at changing the date by adding some configurations, not by changing the existing code.

Body:
Most of these java objects work well with each other. I'm assuming you are storing the server time in one of these classes. There is a simple function to add a year in LocalDate. Here is what I would do to get one year after the given server time.

LocalDate serverDate = LocalDate.of(2022, 2, 7);
System.out.println(serverDate);

LocalDate newTestDate = serverDate.plusYears(1);
System.out.println(newTestDate);

2022-02-07
2023-02-07

Most of these date objects can convert into the other object with a simple function. Hope this answers your question!