问:
How can I develop the in-site product filtering program with multiple dropdown using a JSON file?
I have an in-site redirect tool for our E-Commerce site that I developed with the help of this site. I would like to make these in-site redirects with a JSON file with options suitable for existing links.

The code I wrote

$("#find").on("click", function() {
    let mevsim = ($("#mevsim").val() == 0) ? "" : $("#mevsim").val();
    let tabangenisligi = ($("#tabangenisligi").val() == 0) ? "" : $("#tabangenisligi").val();
    let kesitorani = ($("#kesitorani").val() == 0) ? "" : $("#kesitorani").val();
    let jantcapi = ($("#jantcapi").val() == 0) ? "" : $("#jantcapi").val();
    let url = "https://kolayoto.com/collections/lastikleri?_=pf" + mevsim + tabangenisligi + kesitorani + jantcapi;
    console.log("url: " + url);
    location.href = url
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#find {
    background: #E8562A;
    color: white;
    border-style:none;
    border-radius: 5px;
    left: 50%;
    margin-left: 30%;
}
#baslik {
    color: #fff;
    margin: 0 0 5px;
    margin-top:-5px;
    padding: 0;
    font-weight: 700;
    font-size: 15px;
    text-align: center;
}
#dropdown-container {
    background: url(https://cdn.shopify.com/s/files/1/0251/6146/5961/files/summer_banner_2-2.jpg?v=1582620652) no-repeat center center !important;
    background-size: cover !important;
    margin-top: -40px !important;
    padding: 80px 0 !important;
}
#dropdown-holder {
    width: 300px;
    background: rgba(25, 18, 18, 0.4);
    margin: auto !important;
    padding: 20px !important;
}
.dropdown-holder .fo-info {
    color: #fff !important;
    margin: 5px 0 !important;
}
#dropdown-container > b {
    display: block !important;
    text-align: center !important;
    color: #000 !important;
    font-weight: 700 !important;
    font-size: 25px !important;
    margin-bottom: 15px !important;
}</code>```

    Lastik ebatınızı seçin.

Mevsim

        <select id="mevsim">
            <option value="">Seçiniz</option>
            <option value="&pf_t_diger_oezellikler=DiğerÖzellikler-4Mevsim">Dört Mevsim</option>
            <option value="&pf_t_mevsim=Mevsim-Yaz">Yaz</option>
            <option value="&pf_t_mevsim=Mevsim-Kış">Kış</option>
        </select>

Taban Genişliği

        <select id="tabangenisligi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-135">135</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-145">145</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-155">155</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-165">165</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-175">175</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-185">185</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-195">195</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-205">205</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-215">215</option>
        </select>

Kesit Oranı

        <select id="kesitorani">
            <option value="">Seçiniz</option>
            <option value="&pf_t_oran=Kesit%20Oranı-30">30</option>
            <option value="&pf_t_oran=Kesit%20Oranı-35">35</option>
            <option value="&pf_t_oran=Kesit%20Oranı-40">40</option>
            <option value="&pf_t_oran=Kesit%20Oranı-45">45</option>
            <option value="&pf_t_oran=Kesit%20Oranı-50">50</option>
            <option value="&pf_t_oran=Kesit%20Oranı-55">55</option>
            <option value="&pf_t_oran=Kesit%20Oranı-60">60</option>
        </select>

Jant Çapı

        <select id="jantcapi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_cap=Jant%20Çapı-13">13</option>
            <option value="&pf_t_cap=Jant%20Çapı-14">14</option>
            <option value="&pf_t_cap=Jant%20Çapı-15">15</option>
            <option value="&pf_t_cap=Jant%20Çapı-16">16</option>
            <option value="&pf_t_cap=Jant%20Çapı-17">17</option>
            <option value="&pf_t_cap=Jant%20Çapı-18">18</option>
        </select>

                Lastik ebatınızı, lastiğinizin yanak yüzeyine bakarak öğrenebilirsiniz.

            <button id="find">Hemen Bul</button>

```

And,

I found this solution because the site needs a more specific application, but I couldn't figure out how to integrate this into the app.

I have filter combinations as a JSON file that gives product results. Can we add filtering in order to select them only? For example, if we select the "Yaz" option in the first dropdown, only "Taban Genisligi" options of the "Yaz" option will be added to the second dropdown. Also, there is no need to assign values to each option in this filter option. If 4 options are selected, the button should direct us to the links in the csv file.And of course, in this case, we should use the dropdowns in order from start to finish and all selected. There may be exceptions because some filter options have 2 or 3 options instead of 4.

If you want to try it, the application on our live site also uses a way of working as I mentioned above. Our Site

As a newby software developer, I really need this development and I am waiting for your help. Thank you very much in advance.

答:
You could do it like this:

var data = {
  "Yaz": {
    "195": {
      "60": {
        "15": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Yaz&pf_t_genislik=Taban%20Genişliği-195&pf_t_oran=Kesit%20Oranı-60&pf_t_cap=Jant%20Çapı-15"
      }
    },
    "205": {
      "55": {
        "16": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Yaz&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-205&pf_t_oran=Kesit%20Oran%C4%B1-55&pf_t_cap=Jant%20%C3%87ap%C4%B1-16"
      },
      "70": {
        "15": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Yaz&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-205&pf_t_oran=Kesit%20Oran%C4%B1-70&pf_t_cap=Jant%20%C3%87ap%C4%B1-15"
      }
    }
  },
  "Kış": {
    "185": {
      "65": {
        "15": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Kış&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-185&pf_t_oran=Kesit%20Oran%C4%B1-65&pf_t_cap=Jant%20%C3%87ap%C4%B1-15"
      }
    },
    "225": {
      "45": {
        "17": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Kış&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-225&pf_t_oran=Kesit%20Oran%C4%B1-45&pf_t_cap=Jant%20%C3%87ap%C4%B1-17"
      }
    }
  },
  "DörtMevsim": {
    "205": {
      "55": {
        "16": "kolayoto.com/collections/lastikleri?_=pf&pf_t_diger_oezellikler=Di%C4%9Fer%C3%96zellikler-4Mevsim&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-205&pf_t_oran=Kesit%20Oran%C4%B1-55&pf_t_cap=Jant%20%C3%87ap%C4%B1-16"
      }
    },
    "255": {
      "40": {
        "20": "kolayoto.com/collections/lastikleri?_=pf&pf_t_diger_oezellikler=Di%C4%9Fer%C3%96zellikler-4Mevsim&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-255&pf_t_oran=Kesit%20Oran%C4%B1-40&pf_t_cap=Jant%20%C3%87ap%C4%B1-20"
      },
      "50": {
        "19": "kolayoto.com/collections/lastikleri?_=pf&pf_t_diger_oezellikler=Di%C4%9Fer%C3%96zellikler-4Mevsim&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-255&pf_t_oran=Kesit%20Oran%C4%B1-50&pf_t_cap=Jant%20%C3%87ap%C4%B1-19"
      }
    }
  }
}

let mevsim = [];
let tabangenisligi = [];
let kesitorani = [];
let jantcapi = [];

$.each(data, function(key, val) {
  mevsim.push(key);
  $.each(val, function(key2, val2) {
    tabangenisligi.push(key2);
    $.each(val2, function(key3, val3) {
      kesitorani.push(key3);
      $.each(val3, function(key4, val4) {
        jantcapi.push(key4);
      });
    });
  });
});

mevsim.sort();
tabangenisligi.sort();
kesitorani.sort();
jantcapi.sort();
mevsim = mevsim.filter((x, i, a) => a.indexOf(x) === i);
tabangenisligi = tabangenisligi.filter((x, i, a) => a.indexOf(x) === i);
kesitorani = kesitorani.filter((x, i, a) => a.indexOf(x) === i);
jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

$('#mevsim').empty();
$('#mevsim').append($('<option></option>').val("0").html("Seçiniz"));
$.each(mevsim, function(i, p) {
  $('#mevsim').append($('<option></option>').val(p).html(p));
});
$('#tabangenisligi').empty();
$('#tabangenisligi').append($('<option></option>').val("0").html("Seçiniz"));
$.each(tabangenisligi, function(i, p) {
  $('#tabangenisligi').append($('<option></option>').val(p).html(p));
});
$('#kesitorani').empty();
$('#kesitorani').append($('<option></option>').val("0").html("Seçiniz"));
$.each(kesitorani, function(i, p) {
  $('#kesitorani').append($('<option></option>').val(p).html(p));
});
$('#jantcapi').empty();
$('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
$.each(jantcapi, function(i, p) {
  $('#jantcapi').append($('<option></option>').val(p).html(p));
});

$("#tabangenisligi").prop('disabled', 'disabled');
$("#kesitorani").prop('disabled', 'disabled');
$("#jantcapi").prop('disabled', 'disabled');
$("#find").prop('disabled', 'disabled');

$("#mevsim").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#tabangenisligi").prop('disabled', false);
  }

  let mevsim = $(this).find("option:selected").text();
  let tabangenisligi = [];
  let kesitorani = [];
  let jantcapi = [];
  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        tabangenisligi.push(key2);
        $.each(val2, function(key3, val3) {
          kesitorani.push(key3);
          $.each(val3, function(key4, val4) {
            jantcapi.push(key4);
          });
        });
      });
    }
  });
  tabangenisligi.sort();
  kesitorani.sort();
  jantcapi.sort();
  tabangenisligi = tabangenisligi.filter((x, i, a) => a.indexOf(x) === i);
  kesitorani = kesitorani.filter((x, i, a) => a.indexOf(x) === i);
  jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

  $('#tabangenisligi').empty();
  $('#tabangenisligi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(tabangenisligi, function(i, p) {
    $('#tabangenisligi').append($('<option></option>').val(p).html(p));
  });
  $('#kesitorani').empty();
  $('#kesitorani').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(kesitorani, function(i, p) {
    $('#kesitorani').append($('<option></option>').val(p).html(p));
  });
  $('#jantcapi').empty();
  $('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(jantcapi, function(i, p) {
    $('#jantcapi').append($('<option></option>').val(p).html(p));
  });

});

$("#tabangenisligi").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#kesitorani").prop('disabled', false);
  }
  let mevsim = $("#mevsim").find("option:selected").text();
  let tabangenisligi = $(this).find("option:selected").text();
  let kesitorani = [];
  let jantcapi = [];
  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        if (key2 == tabangenisligi) {
          $.each(val2, function(key3, val3) {
            kesitorani.push(key3);
            $.each(val3, function(key4, val4) {
              jantcapi.push(key4);
            });
          });
        }
      });
    }
  });
  kesitorani.sort();
  jantcapi.sort();
  kesitorani = kesitorani.filter((x, i, a) => a.indexOf(x) === i);
  jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

  $('#kesitorani').empty();
  $('#kesitorani').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(kesitorani, function(i, p) {
    $('#kesitorani').append($('<option></option>').val(p).html(p));
  });
  $('#jantcapi').empty();
  $('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(jantcapi, function(i, p) {
    $('#jantcapi').append($('<option></option>').val(p).html(p));
  });

});

$("#kesitorani").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#jantcapi").prop('disabled', false);
  }
  let mevsim = $("#mevsim").find("option:selected").text();
  let tabangenisligi = $("#tabangenisligi").find("option:selected").text();
  let kesitorani = $(this).find("option:selected").text();
  let jantcapi = [];
  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        if (key2 == tabangenisligi) {
          $.each(val2, function(key3, val3) {
            if (key3 == kesitorani) {
              $.each(val3, function(key4, val4) {
                jantcapi.push(key4);
              });
            }
          });
        }
      });
    }
  });
  jantcapi.sort();
  jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

  $('#jantcapi').empty();
  $('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(jantcapi, function(i, p) {
    $('#jantcapi').append($('<option></option>').val(p).html(p));
  });

});

$("#jantcapi").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#find").prop('disabled', false);
  }
});

$("#find").on("click", function() {
  let mevsim = $("#mevsim").val();
  let tabangenisligi = $("#tabangenisligi").val();
  let kesitorani = $("#kesitorani").val();
  let jantcapi = $("#jantcapi").val();
  let newUrl;

  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        if (key2 == tabangenisligi) {
          $.each(val2, function(key3, val3) {
            if (key3 == kesitorani) {
              $.each(val3, function(key4, val4) {
                if (key4 == jantcapi) {
                  newUrl = val4;
                }
              });
            }
          });
        }
      });
    }
  });

  console.log(newUrl);
  /* location.href= url */
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dropdown-container">
  <b>Lastik ebatınızı seçin.</b>
  <div id="dropdown-holder">
    <p id="baslik">Mevsim</p>
    <select id="mevsim">
    </select><br /><br />
    <p id="baslik">Taban Genişliği</p>
    <select id="tabangenisligi">
    </select><br /><br />
    <p id="baslik">Kesit Oranı</p>
    <select id="kesitorani">
    </select><br /><br />
    <p id="baslik">Jant Çapı</p>
    <select id="jantcapi">
    </select><br /><br />
    <button id="find">
      Hemen Bul
    </button>
  </div>
</div>
<br /><br /></code>```

Body:
I have an in-site redirect tool for our E-Commerce site that I developed with the help of this site. I would like to make these in-site redirects with a JSON file with options suitable for existing links.

The code I wrote

$("#find").on("click", function() {
    let mevsim = ($("#mevsim").val() == 0) ? "" : $("#mevsim").val();
    let tabangenisligi = ($("#tabangenisligi").val() == 0) ? "" : $("#tabangenisligi").val();
    let kesitorani = ($("#kesitorani").val() == 0) ? "" : $("#kesitorani").val();
    let jantcapi = ($("#jantcapi").val() == 0) ? "" : $("#jantcapi").val();
    let url = "https://kolayoto.com/collections/lastikleri?_=pf" + mevsim + tabangenisligi + kesitorani + jantcapi;
    console.log("url: " + url);
    location.href = url
});

#find {
    background: #E8562A;
    color: white;
    border-style:none;
    border-radius: 5px;
    left: 50%;
    margin-left: 30%;
}
#baslik {
    color: #fff;
    margin: 0 0 5px;
    margin-top:-5px;
    padding: 0;
    font-weight: 700;
    font-size: 15px;
    text-align: center;
}
#dropdown-container {
    background: url(https://cdn.shopify.com/s/files/1/0251/6146/5961/files/summer_banner_2-2.jpg?v=1582620652) no-repeat center center !important;
    background-size: cover !important;
    margin-top: -40px !important;
    padding: 80px 0 !important;
}
#dropdown-holder {
    width: 300px;
    background: rgba(25, 18, 18, 0.4);
    margin: auto !important;
    padding: 20px !important;
}
.dropdown-holder .fo-info {
    color: #fff !important;
    margin: 5px 0 !important;
}
#dropdown-container > b {
    display: block !important;
    text-align: center !important;
    color: #000 !important;
    font-weight: 700 !important;
    font-size: 25px !important;
    margin-bottom: 15px !important;
}

    Lastik ebatınızı seçin.

Mevsim

        <select id="mevsim">
            <option value="">Seçiniz</option>
            <option value="&pf_t_diger_oezellikler=DiğerÖzellikler-4Mevsim">Dört Mevsim</option>
            <option value="&pf_t_mevsim=Mevsim-Yaz">Yaz</option>
            <option value="&pf_t_mevsim=Mevsim-Kış">Kış</option>
        </select>

Taban Genişliği

        <select id="tabangenisligi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-135">135</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-145">145</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-155">155</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-165">165</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-175">175</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-185">185</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-195">195</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-205">205</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-215">215</option>
        </select>

Kesit Oranı

        <select id="kesitorani">
            <option value="">Seçiniz</option>
            <option value="&pf_t_oran=Kesit%20Oranı-30">30</option>
            <option value="&pf_t_oran=Kesit%20Oranı-35">35</option>
            <option value="&pf_t_oran=Kesit%20Oranı-40">40</option>
            <option value="&pf_t_oran=Kesit%20Oranı-45">45</option>
            <option value="&pf_t_oran=Kesit%20Oranı-50">50</option>
            <option value="&pf_t_oran=Kesit%20Oranı-55">55</option>
            <option value="&pf_t_oran=Kesit%20Oranı-60">60</option>
        </select>

Jant Çapı

        <select id="jantcapi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_cap=Jant%20Çapı-13">13</option>
            <option value="&pf_t_cap=Jant%20Çapı-14">14</option>
            <option value="&pf_t_cap=Jant%20Çapı-15">15</option>
            <option value="&pf_t_cap=Jant%20Çapı-16">16</option>
            <option value="&pf_t_cap=Jant%20Çapı-17">17</option>
            <option value="&pf_t_cap=Jant%20Çapı-18">18</option>
        </select>

                Lastik ebatınızı, lastiğinizin yanak yüzeyine bakarak öğrenebilirsiniz.

            <button id="find">Hemen Bul</button>

And,

I found this solution because the site needs a more specific application, but I couldn't figure out how to integrate this into the app.

I have filter combinations as a JSON file that gives product results. Can we add filtering in order to select them only? For example, if we select the "Yaz" option in the first dropdown, only "Taban Genisligi" options of the "Yaz" option will be added to the second dropdown. Also, there is no need to assign values to each option in this filter option. If 4 options are selected, the button should direct us to the links in the csv file.And of course, in this case, we should use the dropdowns in order from start to finish and all selected. There may be exceptions because some filter options have 2 or 3 options instead of 4.

If you want to try it, the application on our live site also uses a way of working as I mentioned above. Our Site

As a newby software developer, I really need this development and I am waiting for your help. Thank you very much in advance.

Body:
You could do it like this:

var data = {
  "Yaz": {
    "195": {
      "60": {
        "15": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Yaz&pf_t_genislik=Taban%20Genişliği-195&pf_t_oran=Kesit%20Oranı-60&pf_t_cap=Jant%20Çapı-15"
      }
    },
    "205": {
      "55": {
        "16": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Yaz&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-205&pf_t_oran=Kesit%20Oran%C4%B1-55&pf_t_cap=Jant%20%C3%87ap%C4%B1-16"
      },
      "70": {
        "15": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Yaz&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-205&pf_t_oran=Kesit%20Oran%C4%B1-70&pf_t_cap=Jant%20%C3%87ap%C4%B1-15"
      }
    }
  },
  "Kış": {
    "185": {
      "65": {
        "15": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Kış&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-185&pf_t_oran=Kesit%20Oran%C4%B1-65&pf_t_cap=Jant%20%C3%87ap%C4%B1-15"
      }
    },
    "225": {
      "45": {
        "17": "kolayoto.com/collections/lastikleri?_=pf&pf_t_mevsim=Mevsim-Kış&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-225&pf_t_oran=Kesit%20Oran%C4%B1-45&pf_t_cap=Jant%20%C3%87ap%C4%B1-17"
      }
    }
  },
  "DörtMevsim": {
    "205": {
      "55": {
        "16": "kolayoto.com/collections/lastikleri?_=pf&pf_t_diger_oezellikler=Di%C4%9Fer%C3%96zellikler-4Mevsim&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-205&pf_t_oran=Kesit%20Oran%C4%B1-55&pf_t_cap=Jant%20%C3%87ap%C4%B1-16"
      }
    },
    "255": {
      "40": {
        "20": "kolayoto.com/collections/lastikleri?_=pf&pf_t_diger_oezellikler=Di%C4%9Fer%C3%96zellikler-4Mevsim&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-255&pf_t_oran=Kesit%20Oran%C4%B1-40&pf_t_cap=Jant%20%C3%87ap%C4%B1-20"
      },
      "50": {
        "19": "kolayoto.com/collections/lastikleri?_=pf&pf_t_diger_oezellikler=Di%C4%9Fer%C3%96zellikler-4Mevsim&pf_t_genislik=Taban%20Geni%C5%9Fli%C4%9Fi-255&pf_t_oran=Kesit%20Oran%C4%B1-50&pf_t_cap=Jant%20%C3%87ap%C4%B1-19"
      }
    }
  }
}

let mevsim = [];
let tabangenisligi = [];
let kesitorani = [];
let jantcapi = [];

$.each(data, function(key, val) {
  mevsim.push(key);
  $.each(val, function(key2, val2) {
    tabangenisligi.push(key2);
    $.each(val2, function(key3, val3) {
      kesitorani.push(key3);
      $.each(val3, function(key4, val4) {
        jantcapi.push(key4);
      });
    });
  });
});

mevsim.sort();
tabangenisligi.sort();
kesitorani.sort();
jantcapi.sort();
mevsim = mevsim.filter((x, i, a) => a.indexOf(x) === i);
tabangenisligi = tabangenisligi.filter((x, i, a) => a.indexOf(x) === i);
kesitorani = kesitorani.filter((x, i, a) => a.indexOf(x) === i);
jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

$('#mevsim').empty();
$('#mevsim').append($('<option></option>').val("0").html("Seçiniz"));
$.each(mevsim, function(i, p) {
  $('#mevsim').append($('<option></option>').val(p).html(p));
});
$('#tabangenisligi').empty();
$('#tabangenisligi').append($('<option></option>').val("0").html("Seçiniz"));
$.each(tabangenisligi, function(i, p) {
  $('#tabangenisligi').append($('<option></option>').val(p).html(p));
});
$('#kesitorani').empty();
$('#kesitorani').append($('<option></option>').val("0").html("Seçiniz"));
$.each(kesitorani, function(i, p) {
  $('#kesitorani').append($('<option></option>').val(p).html(p));
});
$('#jantcapi').empty();
$('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
$.each(jantcapi, function(i, p) {
  $('#jantcapi').append($('<option></option>').val(p).html(p));
});

$("#tabangenisligi").prop('disabled', 'disabled');
$("#kesitorani").prop('disabled', 'disabled');
$("#jantcapi").prop('disabled', 'disabled');
$("#find").prop('disabled', 'disabled');

$("#mevsim").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#tabangenisligi").prop('disabled', false);
  }

  let mevsim = $(this).find("option:selected").text();
  let tabangenisligi = [];
  let kesitorani = [];
  let jantcapi = [];
  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        tabangenisligi.push(key2);
        $.each(val2, function(key3, val3) {
          kesitorani.push(key3);
          $.each(val3, function(key4, val4) {
            jantcapi.push(key4);
          });
        });
      });
    }
  });
  tabangenisligi.sort();
  kesitorani.sort();
  jantcapi.sort();
  tabangenisligi = tabangenisligi.filter((x, i, a) => a.indexOf(x) === i);
  kesitorani = kesitorani.filter((x, i, a) => a.indexOf(x) === i);
  jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

  $('#tabangenisligi').empty();
  $('#tabangenisligi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(tabangenisligi, function(i, p) {
    $('#tabangenisligi').append($('<option></option>').val(p).html(p));
  });
  $('#kesitorani').empty();
  $('#kesitorani').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(kesitorani, function(i, p) {
    $('#kesitorani').append($('<option></option>').val(p).html(p));
  });
  $('#jantcapi').empty();
  $('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(jantcapi, function(i, p) {
    $('#jantcapi').append($('<option></option>').val(p).html(p));
  });

});

$("#tabangenisligi").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#kesitorani").prop('disabled', false);
  }
  let mevsim = $("#mevsim").find("option:selected").text();
  let tabangenisligi = $(this).find("option:selected").text();
  let kesitorani = [];
  let jantcapi = [];
  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        if (key2 == tabangenisligi) {
          $.each(val2, function(key3, val3) {
            kesitorani.push(key3);
            $.each(val3, function(key4, val4) {
              jantcapi.push(key4);
            });
          });
        }
      });
    }
  });
  kesitorani.sort();
  jantcapi.sort();
  kesitorani = kesitorani.filter((x, i, a) => a.indexOf(x) === i);
  jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

  $('#kesitorani').empty();
  $('#kesitorani').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(kesitorani, function(i, p) {
    $('#kesitorani').append($('<option></option>').val(p).html(p));
  });
  $('#jantcapi').empty();
  $('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(jantcapi, function(i, p) {
    $('#jantcapi').append($('<option></option>').val(p).html(p));
  });

});

$("#kesitorani").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#jantcapi").prop('disabled', false);
  }
  let mevsim = $("#mevsim").find("option:selected").text();
  let tabangenisligi = $("#tabangenisligi").find("option:selected").text();
  let kesitorani = $(this).find("option:selected").text();
  let jantcapi = [];
  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        if (key2 == tabangenisligi) {
          $.each(val2, function(key3, val3) {
            if (key3 == kesitorani) {
              $.each(val3, function(key4, val4) {
                jantcapi.push(key4);
              });
            }
          });
        }
      });
    }
  });
  jantcapi.sort();
  jantcapi = jantcapi.filter((x, i, a) => a.indexOf(x) === i);

  $('#jantcapi').empty();
  $('#jantcapi').append($('<option></option>').val("0").html("Seçiniz"));
  $.each(jantcapi, function(i, p) {
    $('#jantcapi').append($('<option></option>').val(p).html(p));
  });

});

$("#jantcapi").on("change", function() {
  if ($(this).find("option:selected").val() != "0") {
    $("#find").prop('disabled', false);
  }
});

$("#find").on("click", function() {
  let mevsim = $("#mevsim").val();
  let tabangenisligi = $("#tabangenisligi").val();
  let kesitorani = $("#kesitorani").val();
  let jantcapi = $("#jantcapi").val();
  let newUrl;

  $.each(data, function(key, val) {
    if (key == mevsim) {
      $.each(val, function(key2, val2) {
        if (key2 == tabangenisligi) {
          $.each(val2, function(key3, val3) {
            if (key3 == kesitorani) {
              $.each(val3, function(key4, val4) {
                if (key4 == jantcapi) {
                  newUrl = val4;
                }
              });
            }
          });
        }
      });
    }
  });

  console.log(newUrl);
  /* location.href= url */
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dropdown-container">
  <b>Lastik ebatınızı seçin.</b>
  <div id="dropdown-holder">
    <p id="baslik">Mevsim</p>
    <select id="mevsim">
    </select><br /><br />
    <p id="baslik">Taban Genişliği</p>
    <select id="tabangenisligi">
    </select><br /><br />
    <p id="baslik">Kesit Oranı</p>
    <select id="kesitorani">
    </select><br /><br />
    <p id="baslik">Jant Çapı</p>
    <select id="jantcapi">
    </select><br /><br />
    <button id="find">
      Hemen Bul
    </button>
  </div>
</div>
<br /><br />


来源: stackexchange

问:
Print top 3 and bottom 3 scores in order from file
```<code>numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
  name = input("\nEnter the name of the band: ")
  votes = input("Enter how many votes that band received: ")
  file.write(name + "," + votes + "," + "\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

def topbottom3():

  file = open("scores.txt", "r")
  maxScore = 0
  maxName = ""
  for line in file:

    data = line.split(",")
    highScore = data[1]
    if int(highScore) > int(maxScore):
      maxScore = highScore
      maxName = data[0]
  file.close()

  #for i in range(3):
  print("Top 3 is", maxName, maxScore)
  maxScore = int(maxScore)

  #for i in range(3):
  #   print("Bottom 3 is", minName, minScore)
  #   minScore = int(minScore)
topbottom3()
</code>```

The user inputs a band name and score multiple times. This gets stored in a file.
I want the code to output the top 3 bands and bottom 3 bands in order.
The hashtag parts are just an idea as minScore, ect. has not been defined.

This code only outputs the highest score. I want the top 3 and bottom 3 in order to be printed.
Thank you in advance.

答:
The answer here is to simply use a list to store more than one value (since you are only printing one value). The code will look as follows (I formatted the variable names as Python advocates, snake case):

```<code>...
max_score = []
...

if int(high_score) > max(max_score):
    max_score += [int(high_score)]
</code>```

Remove the last line where you cast max_score to an int, and it should work.

I am curious, were you asked to write a function to find the max without using the max function? If so, we can find an alternative.

ContentLicense: CC BY-SA 4.0

Body:
numberofbands = int(input("How many bands are there in the competition? "))

print("Input each band’s name pressing enter after each one")

file = open("scores.txt","w")
for loop in range(numberofbands):
  name = input("\nEnter the name of the band: ")
  votes = input("Enter how many votes that band received: ")
  file.write(name + "," + votes + "," + "\n")
file.close()

number_of_lines = len(open("scores.txt").readlines(  ))

def topbottom3():

  file = open("scores.txt", "r")
  maxScore = 0
  maxName = ""
  for line in file:

    data = line.split(",")
    highScore = data[1]
    if int(highScore) > int(maxScore):
      maxScore = highScore
      maxName = data[0]
  file.close()

  #for i in range(3):
  print("Top 3 is", maxName, maxScore)
  maxScore = int(maxScore)

  #for i in range(3):
  #   print("Bottom 3 is", minName, minScore)
  #   minScore = int(minScore)
topbottom3()

The user inputs a band name and score multiple times. This gets stored in a file.
I want the code to output the top 3 bands and bottom 3 bands in order.
The hashtag parts are just an idea as minScore, ect. has not been defined.

This code only outputs the highest score. I want the top 3 and bottom 3 in order to be printed.
Thank you in advance.

Body:
The answer here is to simply use a list to store more than one value (since you are only printing one value). The code will look as follows (I formatted the variable names as Python advocates, snake case):

...
max_score = []
...

if int(high_score) > max(max_score):
    max_score += [int(high_score)]

Remove the last line where you cast max_score to an int, and it should work.

I am curious, were you asked to write a function to find the max without using the max function? If so, we can find an alternative.


问:
StorageException occuring when trying to get image from firebase database into storage
I am trying to store an image into FireBase database, I am pretty sure all of the code is working fine in relation to getting the imagelink as it no longer shows an error for it like before. Now however, a new problem occurs when I upload an image. Something to do with a storage exception and I am guessing it is having a problem to actually withdraw the imagelink from the storage and insert it into the database. Here is my code where I think the problem occurs:

```<code>private StorageReference PostsImagesReference;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;
//private String downloadUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    PostsImagesReference = FirebaseStorage.getInstance().getReference();

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
</code>```

Here is my entire code if need be:

```<code> private Toolbar mToolbar;
private ProgressDialog loadingBar;

private ImageButton SelectPostImage;
private Button AddPostButton;
private EditText PostDescription;

private static final int Gallery_Pick = 1;
private Uri ImageUri;

private StorageReference PostsImagesReference;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;
//private String downloadUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    PostsImagesReference = FirebaseStorage.getInstance().getReference();

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

    SelectPostImage = (ImageButton) findViewById(R.id.select_post_image);
    AddPostButton = (Button) findViewById(R.id.add_post);
    PostDescription = (EditText) findViewById(R.id.post_description);
    loadingBar = new ProgressDialog(this);

    mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Update Post");

    SelectPostImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            OpenGallery();

        }
    });

    AddPostButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            ValidatePostInfo();
        }
    });

}

private void ValidatePostInfo()
{
    Description = PostDescription.getText().toString();

    if(ImageUri == null)
    {
        Toast.makeText(this, "Please select image", Toast.LENGTH_SHORT).show();
    }
    else if(TextUtils.isEmpty(Description))
    {
        Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
    }
    else
    {
        loadingBar.setTitle("Post Uploading");
        loadingBar.setMessage("Please Wait");
        loadingBar.show();
        loadingBar.setCanceledOnTouchOutside(true);

        StoringImageToFirebaseStorage();

    }
}

private void StoringTextToFirebaseStorage(Uri downloadUrl)
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", downloadUrl.toString());

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {
                        StoringTextToFirebaseStorage(uri);

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}

private void OpenGallery()
{
    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent, Gallery_Pick);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
    {
        ImageUri = data.getData();
        SelectPostImage.setImageURI(ImageUri);
    }
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
    int id = item.getItemId();

    if(id == android.R.id.home)
    {
        SendUserToMainActivity();
    }

    return super.onOptionsItemSelected(item);
}

private void SendUserToMainActivity()
{
    Intent mainIntent = new Intent(PostActivity.this, MainActivity.class);
    startActivity(mainIntent);
}
</code>```

}

Error message:

```<code>2020-06-02 13:54:22.594 3466-5776/com.example.app E/StorageException: StorageException has occurred.
Object does not exist at location.
 Code: -13010 HttpResult: 404
</code>```

2020-06-02 13:54:22.594 3466-5776/com.example.app E/StorageException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}
    java.io.IOException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}
        at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage@@17.0.0:455)
        at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage@@17.0.0:435)
        at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage@@17.0.0:426)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage@@17.0.0:280)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage@@17.0.0:294)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage@@17.0.0:70)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage@@17.0.0:62)
        at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage@@17.0.0:74)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
2020-06-02 13:54:22.602 3466-3466/com.example.app E/RecyclerView: No layout manager attached; skipping layout

答:
You're trying to get the download URL of the `` folder, which isn't possible:

```<code>PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(...
</code>```

You need to call getDownloadUrl() on the StorageReference that you called putFile on:

```<code>filePath.getDownloadUrl().addOnSuccessListener(...
</code>```

Body:
I am trying to store an image into FireBase database, I am pretty sure all of the code is working fine in relation to getting the imagelink as it no longer shows an error for it like before. Now however, a new problem occurs when I upload an image. Something to do with a storage exception and I am guessing it is having a problem to actually withdraw the imagelink from the storage and insert it into the database. Here is my code where I think the problem occurs:

private StorageReference PostsImagesReference;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;
//private String downloadUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    PostsImagesReference = FirebaseStorage.getInstance().getReference();

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

Here is my entire code if need be:

 private Toolbar mToolbar;
private ProgressDialog loadingBar;

private ImageButton SelectPostImage;
private Button AddPostButton;
private EditText PostDescription;

private static final int Gallery_Pick = 1;
private Uri ImageUri;

private StorageReference PostsImagesReference;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;
//private String downloadUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post);

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    PostsImagesReference = FirebaseStorage.getInstance().getReference();

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

    SelectPostImage = (ImageButton) findViewById(R.id.select_post_image);
    AddPostButton = (Button) findViewById(R.id.add_post);
    PostDescription = (EditText) findViewById(R.id.post_description);
    loadingBar = new ProgressDialog(this);

    mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Update Post");

    SelectPostImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            OpenGallery();

        }
    });

    AddPostButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            ValidatePostInfo();
        }
    });

}

private void ValidatePostInfo()
{
    Description = PostDescription.getText().toString();

    if(ImageUri == null)
    {
        Toast.makeText(this, "Please select image", Toast.LENGTH_SHORT).show();
    }
    else if(TextUtils.isEmpty(Description))
    {
        Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
    }
    else
    {
        loadingBar.setTitle("Post Uploading");
        loadingBar.setMessage("Please Wait");
        loadingBar.show();
        loadingBar.setCanceledOnTouchOutside(true);

        StoringImageToFirebaseStorage();

    }
}

private void StoringTextToFirebaseStorage(Uri downloadUrl)
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", downloadUrl.toString());

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {
                        StoringTextToFirebaseStorage(uri);

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}

private void OpenGallery()
{
    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent, Gallery_Pick);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
    {
        ImageUri = data.getData();
        SelectPostImage.setImageURI(ImageUri);
    }
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
    int id = item.getItemId();

    if(id == android.R.id.home)
    {
        SendUserToMainActivity();
    }

    return super.onOptionsItemSelected(item);
}

private void SendUserToMainActivity()
{
    Intent mainIntent = new Intent(PostActivity.this, MainActivity.class);
    startActivity(mainIntent);
}

}

Error message:

2020-06-02 13:54:22.594 3466-5776/com.example.app E/StorageException: StorageException has occurred.
Object does not exist at location.
 Code: -13010 HttpResult: 404

2020-06-02 13:54:22.594 3466-5776/com.example.app E/StorageException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}
    java.io.IOException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}
        at com.google.firebase.storage.network.NetworkRequest.parseResponse(com.google.firebase:firebase-storage@@17.0.0:455)
        at com.google.firebase.storage.network.NetworkRequest.parseErrorResponse(com.google.firebase:firebase-storage@@17.0.0:435)
        at com.google.firebase.storage.network.NetworkRequest.processResponseStream(com.google.firebase:firebase-storage@@17.0.0:426)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage@@17.0.0:280)
        at com.google.firebase.storage.network.NetworkRequest.performRequest(com.google.firebase:firebase-storage@@17.0.0:294)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage@@17.0.0:70)
        at com.google.firebase.storage.internal.ExponentialBackoffSender.sendWithExponentialBackoff(com.google.firebase:firebase-storage@@17.0.0:62)
        at com.google.firebase.storage.GetDownloadUrlTask.run(com.google.firebase:firebase-storage@@17.0.0:74)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
2020-06-02 13:54:22.602 3466-3466/com.example.app E/RecyclerView: No layout manager attached; skipping layout

Body:
You're trying to get the download URL of the `` folder, which isn't possible:

PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(...

You need to call getDownloadUrl() on the StorageReference that you called putFile on:

filePath.getDownloadUrl().addOnSuccessListener(...


问:
ansible - Showing warning "conditional statements should not include jinja2 templating delimiters”
```<code>- name: creating  task
  shell: my_commnad
  when: ns.stdout.find('{{lookup('env',env')}}') == -1
</code>```

warning

```<code>[WARNING]: conditional statements should not include jinja2 templating
delimiters such as {{ }} or {% %}. Found:
ns.stdout.find("{{lookup('env','NAMESPACE')}}") == -1
</code>```

my playbook showing Warning "conditional statements should not include jinja2 templating delimiters".The task is to run the shell command if a paricular env is not present . how should I avoid this warning and keep task working?

答:
You never nest {{...}} markers inside a Jinja templating context. The arguments to the when keyword are implicitly inside a Jinja context, so you don't need any {{...}} markers. Just write e.g:

```<code>when: ns.stdout.find(lookup('env','NAMESPACE')) == -1
</code>```

Body:
- name: creating  task
  shell: my_commnad
  when: ns.stdout.find('{{lookup('env',env')}}') == -1

warning

[WARNING]: conditional statements should not include jinja2 templating
delimiters such as {{ }} or {% %}. Found:
ns.stdout.find("{{lookup('env','NAMESPACE')}}") == -1

my playbook showing Warning "conditional statements should not include jinja2 templating delimiters".The task is to run the shell command if a paricular env is not present . how should I avoid this warning and keep task working?

Body:
You never nest {{...}} markers inside a Jinja templating context. The arguments to the when keyword are implicitly inside a Jinja context, so you don't need any {{...}} markers. Just write e.g:

when: ns.stdout.find(lookup('env','NAMESPACE')) == -1


问:
How do I wait for the termination of my goroutines in beego
I have n number of goroutines waiting on a task channel. These goroutines are responsible for performing these tasks. Currently, I'm using beego as my web golang framework. When do I signal termination to my goroutines in a beego application? How do I deduce when a service termination request is received?

答:
As a first step, let's create a channel and bind it to signal which is in your sphere of interest. Then you need to create context and trigger cancelation function when you will receive this signal.

```<code>c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background()) // pass your ctx in all goroutines as first argument,
go func() {
    signal := <-c
    logger.Info("signal was received", zap.Stringer("signal", signal)
    cancel()
}()
</code>```

Then, you can create WaitGroup and pass your context as first argument in every goroutine

```<code>wg := &sync.WaitGroup{}
hooks.RunStartHooks(ctx, wg)
</code>```

Inside your worker listen to context cancelation working appropriately with wg as specified in docs

```<code>for {

    select {

    case <-ctx.Done():
        wg.Done()
        return
    }

    // other cases
}
</code>```

And finally,

```<code>    timeout := cfg.Server.HooksCloseTimeout // this is from your config
    if waitTimeout(wg, timeout) {
        logger.Info("timed out waiting for wait group")
    } else {
        logger.Info("server exited properly")
    }
</code>```

where waitTimeout is

```<code>// waitTimeout waits for the waitgroup for the specified max timeout.
// Returns true if waiting timed out.
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
    c := make(chan struct{})
    go func() {
        defer close(c)
        wg.Wait()
    }()
    select {
    case <-c:
        return false // completed normally
    case <-time.After(timeout):
        return true // timed out
    }
}
</code>```

Body:
As a first step, let's create a channel and bind it to signal which is in your sphere of interest. Then you need to create context and trigger cancelation function when you will receive this signal.

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
ctx, cancel := context.WithCancel(context.Background()) // pass your ctx in all goroutines as first argument,
go func() {
    signal := <-c
    logger.Info("signal was received", zap.Stringer("signal", signal)
    cancel()
}()

Then, you can create WaitGroup and pass your context as first argument in every goroutine

wg := &sync.WaitGroup{}
hooks.RunStartHooks(ctx, wg)

Inside your worker listen to context cancelation working appropriately with wg as specified in docs

for {

    select {

    case <-ctx.Done():
        wg.Done()
        return
    }

    // other cases
}

And finally,

    timeout := cfg.Server.HooksCloseTimeout // this is from your config
    if waitTimeout(wg, timeout) {
        logger.Info("timed out waiting for wait group")
    } else {
        logger.Info("server exited properly")
    }

where waitTimeout is

// waitTimeout waits for the waitgroup for the specified max timeout.
// Returns true if waiting timed out.
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
    c := make(chan struct{})
    go func() {
        defer close(c)
        wg.Wait()
    }()
    select {
    case <-c:
        return false // completed normally
    case <-time.After(timeout):
        return true // timed out
    }
}


问:
How to count the strings in a vector?
I have a data set as I've shown below:

```<code>df_A <- tribble(
      ~shop_name,      ~id,
        "A",         "1, 4, 3",
        "B",         "4, 6",
        "C",         "3, 5",
        "D",         "6, 2, 3",
)
</code>```

Now, I want to group the data by each unique id which in the vector, and then count them accordingly. Do you think it is doable? How can I manipulate the data to get my desired data?

```<code>desired <- tribble(
  ~id,   ~counted_id,
  "1",      1,
  "2",      1,
  "3",      3,
  "4",      2,
  "5",      1,
  "6",      2,
)
</code>```

答:
In base R

```<code>id_vector <- unlist(strsplit(df_A$id, ", "))
data.frame(table(id_vector))

#   id_vector Freq
# 1         1    1
# 2         2    1
# 3         3    3
# 4         4    2
# 5         5    1
# 6         6    2
</code>```

Using stringr::str_count():

```<code>ids <- as.character(1:7)
data.frame(
  id = ids,
  counted_id = sapply(ids, function(x) sum(str_count(df_A$id, x)))
)

#   id counted_id
# 1  1          1
# 2  2          1
# 3  3          3
# 4  4          2
# 5  5          1
# 6  6          2
# 7  7          0
</code>```

Title: How to count the strings in a vector?

Body:
I have a data set as I've shown below:

df_A <- tribble(
      ~shop_name,      ~id,
        "A",         "1, 4, 3",
        "B",         "4, 6",
        "C",         "3, 5",
        "D",         "6, 2, 3",
)

Now, I want to group the data by each unique id which in the vector, and then count them accordingly. Do you think it is doable? How can I manipulate the data to get my desired data?

desired <- tribble(
  ~id,   ~counted_id,
  "1",      1,
  "2",      1,
  "3",      3,
  "4",      2,
  "5",      1,
  "6",      2,
)

Body:
In base R

id_vector <- unlist(strsplit(df_A$id, ", "))
data.frame(table(id_vector))

#   id_vector Freq
# 1         1    1
# 2         2    1
# 3         3    3
# 4         4    2
# 5         5    1
# 6         6    2

Using stringr::str_count():

ids <- as.character(1:7)
data.frame(
  id = ids,
  counted_id = sapply(ids, function(x) sum(str_count(df_A$id, x)))
)

#   id counted_id
# 1  1          1
# 2  2          1
# 3  3          3
# 4  4          2
# 5  5          1
# 6  6          2
# 7  7          0


问:
How can I set the max number of MySQL processes or threads?
ps axuw| grep mysql indicates only MySQL process, but if I run htop I can see 10 rows each one of them with a separate PID. So I wonder if they are threads or processes that for some reason I cannot see using ps.

Would it make any sense to try to limit them to two on my development machine, where I don't need concurrent access of many clients.

BTW Running on Ubuntu 8.10

答:
You can set the max number of threads in your my.ini like this:

```<code>max_connections=2
</code>```

However you might also want to set this:

```<code>thread_cache_size=1
</code>```

The thread cache controls how many it keeps open even when nothing is happening.

OwnerDisplayName: szabgab

ContentLicense: CC BY-SA 3.0

Body:
You can set the max number of threads in your my.ini like this:

max_connections=2

However you might also want to set this:

thread_cache_size=1

The thread cache controls how many it keeps open even when nothing is happening.

OwnerDisplayName: RoBorg

ContentLicense: CC BY-SA 2.5


问:
Context menu for TreeViewer based on selected node - SWT
I need to create a context menu for a TreeViewer in an Eclipse plugin project. But, the menu should not contain constant items, they should vary depending on the type of the node that is selected. For example, my treeViewer has the following hierarchy:

```<code>Node A
 |
 --Node B
  |
   --Node C
</code>```

For node A - I want to show a menu with an action, but for nodes B and C I don't want to show anything (no menu).
I managed to create the menu for node A, but then I can't get rid of it when some other type of node is selected. My code looks like:

```<code>treeViewer.addSelectionChangedListener(
            new ISelectionChangedListener(){
                public void selectionChanged(SelectionChangedEvent event) {
                    if(event.getSelection() instanceof IStructuredSelection) {
                        IStructuredSelection selection = (IStructuredSelection)event.getSelection();
                        Object o = selection.getFirstElement();

                        MenuManager menuMgr = new MenuManager();

                        if (o instanceof NodeA){

                            Menu menu = menuMgr.createContextMenu(treeViewer.getControl());
                            treeViewer.getControl().setMenu(menu);
                            getSite().registerContextMenu(menuMgr, treeViewer);

                            menuMgr.add(new SomeAction());

                        }else {
                            //what ?
                        }
                    }

                }
            }
    );
</code>```

On the else branch I tried to call dispose(),removeAll() on the MenuManager...nothing works!

Any help is appreciated, thanks.

答:
As @jeeeyul mentioned, you should only create one MenuManager to use within your view.

You can use New>Plug-in Project and the view template to get an example of a context menu in a view using a viewer, but basically in your createPartControl(Composite) method you would hook up your context manager.

```<code>    MenuManager menuMgr = new MenuManager();
    menuMgr.setRemoveAllWhenShown(true);
    menuMgr.addMenuListener(new IMenuListener() {
        public void menuAboutToShow(IMenuManager manager) {
            SampleView.this.fillContextMenu(manager);
        }
    });
    Menu menu = menuMgr.createContextMenu(viewer.getControl());
    viewer.getControl().setMenu(menu);
    getSite().registerContextMenu(menuMgr, viewer);
</code>```

Your fillContextMenu(MenuManager) method will have access to your viewer, so you can get the current selection from that.  You can add whatever actions you want, even re-add actions after updating them with the current selection.

The registerContextMenu(*) call allows extension points like org.eclipse.ui.popupMenus and org.eclipse.ui.menus to contribute items to your context menu.

Body:
I need to create a context menu for a TreeViewer in an Eclipse plugin project. But, the menu should not contain constant items, they should vary depending on the type of the node that is selected. For example, my treeViewer has the following hierarchy:

Node A
 |
 --Node B
  |
   --Node C

For node A - I want to show a menu with an action, but for nodes B and C I don't want to show anything (no menu).
I managed to create the menu for node A, but then I can't get rid of it when some other type of node is selected. My code looks like:

treeViewer.addSelectionChangedListener(
            new ISelectionChangedListener(){
                public void selectionChanged(SelectionChangedEvent event) {
                    if(event.getSelection() instanceof IStructuredSelection) {
                        IStructuredSelection selection = (IStructuredSelection)event.getSelection();
                        Object o = selection.getFirstElement();

                        MenuManager menuMgr = new MenuManager();

                        if (o instanceof NodeA){

                            Menu menu = menuMgr.createContextMenu(treeViewer.getControl());
                            treeViewer.getControl().setMenu(menu);
                            getSite().registerContextMenu(menuMgr, treeViewer);

                            menuMgr.add(new SomeAction());

                        }else {
                            //what ?
                        }
                    }

                }
            }
    );

On the else branch I tried to call dispose(),removeAll() on the MenuManager...nothing works!

Any help is appreciated, thanks.

Body:
As @jeeeyul mentioned, you should only create one MenuManager to use within your view.

You can use New>Plug-in Project and the view template to get an example of a context menu in a view using a viewer, but basically in your createPartControl(Composite) method you would hook up your context manager.

    MenuManager menuMgr = new MenuManager();
    menuMgr.setRemoveAllWhenShown(true);
    menuMgr.addMenuListener(new IMenuListener() {
        public void menuAboutToShow(IMenuManager manager) {
            SampleView.this.fillContextMenu(manager);
        }
    });
    Menu menu = menuMgr.createContextMenu(viewer.getControl());
    viewer.getControl().setMenu(menu);
    getSite().registerContextMenu(menuMgr, viewer);

Your fillContextMenu(MenuManager) method will have access to your viewer, so you can get the current selection from that.  You can add whatever actions you want, even re-add actions after updating them with the current selection.

The registerContextMenu(*) call allows extension points like org.eclipse.ui.popupMenus and org.eclipse.ui.menus to contribute items to your context menu.


问:
VBA taking too long to apply the formula to the given range
Please refer attached Image below.  VBA code is taking more than 30 minutes to update the formula in Column F till the last row based on latest quarter information.

For Example, if I have Q1 data and Q2 data then formula should calculate based on Q2 data as it is the latest quarter.  This a main requirement.

I have done the below things.

1) Created a Named rages for each quarter/Column
Q1 =OFFSET(Data!$B$2;0;0;COUNTA(Data!$A:$A)-1;1);
Q2 =OFFSET(Data!$C$2;0;0;COUNTA(Data!$A:$A)-1;1);
Q3 =OFFSET(Data!$D$2;0;0;COUNTA(Data!$A:$A)-1;1);
Q4 =OFFSET(Data!$E$2;0;0;COUNTA(Data!$A:$A)-1;1);

2) Now in Column F I have included the following IF condition through VBA code=IF(Q4_Range>0;E2;IF(Q3_Range>0;D2;IF(Q2_Range>0;C2;IF(Q1_Range>0;B2;""))))

This is how it looks in the VBA editor

ActiveCell.FormulaR1C1 =_ "=IF(Q4_Range>0,RC[-1],IF(Q3_Range>0,RC[-2],IF(Q2_Range>0,RC[-3],IF(Q1_Range>0,RC[-4],""""))))"

When I run the VBA code it is taking more than 30 minutes to copy this formula till the last row which is dynamic and will be around 50,000 to 80,000 rows.

 My Complete Code

```<code>Sub Add_Formula()

Dim Sht As Worksheet
Dim LastRow As Long

    Set StartCell = Range("A2")

    LastRow = Sht.Cells(Sht.Rows.Count, StartCell.Column).End(xlUp).Row

      Range("F2:F" & LastRow).Select
      Range("F2:F" & LastRow).FormulaR1C1 = "=IF(FF3_RANGE>0,RC[-1],IF(FF2_RANGE>0,RC[-2],IF(FF1_RANGE>0,RC[-3],IF(FF0_RANGE>0,RC[-4],))))"

      Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"

End Sub
</code>```

Is there a way to speed-up process by changing the VBA code?

答:
Here are a few things that can help:

If all you need in Column F is the value of the latest quarter (cells Bx:Ex), then you can simplify your formula without using dynamic named ranges. This answer shows several options for you, but since you're almost certainly looking at numbers, the formula in column F should be =LOOKUP(9.99E+307,$B2:$E2).

You've got the right approach to apply the formula using VBA (which would be =LOOKUP(9.99E+307,RC2:RC5)), but you should always avoid using Select or Activate.

The real key in speeding up your process is to disable screen updates and automatic calculation.

Wrapped all together as an example:

```<code>Option Explicit

Sub Add_Formula()
    ToggleAppUpdates False
    Dim Sht As Worksheet
    Set Sht = Worksheets("Sheet1")
    With Sht
        Dim startCell As Range
        Set startCell = .Range("A2")
        Dim lastRow As Long
        lastRow = .Cells(.Rows.Count, startCell.Column).End(xlUp).Row
        With .Range("F2:F" & lastRow)
            .FormulaR1C1 = "=LOOKUP(9.99E+307,RC2:RC5)"
            .NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
        End With
    End With
    ToggleAppUpdates True
End Sub

Sub ToggleAppUpdates(ByVal state As Boolean)
    With Application
        .ScreenUpdating = state
        .Calculation = IIf(state, xlCalculationAutomatic, xlCalculationManual)
    End With
End Sub
</code>```

Body:
Please refer attached Image below.  VBA code is taking more than 30 minutes to update the formula in Column F till the last row based on latest quarter information.

For Example, if I have Q1 data and Q2 data then formula should calculate based on Q2 data as it is the latest quarter.  This a main requirement.

I have done the below things.

1) Created a Named rages for each quarter/Column
Q1 =OFFSET(Data!$B$2;0;0;COUNTA(Data!$A:$A)-1;1);
Q2 =OFFSET(Data!$C$2;0;0;COUNTA(Data!$A:$A)-1;1);
Q3 =OFFSET(Data!$D$2;0;0;COUNTA(Data!$A:$A)-1;1);
Q4 =OFFSET(Data!$E$2;0;0;COUNTA(Data!$A:$A)-1;1);

2) Now in Column F I have included the following IF condition through VBA code=IF(Q4_Range>0;E2;IF(Q3_Range>0;D2;IF(Q2_Range>0;C2;IF(Q1_Range>0;B2;""))))

This is how it looks in the VBA editor

ActiveCell.FormulaR1C1 =_ "=IF(Q4_Range>0,RC[-1],IF(Q3_Range>0,RC[-2],IF(Q2_Range>0,RC[-3],IF(Q1_Range>0,RC[-4],""""))))"

When I run the VBA code it is taking more than 30 minutes to copy this formula till the last row which is dynamic and will be around 50,000 to 80,000 rows.

 My Complete Code

Sub Add_Formula()

Dim Sht As Worksheet
Dim LastRow As Long

    Set StartCell = Range("A2")

    LastRow = Sht.Cells(Sht.Rows.Count, StartCell.Column).End(xlUp).Row

      Range("F2:F" & LastRow).Select
      Range("F2:F" & LastRow).FormulaR1C1 = "=IF(FF3_RANGE>0,RC[-1],IF(FF2_RANGE>0,RC[-2],IF(FF1_RANGE>0,RC[-3],IF(FF0_RANGE>0,RC[-4],))))"

      Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"

End Sub

Is there a way to speed-up process by changing the VBA code?

Body:
Here are a few things that can help:

If all you need in Column F is the value of the latest quarter (cells Bx:Ex), then you can simplify your formula without using dynamic named ranges. This answer shows several options for you, but since you're almost certainly looking at numbers, the formula in column F should be =LOOKUP(9.99E+307,$B2:$E2).

You've got the right approach to apply the formula using VBA (which would be =LOOKUP(9.99E+307,RC2:RC5)), but you should always avoid using Select or Activate.

The real key in speeding up your process is to disable screen updates and automatic calculation.

Wrapped all together as an example:

Option Explicit

Sub Add_Formula()
    ToggleAppUpdates False
    Dim Sht As Worksheet
    Set Sht = Worksheets("Sheet1")
    With Sht
        Dim startCell As Range
        Set startCell = .Range("A2")
        Dim lastRow As Long
        lastRow = .Cells(.Rows.Count, startCell.Column).End(xlUp).Row
        With .Range("F2:F" & lastRow)
            .FormulaR1C1 = "=LOOKUP(9.99E+307,RC2:RC5)"
            .NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
        End With
    End With
    ToggleAppUpdates True
End Sub

Sub ToggleAppUpdates(ByVal state As Boolean)
    With Application
        .ScreenUpdating = state
        .Calculation = IIf(state, xlCalculationAutomatic, xlCalculationManual)
    End With
End Sub


问:
IDE does not recognize Assumptions
I am using Junit5, and my IDE (IntelijIdea) is not recognize Assumptions. I am actually do not know why, but may be there is some dependecy on Maven I do not connect into project. Below I will show you the sample of my code.

This is my Assumptions import.

import org.junit.jupiter.api.Assumptions;

And this is wrong code (I can not compile it, compiler does not know what is assumeTrue() )

```<code>@Test
@EnabledOnOs(OS.MAC)
void testInsertion() {
    assumeTrue(isServerUp); //That place is crashing
    assertThrows(NullPointerException.class, () -> Connection.insertTheInstance(person),
            "");
</code>```

If you are familiar with this case then, please, share you knowledge) Many thanks!

答:
It's a import problem probably. Try:

```<code>  <dependency>
     <groupId>org.junit.jupiter</groupId>
     <artifactId>junit-jupiter-api</artifactId>
     <version>5.6.2</version>
     <scope>test</scope>
  </dependency>
</code>```

Check if maven import is ok

Close your project in intellij

Delete your .m2 folder in your HOME directory (user/yourusername in windows, /home in linux)

Execute in a terminal in your project: mvn dependency:purge-local-repository clean.

Open your project again

If it's not ok yet, try the junit 4.12. Its have Assumptions too.

Title: IDE does not recognize Assumptions

Body:
I am using Junit5, and my IDE (IntelijIdea) is not recognize Assumptions. I am actually do not know why, but may be there is some dependecy on Maven I do not connect into project. Below I will show you the sample of my code.

This is my Assumptions import.

import org.junit.jupiter.api.Assumptions;

And this is wrong code (I can not compile it, compiler does not know what is assumeTrue() )

@Test
@EnabledOnOs(OS.MAC)
void testInsertion() {
    assumeTrue(isServerUp); //That place is crashing
    assertThrows(NullPointerException.class, () -> Connection.insertTheInstance(person),
            "");

If you are familiar with this case then, please, share you knowledge) Many thanks!

Body:
It's a import problem probably. Try:

  <dependency>
     <groupId>org.junit.jupiter</groupId>
     <artifactId>junit-jupiter-api</artifactId>
     <version>5.6.2</version>
     <scope>test</scope>
  </dependency>

Check if maven import is ok

Close your project in intellij

Delete your .m2 folder in your HOME directory (user/yourusername in windows, /home in linux)

Execute in a terminal in your project: mvn dependency:purge-local-repository clean.

Open your project again

If it's not ok yet, try the junit 4.12. Its have Assumptions too.


答:
You can do with by splitting your string on ", " and table:</p>

```<code>as.data.frame(table(unlist(strsplit(df_A$id,", "))))

  Var1 Freq
1    1    1
2    2    1
3    3    3
4    4    2
5    5    1
6    6    2
</code>```

Title: How to count the strings in a vector?

Body:
You can do with by splitting your string on ", " and table:

as.data.frame(table(unlist(strsplit(df_A$id,", "))))

  Var1 Freq
1    1    1
2    2    1
3    3    3
4    4    2
5    5    1
6    6    2


问:
Jetpack Compose - Column - Gravity center
I'm creating a layout with Jetpack Compose and there is a column. I would like center items inside this column:</p>

```<code> Column(modifier = ExpandedWidth) {
        Text(text = item.title)
        Text(text = item.description)
 }
</code>```

答:
You can use these parameters:

horizontalAlignment = the horizontal gravity of the layout's children.

verticalArrangement= the vertical arrangement of the layout's children

Something like:

```<code>Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
) {
        Text(
                text = "First item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Second item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Third item",
                modifier = Modifier.padding(16.dp)
        )
}
</code>```

If you want only to center horizontally just use:

```<code>Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
) {
    Column (  ) { ... }
</code>```

Body:
I'm creating a layout with Jetpack Compose and there is a column. I would like center items inside this column:

 Column(modifier = ExpandedWidth) {
        Text(text = item.title)
        Text(text = item.description)
 }

Body:
You can use these parameters:

horizontalAlignment = the horizontal gravity of the layout's children.

verticalArrangement= the vertical arrangement of the layout's children

Something like:

Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
) {
        Text(
                text = "First item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Second item",
                modifier = Modifier.padding(16.dp)
        )
        Text(
                text = "Third item",
                modifier = Modifier.padding(16.dp)
        )
}

If you want only to center horizontally just use:

Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
) {
    Column (  ) { ... }