答:
I fix your code. I use position absolute to resolve this problem

also, z-index is important

function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropdown-menu {
  display: flex;
  flex-wrap: wrap;
  max-width: 1240px;
  margin-left: auto;
  margin-right: auto;
  height: auto;
  background-color: #F3F3F3;
  border: 1px solid gray;
  justify-content: space-around;
  font-family: Arial, Helvetica, sans-serif;
  padding-bottom: 20px;
  box-sizing: border-box;
  gap: 10px;
  margin-bottom: 10px;
  margin-top: -20px;

  position: absolute;
  z-index: 2;
  max-width: 100%;
}

.dropdown-menu-column {
  display: flex;
  flex-direction: column;
  width: 200px;
}

.dropdown-menu-column-block {
  display: flex;
  flex-direction: column;
}

.dropdown-menu-column-block-header {
  font-size: 14px;
  line-height: 14px;
  font-weight: bold;
  color: #595959;
  background-color: #dedede;
  padding-top: 9px;
  padding-bottom: 9px;
  display: block;
  text-align: center;
  margin-bottom: 10px;
  padding-left: 10px;
  padding-right: 10px;
  margin-top: 15px;
}

.dropdown-menu-column-block-element a {
  font-size: 13px;
  line-height: 22px;
  color: #167491;
}

.hide {
  display: none;
}

.dropdown-menu {
  display: none;
}

.hide:checked+label+div {
  display: flex;
}

@media (max-width: 444px) {
  .hide,
  .hide+label~div {
    display: none;
  }
  .hide:checked+label+div {
    display: block;
  }
  .hide+label:before {
    background-color: #2CB1D9;
    color: black;
    content: "\002B";
    display: block;
    float: right;
    font-size: 14px;
    font-weight: bold;
    height: 16px;
    line-height: 16px;
    margin: 3px 5px;
    text-align: center;
    width: 16px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    border: 1px solid black;
  }
  .hide:checked+label:before {
    content: "\2212";
  }
  .dropdown-menu {
    gap: 0px;
    padding-bottom: 0px;
  }
  .dropdown-menu-column {
    width: 100%;
  }
  .dropdown-menu-column-block-header {
    margin-bottom: 0px;
    margin-top: 0px;
  }
  .dropdown-menu-column-block {
    border: 1px solid #CDCDCD;
  }
  .dropdown-menu-column-block-element a {
    padding-left: 10px;
    display: inline-block;
  }
}

.header-flex {
  width: 100%;
  max-width: 1240px;
  display: flex;
  margin-left: auto;
  margin-right: auto;
  justify-content: space-between;
  border: 1px solid black;
  align-items: center;
  border: 1px solid #cecece;
  font-size: 18px;
  color: #1c1c1c;
  position: relative;
  height: 60px;
  box-sizing: border-box;
}

.article-header {
  font-size: 24px;
  font-weight: bold;
  padding-left: 10px;
}

.article-header-price {
  color: red;
  font-size: 24px;
  font-weight: bold;
}

.sidebar-button {
  font-size: 15px;
  line-height: 15px;
  font-weight: bold;
  color: #fff;
  text-align: center;
  background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/feedBackButton.png);
  height: 40px;
  width: 187px;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: #863e39;
  border-radius: 2px;
  cursor: pointer;
  display: block;
  margin-right: 20px;
}

.sidebar-button:hover {
  background-color: #1fa6ce;
  background-image: none;
}

.menu {
  display: flex;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  border: 1px dotted black;
  max-width: 1240px;
  color: white;
  font-size: 1rem;
  font-weight: bold;
  width: 100%;
  flex-wrap: nowrap;
  border-radius: 2px;
  margin-bottom: 20px;
  align-items: center;
  box-sizing: border-box;
  background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3.jpg');
  border: 0px;
  /*   border-bottom: 1px solid 167491; */
}

.menu-block:hover {
  background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3-hover.jpg');
}

.menu-block {
  width: 33%;
  box-sizing: border-box;
  /*   padding: 10px 0;  */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.menu-block-3 {
  min-width: 33%;
  flex-basis: 33.5%;
  max-width: 34%;
}

.menu-block-divider {
  width: 1px;
  height: 35px;
  margin-left: 1px;
  margin-right: 1px;
  background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/menuTop-li.gif);
}</code>```

О сервисе

      Услуги и цены

Контактная информация

      <input class="hide" id="hd-1" type="checkbox">
      Техническое обслуживание авто

Техническое обслуживание авто

Акции

      <input class="hide" id="hd-2" type="checkbox">
      Рулевое управление

Рулевое управление - прайс лист

Ремонт и замена рулевой рейки

Ремонт гидроусилителя руля (ГУР)

        <input class="hide" id="hd-3" type="checkbox">
        Трансмиссия

Трансмиссия- прайс-лист

Замена сцепления

Стоимость и ремонт вариатора

Диагноситка и ремонт РКПП

Ремонт раздаточной кородки TOD

      <input class="hide" id="hd-4" type="checkbox">
      Двигатель

Двигатель - прайс лист

Ремонт турбин

Замена маслосъемных колпачков

Ремонт и замена головок

Замена колец

Замена двигателя

Замена масла в двигателе

Замена свечей накала

Ремонт компонентов ГРМ

Замена цепи ГРМ

      <input class="hide" id="hd-5" type="checkbox">
      Топливная система

Топливная система - прайс лист

Ремонт топливной системы

Ремонт инжекторной системы

Ремонт узлов системы впрыска

Замена и диагностика форсунок

Замена топливного фильтра

      <input class="hide" id="hd-6" type="checkbox">
      Система электрики

Электрика - прайс лист

      <input class="hide" id="hd-7" type="checkbox">
      Системы охлаждения

Охлаждение - прайс лист

Замена радиатора охлаждения

Замена термостата

      <input class="hide" id="hd-8" type="checkbox">
      Тормозная система

Тормозная система - прайс-лист

Тормозная система

      <input class="hide" id="hd-9" type="checkbox">
      Выхлопная система

Выхлопная система - прайс лист

Ремонт выхлопной системы

Ремонт и замена глушителя

Замена гофры глушителя

Замена резинок глушителя

Замена средней части глушителя

Замена приемной трубы глушителя

Замена кольца глушителя

Замена прокладки катализатора

Замена заднего глушителя

      <input class="hide" id="hd-10" type="checkbox">
      Подвеска

Подвеска - прайс лист

Диагностика и ремонт ходовой

Диагностика подвески

Замена амортизаторов

Замена ступичного подшипника

Замена шаровой опоры

Замена стоек стабилизатора

Замена рычагов подвески

Замена сайлентблоков подвески

Замена и ремонт головок двигателя от 3000 руб.

  <button class="sidebar-button">Запрос цены и сроков</button>
```

Title: How to style dropdown flex-block so it wouldn't push content under him, but overlap it without position?

Body:
I fix your code. I use position absolute to resolve this problem

also, z-index is important

function myFunction() {
  var x = document.getElementById("dropdown");
  if (x.style.display === "none") {
    x.style.display = "flex";
  } else {
    x.style.display = "none";
  }
}

.dropdown-menu {
  display: flex;
  flex-wrap: wrap;
  max-width: 1240px;
  margin-left: auto;
  margin-right: auto;
  height: auto;
  background-color: #F3F3F3;
  border: 1px solid gray;
  justify-content: space-around;
  font-family: Arial, Helvetica, sans-serif;
  padding-bottom: 20px;
  box-sizing: border-box;
  gap: 10px;
  margin-bottom: 10px;
  margin-top: -20px;

  position: absolute;
  z-index: 2;
  max-width: 100%;
}

.dropdown-menu-column {
  display: flex;
  flex-direction: column;
  width: 200px;
}

.dropdown-menu-column-block {
  display: flex;
  flex-direction: column;
}

.dropdown-menu-column-block-header {
  font-size: 14px;
  line-height: 14px;
  font-weight: bold;
  color: #595959;
  background-color: #dedede;
  padding-top: 9px;
  padding-bottom: 9px;
  display: block;
  text-align: center;
  margin-bottom: 10px;
  padding-left: 10px;
  padding-right: 10px;
  margin-top: 15px;
}

.dropdown-menu-column-block-element a {
  font-size: 13px;
  line-height: 22px;
  color: #167491;
}

.hide {
  display: none;
}

.dropdown-menu {
  display: none;
}

.hide:checked+label+div {
  display: flex;
}

@media (max-width: 444px) {
  .hide,
  .hide+label~div {
    display: none;
  }
  .hide:checked+label+div {
    display: block;
  }
  .hide+label:before {
    background-color: #2CB1D9;
    color: black;
    content: "\002B";
    display: block;
    float: right;
    font-size: 14px;
    font-weight: bold;
    height: 16px;
    line-height: 16px;
    margin: 3px 5px;
    text-align: center;
    width: 16px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    border-radius: 50%;
    border: 1px solid black;
  }
  .hide:checked+label:before {
    content: "\2212";
  }
  .dropdown-menu {
    gap: 0px;
    padding-bottom: 0px;
  }
  .dropdown-menu-column {
    width: 100%;
  }
  .dropdown-menu-column-block-header {
    margin-bottom: 0px;
    margin-top: 0px;
  }
  .dropdown-menu-column-block {
    border: 1px solid #CDCDCD;
  }
  .dropdown-menu-column-block-element a {
    padding-left: 10px;
    display: inline-block;
  }
}

.header-flex {
  width: 100%;
  max-width: 1240px;
  display: flex;
  margin-left: auto;
  margin-right: auto;
  justify-content: space-between;
  border: 1px solid black;
  align-items: center;
  border: 1px solid #cecece;
  font-size: 18px;
  color: #1c1c1c;
  position: relative;
  height: 60px;
  box-sizing: border-box;
}

.article-header {
  font-size: 24px;
  font-weight: bold;
  padding-left: 10px;
}

.article-header-price {
  color: red;
  font-size: 24px;
  font-weight: bold;
}

.sidebar-button {
  font-size: 15px;
  line-height: 15px;
  font-weight: bold;
  color: #fff;
  text-align: center;
  background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/feedBackButton.png);
  height: 40px;
  width: 187px;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: #863e39;
  border-radius: 2px;
  cursor: pointer;
  display: block;
  margin-right: 20px;
}

.sidebar-button:hover {
  background-color: #1fa6ce;
  background-image: none;
}

.menu {
  display: flex;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  border: 1px dotted black;
  max-width: 1240px;
  color: white;
  font-size: 1rem;
  font-weight: bold;
  width: 100%;
  flex-wrap: nowrap;
  border-radius: 2px;
  margin-bottom: 20px;
  align-items: center;
  box-sizing: border-box;
  background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3.jpg');
  border: 0px;
  /*   border-bottom: 1px solid 167491; */
}

.menu-block:hover {
  background-image: url('https://pulam.ru/wp-content/themes/avtoservis/images/menuTop3-hover.jpg');
}

.menu-block {
  width: 33%;
  box-sizing: border-box;
  /*   padding: 10px 0;  */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.menu-block-3 {
  min-width: 33%;
  flex-basis: 33.5%;
  max-width: 34%;
}

.menu-block-divider {
  width: 1px;
  height: 35px;
  margin-left: 1px;
  margin-right: 1px;
  background-image: url(//pulam.ru/wp-content/themes/avtoservis/images/menuTop-li.gif);
}

<div class="menu" id="menuTop">
  <div class="menu-block">
    <div class="icon-1"><img src=""></div>
    <div class="menu-block-1">О сервисе</div>

  </div>
  <div class="menu-block-divider"></div>
  <div class="menu-block">
    <div class="icon-2"><img src=""></div>
    <div class="menu-block-2" onclick="myFunction()">
      Услуги и цены </div>

  </div>

  <div class="menu-block-divider"></div>
  <div class="menu-block menu-block-3">
    <div class="icon-3"><img src=""></div>
    <div class="menu-block-33">Контактная информация </div>
  </div>
</div>
<div class="dropdown-menu" id="dropdown">
  <div class="dropdown-menu-column column-1">
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-1" type="checkbox">
      <label for="hd-1" class="dropdown-menu-column-block-header">Техническое обслуживание авто</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Техническое обслуживание авто</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Акции</a></div>
      </div>
    </div>
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-2" type="checkbox">
      <label for="hd-2" class="dropdown-menu-column-block-header">Рулевое управление</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Рулевое управление - прайс лист</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт и замена рулевой рейки</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт гидроусилителя руля (ГУР)</a></div>
      </div>
      <div class="dropdown-menu-column-block">
        <input class="hide" id="hd-3" type="checkbox">
        <label for="hd-3" class="dropdown-menu-column-block-header">Трансмиссия</label>
        <div class="drodown-menu-column-block-element-hider">
          <div class="dropdown-menu-column-block-element"><a href="">Трансмиссия- прайс-лист</a></div>
          <div class="dropdown-menu-column-block-element"><a href="">Замена сцепления</a></div>
          <div class="dropdown-menu-column-block-element"><a href="">Стоимость и ремонт вариатора</a></div>
          <div class="dropdown-menu-column-block-element"><a href="">Диагноситка и ремонт РКПП</a></div>
          <div class="dropdown-menu-column-block-element"><a href="">Ремонт раздаточной кородки TOD</a></div>
        </div>
      </div>
    </div>
  </div>
  <div class="dropdown-menu-column column-2">
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-4" type="checkbox">
      <label for="hd-4" class="dropdown-menu-column-block-header">Двигатель</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Двигатель - прайс лист</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт турбин</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена маслосъемных колпачков</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт и замена головок</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена колец</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена двигателя</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена масла в двигателе</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена свечей накала</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт компонентов ГРМ</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена цепи ГРМ</a></div>
      </div>
    </div>
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-5" type="checkbox">
      <label for="hd-5" class="dropdown-menu-column-block-header">Топливная система</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Топливная система - прайс лист</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт топливной системы</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт инжекторной системы</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт узлов системы впрыска</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена и диагностика форсунок</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена топливного фильтра</a></div>
      </div>
    </div>
  </div>
  <div class="dropdown-menu-column column-3">
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-6" type="checkbox">
      <label for="hd-6" class="dropdown-menu-column-block-header">Система электрики</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Электрика - прайс лист</a></div>
      </div>
    </div>
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-7" type="checkbox">
      <label for="hd-7" class="dropdown-menu-column-block-header">Системы охлаждения</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Охлаждение - прайс лист</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена радиатора охлаждения</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена термостата</a></div>
      </div>
    </div>
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-8" type="checkbox">
      <label for="hd-8" class="dropdown-menu-column-block-header">Тормозная система</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Тормозная система - прайс-лист</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Тормозная система</a></div>
      </div>
    </div>
  </div>
  <div class="dropdown-menu-column column-4">
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-9" type="checkbox">
      <label for="hd-9" class="dropdown-menu-column-block-header">Выхлопная система</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Выхлопная система - прайс лист</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт выхлопной системы</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Ремонт и замена глушителя</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена гофры глушителя</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена резинок глушителя</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена средней части глушителя</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена приемной трубы глушителя</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена кольца глушителя</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена прокладки катализатора</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена заднего глушителя</a></div>
      </div>
    </div>
  </div>
  <div class="dropdown-menu-column column-5">
    <div class="dropdown-menu-column-block">
      <input class="hide" id="hd-10" type="checkbox">
      <label for="hd-10" class="dropdown-menu-column-block-header">Подвеска</label>
      <div class="drodown-menu-column-block-element-hider">
        <div class="dropdown-menu-column-block-element"><a href="">Подвеска - прайс лист</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Диагностика и ремонт ходовой</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Диагностика подвески</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена амортизаторов</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена ступичного подшипника</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена шаровой опоры</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена стоек стабилизатора</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена рычагов подвески</a></div>
        <div class="dropdown-menu-column-block-element"><a href="">Замена сайлентблоков подвески</a></div>
      </div>
    </div>
  </div>
</div>
<header class="header-flex">
  <div class="article-header">Замена и ремонт головок двигателя <span class="article-header-price">от 3000 руб.</span></div>
  <button class="sidebar-button">Запрос цены и сроков</button>
</header>


来源: stackexchange

问:
How to fix 'cannot initialize type TensorProto DataType' error while importing torch?
I installed pytorch using pip3 command for my windows pc without GPU support.
But when I tried to import torch it is giving an error.

At first, there was a different error saying numpy version not matching and I updated the numpy to the latest version.

```<code>import torch
RuntimeError                              Traceback (most recent call last)
<ipython-input-10-c031d3dd82fc> in <module>()
----> 1 import torch

C:\Users\iamuraptha\Anaconda3\lib\site-packages\torch\__init__.py in <module>()
     82     pass
     83
---> 84 from torch._C import *
     85
     86 __all__ += [name for name in dir(_C)

RuntimeError: generic_type: cannot initialize type "TensorProtoDataType": an object with that name is already defined
</code>```

答: If you are running this in colab, remember to restart your runtime after installing your modules with pip.</p>

ContentLicense: CC BY-SA 4.0

Body:
I installed pytorch using pip3 command for my windows pc without GPU support.
But when I tried to import torch it is giving an error.

At first, there was a different error saying numpy version not matching and I updated the numpy to the latest version.

import torch
RuntimeError                              Traceback (most recent call last)
<ipython-input-10-c031d3dd82fc> in <module>()
----> 1 import torch

C:\Users\iamuraptha\Anaconda3\lib\site-packages\torch\__init__.py in <module>()
     82     pass
     83
---> 84 from torch._C import *
     85
     86 __all__ += [name for name in dir(_C)

RuntimeError: generic_type: cannot initialize type "TensorProtoDataType": an object with that name is already defined


问:
Help! Key error in python
I keep getting this error:

```<code>MultiValueDictKeyError at /search/

"Key 'name' not found in <'QueryDict: {}>"
</code>```

I just started learning programming two days ago, so can someone explain in layman's terms why there's a problem and how to solve it. Thanks!

Here is the section of programming:

```<code>def NameAndOrCity(request):
    NoEntry = False
    if 'name' in request.GET and request.GET['name']:
        name = request.GET['name']
        if len(Business.objects.filter(name__icontains=name)) > 0:
            ByName = Business.objects.filter(name__icontains=name)
            q = set(ByName)
            del ByName
            ByName = q

    if 'city' in request.GET and request.GET['city']:
        city = request.GET['city']
        if len(Business.objects.filter(city__icontains=city)) > 0:
            ByCity = Business.objects.filter(city__contains=city)
            p = set(ByCity)
            del ByCity
            ByCity = p

    if len(q) > 0 and len(p) > 0:
            NameXCity = q & p
            return render_to_response('search_results.html', {'businesses':NameXCity, 'query':name})
        if len(q) > 0 and len(p) < 1:
            return render_to_response('search_results.html', {'businesses':ByName, 'query':name})
        if len(p) > 0 and len(q) < 1:
            return render_to_response('search_results.html', {'businesses':ByCity, 'query':city})
        else:
            NoResults = True
            return render_to_response('search_form.html', {'NoResults': NoResults})
    else:
        name = request.GET['name']
        city = request.GET['city']
        if len(name) < 1 and len(city) < 1:
            NoEntry = True
        return render_to_response('search_form.html', {'NoEntry': NoEntry})
</code>```

EDIT

1) Business.object is my database of businesses. They are objects with attributes like name, city, etc. I'm trying to make a program that will search the businesses by their attribute(s)

2) not a duplicate post

3) how do I check to see if those keys exist before I try to use them?

答:
It looks like the only place you could be getting this error is on this line:

```<code>name = request.GET['name']
</code>```

You haven't checked if 'name' is in the request.GET dictionary before trying to access it like you did above so you will get a key error if that key doesn't exist in request.GET.

So it looks like you need to change the following section to check if the 'name' and 'city' keys exist in your request.GET dictionary before you try accessing the values:

```<code>name = request.GET['name']
city = request.GET['city']
if len(name) < 1 and len(city) < 1:
    NoEntry = True
return render_to_response('search_form.html', {'NoEntry': NoEntry})
</code>```

ContentLicense: CC BY-SA 3.0

Title: Help! Key error in python

Body:
I keep getting this error:

MultiValueDictKeyError at /search/

"Key 'name' not found in <'QueryDict: {}>"

I just started learning programming two days ago, so can someone explain in layman's terms why there's a problem and how to solve it. Thanks!

Here is the section of programming:

def NameAndOrCity(request):
    NoEntry = False
    if 'name' in request.GET and request.GET['name']:
        name = request.GET['name']
        if len(Business.objects.filter(name__icontains=name)) > 0:
            ByName = Business.objects.filter(name__icontains=name)
            q = set(ByName)
            del ByName
            ByName = q

    if 'city' in request.GET and request.GET['city']:
        city = request.GET['city']
        if len(Business.objects.filter(city__icontains=city)) > 0:
            ByCity = Business.objects.filter(city__contains=city)
            p = set(ByCity)
            del ByCity
            ByCity = p

    if len(q) > 0 and len(p) > 0:
            NameXCity = q & p
            return render_to_response('search_results.html', {'businesses':NameXCity, 'query':name})
        if len(q) > 0 and len(p) < 1:
            return render_to_response('search_results.html', {'businesses':ByName, 'query':name})
        if len(p) > 0 and len(q) < 1:
            return render_to_response('search_results.html', {'businesses':ByCity, 'query':city})
        else:
            NoResults = True
            return render_to_response('search_form.html', {'NoResults': NoResults})
    else:
        name = request.GET['name']
        city = request.GET['city']
        if len(name) < 1 and len(city) < 1:
            NoEntry = True
        return render_to_response('search_form.html', {'NoEntry': NoEntry})

EDIT

1) Business.object is my database of businesses. They are objects with attributes like name, city, etc. I'm trying to make a program that will search the businesses by their attribute(s)

2) not a duplicate post

3) how do I check to see if those keys exist before I try to use them?

Body:
It looks like the only place you could be getting this error is on this line:

name = request.GET['name']

You haven't checked if 'name' is in the request.GET dictionary before trying to access it like you did above so you will get a key error if that key doesn't exist in request.GET.

So it looks like you need to change the following section to check if the 'name' and 'city' keys exist in your request.GET dictionary before you try accessing the values:

name = request.GET['name']
city = request.GET['city']
if len(name) < 1 and len(city) < 1:
    NoEntry = True
return render_to_response('search_form.html', {'NoEntry': NoEntry})


问:
Spring Boot not mapping controller paths after upgrade to 2.6.4
I have a Spring Boot application which I upgraded from 2.0.4 to 2.6.4, but since the update it doesn't appear to mapping ANY of the controller paths anymore.

Normally, at startup, the console output specifies every path that has been mapped, but it no longer does that and every URL I visit returns not found.

My controllers are all inside a package called 'controllers' inside the project, and they're all annotated with @Controller and @RequestMapping.

Here's a copy of my main application file.

```<code>@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
</code>```

After making a request, I see the following in the console output, it seems to be insinuating that it can't find the jsp files?

```<code>2022-02-07 17:11:56.998  WARN 29055 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : "Path with "WEB-INF" or "META-INF": [WEB-INF/view/app/login.jsp]"
2022-02-07 17:11:57.009  WARN 29055 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : "Path with "WEB-INF" or "META-INF": [WEB-INF/view/exception/error.jsp]"
</code>```

Does anyone know why this might be happening?

答:
I fixed this by re-adding the tomcat-embed-jasper dependency.</p>
```<code><dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
</code>```

Body:
I have a Spring Boot application which I upgraded from 2.0.4 to 2.6.4, but since the update it doesn't appear to mapping ANY of the controller paths anymore.

Normally, at startup, the console output specifies every path that has been mapped, but it no longer does that and every URL I visit returns not found.

My controllers are all inside a package called 'controllers' inside the project, and they're all annotated with @Controller and @RequestMapping.

Here's a copy of my main application file.

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

After making a request, I see the following in the console output, it seems to be insinuating that it can't find the jsp files?

2022-02-07 17:11:56.998  WARN 29055 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : "Path with "WEB-INF" or "META-INF": [WEB-INF/view/app/login.jsp]"
2022-02-07 17:11:57.009  WARN 29055 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler     : "Path with "WEB-INF" or "META-INF": [WEB-INF/view/exception/error.jsp]"

Does anyone know why this might be happening?

Body:
I fixed this by re-adding the tomcat-embed-jasper dependency.

<dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>


问:
How to save custom color on localStorage jquery?
I` have a function in jquery witch allow users to change background color of site. But if they refresh the page background-color go to default. How can i use LocalStorage with this jquery function

sessionStorage.setItem("bg_color", "#000");
let personName = sessionStorage.getItem("bg_color");

$(document).ready(function() {
    $('.dark__mode').click(function() {
        $('#headerCustomColor').css("background-color", personName);
        $('#TogleBarWi').css("color", "#fff");
        $('.custom_color_link').css("color", "#fff");
    });
});
```

答:
```<code>//You have to check if there is a certain background
// If there is a background color use it else use default
let background = localStorage.getItem("background") ? localStorage.getItem("background") : "#FFF";

// Change header on document loading the background color based on localStorage
$('#headerCustomColor').css("background-color", background);

// On click
$('.dark__mode').click(function() {
    // Set the variable background to custom
    background = "#383838";
    // Set localStorage bg color to custom
    // This is to enable on refresh so the new bg is set.
    localStorage.setItem("background", background);

    // Recolor the header after the click
    $('#headerCustomColor').css("background-color", background);

});
</code>```


问:
c++ template with partially fixed argument list
Consider a case like the following:

```<code>template<typename T>
class A { ... };

template<typename T, typename DataType = std::vector<A<T>>>
class B {
  ....
  DataType data;
  ...
}
</code>```

In my case the DataType type can be any std "container", but it must always be specialized with type A. The use of A should be transparent from outside class B, however in the definition of B without the default type for DataType one should explicitly specify e.g. B<int, std::deque<A<int>>. I'd like to remove this possibility and achieve something like:

```<code>template<typename T, typename container = std::vector>
class B{
  using DataType = container<A<T>>;
  ...
}
</code>```

so that I would specialize B like B<int, std::vector>.
Of course it cannot be exactly like this because container in this case should a complete type and then must be specialized. Is there a way to achieve this with c++14?

答:
You can do it with template template parameter, e.g.

```<code>template<typename T, template <typename...> typename container = std::vector>
class B {
  using DataType = container<A<T>>;
  ...
};
</code>```

Then use it like B<int> (i.e. B<int, std::vector>) or B<int, std::deque>.

Body:
Consider a case like the following:

template<typename T>
class A { ... };

template<typename T, typename DataType = std::vector<A<T>>>
class B {
  ....
  DataType data;
  ...
}

In my case the DataType type can be any std "container", but it must always be specialized with type A. The use of A should be transparent from outside class B, however in the definition of B without the default type for DataType one should explicitly specify e.g. B<int, std::deque<A<int>>. I'd like to remove this possibility and achieve something like:

template<typename T, typename container = std::vector>
class B{
  using DataType = container<A<T>>;
  ...
}

so that I would specialize B like B<int, std::vector>.
Of course it cannot be exactly like this because container in this case should a complete type and then must be specialized. Is there a way to achieve this with c++14?

Body:
You can do it with template template parameter, e.g.

template<typename T, template <typename...> typename container = std::vector>
class B {
  using DataType = container<A<T>>;
  ...
};

Then use it like B<int> (i.e. B<int, std::vector>) or B<int, std::deque>.


问:
Android Studio - RecyclerView with API level 19 (API 19)
I need to use RecyclerView with API 19 (API level 19).

I already have tried adding

```<code>implementation 'com.android.support:recyclerview-v7:+'
</code>```

and

```<code>implementation 'androidx.recyclerview:recyclerview:1.0.0'
</code>```

in build.gradle but no success. I am new to Android development. I have checked 3-4 similar questions but no solution worked for me.
Please if someone can tell me all of the changes I need to make in build.gradle, XML and/or in manifest file?

Thank you!

答:
I was able to run successfully after re-synching and re-building. If anyone faces this issue in future then add

```<code>implementation 'androidx.recyclerview:recyclerview:1.0.0'
</code>```

in build.gradle (Module) and then use

```<code><androidx.recyclerview.widget.RecyclerView
</code>```

in XML. You will have to sync because of the change in build.gradle.

Body:
I need to use RecyclerView with API 19 (API level 19).

I already have tried adding

implementation 'com.android.support:recyclerview-v7:+'

and

implementation 'androidx.recyclerview:recyclerview:1.0.0'

in build.gradle but no success. I am new to Android development. I have checked 3-4 similar questions but no solution worked for me.
Please if someone can tell me all of the changes I need to make in build.gradle, XML and/or in manifest file?

Thank you!

Body:
I was able to run successfully after re-synching and re-building. If anyone faces this issue in future then add

implementation 'androidx.recyclerview:recyclerview:1.0.0'

in build.gradle (Module) and then use

<androidx.recyclerview.widget.RecyclerView

in XML. You will have to sync because of the change in build.gradle.


问:
I want to query 3 Random Products from the Database everytime only 3
```<code>y = (Product.objects.all()).count()
    x = random.randint(3,y)
    prouct1 = Product.objects.get(id = x+1)
    prouct2 = Product.objects.get(id = x-1)
    prouct3 = Product.objects.get(id = x-2)
</code>```

I want to obtain 3 random products everytime i run a function initially i use the above method But the problem with this is If i delete a object Then i get the error i dont want that thing to happen obviously i can run more checks but i feel there is some simple way to do that The objective is to Get the random object from the  database every time the page is renderd

答:
Simply you can fetch random product by using .order_by('?'):

```<code>ran_prod = Product.objects.all().order_by('?')[:3]
</code>```

Note :

order_by('?') queries may be expensive and slow, depending on
the database backend you’re using.

Body:
y = (Product.objects.all()).count()
    x = random.randint(3,y)
    prouct1 = Product.objects.get(id = x+1)
    prouct2 = Product.objects.get(id = x-1)
    prouct3 = Product.objects.get(id = x-2)

I want to obtain 3 random products everytime i run a function initially i use the above method But the problem with this is If i delete a object Then i get the error i dont want that thing to happen obviously i can run more checks but i feel there is some simple way to do that The objective is to Get the random object from the  database every time the page is renderd

Body:
Simply you can fetch random product by using .order_by('?'):

ran_prod = Product.objects.all().order_by('?')[:3]

Note :

order_by('?') queries may be expensive and slow, depending on
the database backend you’re using.


问:
how to set CSS attributes of label in MVC 3
I am creating a static using Html.LabelFor(...).
I have to set Name attribute of the label dynamically using JQuery.</p>

答:
If I understand your question and comments together, you're just trying to change the text of a label.  The MVC LabelFor turns into an HTML  and that doesn't have any attributes like a text box does.

If you need to change it with JS/jQuery then give it an ID and use the html method.

Markup:

```<code>@Html.LabelFor(m => m.Something, new { id = "somethingLabel" })
@Html.TextBoxFor(m => m.Something)
</code>```

jQuery:

```<code>$("#somethingLabel").html("New Label Text");
</code>```

You could also use text instead of html - the difference is just that it escapes the input.

Body:
If I understand your question and comments together, you're just trying to change the text of a label.  The MVC LabelFor turns into an HTML <label> and that doesn't have any attributes like a text box does.

If you need to change it with JS/jQuery then give it an ID and use the html method.

Markup:

@Html.LabelFor(m => m.Something, new { id = "somethingLabel" })
@Html.TextBoxFor(m => m.Something)

jQuery:

$("#somethingLabel").html("New Label Text");

You could also use text instead of html - the difference is just that it escapes the input.


问:
How to update a single key value pair in an array of objects in react?
I am trying to update a single key value pair in an array of objets using React.

Here is the setup

An array of objects

const array = [
  {id:1,name:'Tyler',age:23},
  {id:2,name:'Lauren',age:28},
  {id:3,name:'Nico',age:14},
]
```
<p>Given an id and age, I want to be able to update the single object that matches the id. For example, given an id of 2 and age of 56, <code>{id:2,name:'Lauren',age:28}</code> should change to <code>{id:2,name:'Lauren',age:56}</code></p>
<h3>My approach</h3>
<p>I've set up useState to copy the array of object. However, I am struggling to filter out for the selected id, change the age, and return the updated array.</p>
<p>This is what I currently have:</p>
<pre class="lang-js prettyprint-override"><code>import { useState } from "react";

const array = [
  { id: 1, name: "Tyler", age: 23 },
  { id: 2, name: "Lauren", age: 28 },
  { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id = 2, age = 56) => {
    setList([...list, list.filter((item) => item.id === id)]);
  };

  return (
    <>
      <ul>
        {list.map((item) => {
          return (
            <li>
              {item.name} | {item.age}
            </li>
          );
        })}
      </ul>
      <button onClick={updateAge}>Update age</button>
    </>
  );
}

</code>```

Here is my codesandbox link

答:
```<code>import  { useState } from "react";
const array = [
 { id: 1, name: "Tyler", age: 23 },
 { id: 2, name: "Lauren", age: 28 },
 { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id, age) => {
    // Find the item to update and store it in new list
    let el = list.map((item) => {if(item.id === id){item.age=age}return
     item});
    // Set the previous list to the new list
    setList(el)
    console.log(list)

 };

 return (
   <>
     <ul>
       {list.map((item, index) => {
          return (
           <li key={index}>
             {item.name} | {item.age}
           </li>
         );
        })}
      </ul>
      <button onClick={()=>updateAge(2, 56)}>Update age</button>
    </>
  );
}
</code>```

Went to your codesandbox link changed it a bit does what you were trying to do now used Map instead of filter hope this helps

Body:
I am trying to update a single key value pair in an array of objets using React.

Here is the setup

An array of objects

const array = [
  {id:1,name:'Tyler',age:23},
  {id:2,name:'Lauren',age:28},
  {id:3,name:'Nico',age:14},
]

Given an id and age, I want to be able to update the single object that matches the id. For example, given an id of 2 and age of 56, {id:2,name:'Lauren',age:28} should change to {id:2,name:'Lauren',age:56}

My approach

I've set up useState to copy the array of object. However, I am struggling to filter out for the selected id, change the age, and return the updated array.

This is what I currently have:

import { useState } from "react";

const array = [
  { id: 1, name: "Tyler", age: 23 },
  { id: 2, name: "Lauren", age: 28 },
  { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id = 2, age = 56) => {
    setList([...list, list.filter((item) => item.id === id)]);
  };

  return (
    <>

        {list.map((item) => {
          return (

              {item.name} | {item.age}

          );
        })}

      <button onClick={updateAge}>Update age</button>
    </>
  );
}

Here is my codesandbox link

Body:
import  { useState } from "react";
const array = [
 { id: 1, name: "Tyler", age: 23 },
 { id: 2, name: "Lauren", age: 28 },
 { id: 3, name: "Nico", age: 14 }
];

export default function App() {
  const [list, setList] = useState(array);

  const updateAge = (id, age) => {
    // Find the item to update and store it in new list
    let el = list.map((item) => {if(item.id === id){item.age=age}return
     item});
    // Set the previous list to the new list
    setList(el)
    console.log(list)

 };

 return (
   <>
     <ul>
       {list.map((item, index) => {
          return (
           <li key={index}>
             {item.name} | {item.age}
           </li>
         );
        })}
      </ul>
      <button onClick={()=>updateAge(2, 56)}>Update age</button>
    </>
  );
}

Went to your codesandbox link changed it a bit does what you were trying to do now used Map instead of filter hope this helps


答:
Hard to say without exact definition of underlying table and and objective of the query.

You need two levels of aggregation in any case. And you can probably largely simplify:

SELECT sub.id, sub."firstName"
     , jsonb_agg(jsonb_build_object('yearId', sub."yearId"
                                  , 'classes', sub.classes)) AS years
FROM  (
   SELECT s.id, s."firstName", cy."yearId"
        , jsonb_agg(jsonb_build_object('classId', cy."classId")) AS classes
   FROM   users s
   LEFT   JOIN "classYearStudents" cys ON cys."studentId" = s.id
   LEFT   JOIN "classYears"        cy  ON cy.id = cys."classYearId"
   GROUP  BY s.id, cy."yearId"
   ) sub
GROUP BY sub.id, sub."firstName";
```

Not sure if and where you need DISTINCT in this query.

I kept the user ID in the result, as first names are hardly unique.

Don't use CaMeL-case identifiers with Postgres if you can avoid it. See:

Are PostgreSQL column names case-sensitive?

Title: Nested aggregation with `jsonb_agg`

Body:
SELECT
  s."firstName",
  jsonb_agg(
    DISTINCT jsonb_build_object(
      'yearId',
      y.id,
      'classes',
      (
        SELECT
          jsonb_agg(
            jsonb_build_object(
              'classId',
              c.id
            )
          )
        FROM
          classes AS c
        WHERE
          y.id = cy."yearId"
          AND c.id = cy."classId"
          AND s.id = cys."studentId"
      )
    )
  ) AS years
FROM
  users AS s
  LEFT JOIN "classYearStudents" AS cys ON cys."studentId" = s.id
  LEFT JOIN "classYears" AS cy ON cy.id = cys."classYearId"
  LEFT JOIN "years" AS y ON y.id = cy."yearId"
GROUP BY
  s.id

SQL Output

 firstName |                                                                                years
-----------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Jarrell   | [{"yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039", "classes": [{"classId": "2590b596-e894-4af5-8ac5-68d109eee995"}]}, {"yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039", "classes": [{"classId": "fe4a11f2-5f38-4f7a-bbce-609bc7ad8f99"}]}]
 Kevon     | [{"yearId": "7f5789b5-999e-45e4-aba4-9f45b29a69ef", "classes": [{"classId": "c8cda7d1-7321-443c-b0ad-6d18451613b5"}]}, {"yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039", "classes": [{"classId": "2590b596-e894-4af5-8ac5-68d109eee995"}]}, {"yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039", "classes": [{"classId": "fe4a11f2-5f38-4f7a-bbce-609bc7ad8f99"}]}]
 Antone    | [{"yearId": "7f5789b5-999e-45e4-aba4-9f45b29a69ef", "classes": [{"classId": "c8cda7d1-7321-443c-b0ad-6d18451613b5"}]}, {"yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039", "classes": [{"classId": "2590b596-e894-4af5-8ac5-68d109eee995"}]}, {"yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039", "classes": [{"classId": "fe4a11f2-5f38-4f7a-bbce-609bc7ad8f99"}]}]
(3 rows)

The problem

What I wanted was for the years with the same ID to be merged together and have multiple classes per year id. As you can see bd5b69ac-6638-4d3e-8a52-94c24ed9a039 on the first row (Jarell) has two entries in the year's column array with each having one class.

Current JSON output

[
  {
    "yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039",
    "classes": [{ "classId": "2590b596-e894-4af5-8ac5-68d109eee995" }]
  },
  {
    "yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039",
    "classes": [{ "classId": "fe4a11f2-5f38-4f7a-bbce-609bc7ad8f99" }]
  }
]

Desired output

[
  {
    "yearId": "bd5b69ac-6638-4d3e-8a52-94c24ed9a039",
    "classes": [
      { "classId": "2590b596-e894-4af5-8ac5-68d109eee995" },
      { "classId": "fe4a11f2-5f38-4f7a-bbce-609bc7ad8f99" }
    ]
  }
]

Is this possible?

Body:
Hard to say without exact definition of underlying table and and objective of the query.

You need two levels of aggregation in any case. And you can probably largely simplify:

SELECT sub.id, sub."firstName"
     , jsonb_agg(jsonb_build_object('yearId', sub."yearId"
                                  , 'classes', sub.classes)) AS years
FROM  (
   SELECT s.id, s."firstName", cy."yearId"
        , jsonb_agg(jsonb_build_object('classId', cy."classId")) AS classes
   FROM   users s
   LEFT   JOIN "classYearStudents" cys ON cys."studentId" = s.id
   LEFT   JOIN "classYears"        cy  ON cy.id = cys."classYearId"
   GROUP  BY s.id, cy."yearId"
   ) sub
GROUP BY sub.id, sub."firstName";

Not sure if and where you need DISTINCT in this query.

I kept the user ID in the result, as first names are hardly unique.

Don't use CaMeL-case identifiers with Postgres if you can avoid it. See:

Are PostgreSQL column names case-sensitive?


问:
Use column value as column name to create a cross-tab
I have a long table with groups of rows that look like this. Essentially, I'd like to use the value stored in v1 to rename v1_hasvalue, and likewise for v2.

```<code>v1 <- rep(c("varA"), 4)
v2 <- rep(c("varB"), 4)
v1_hasvalue <- c(1,1,0,0)
v2_hasvalue <- c(1,0,1,0)
n <- c(100, 20, 30, 40)

have <- data.frame(v1, v2, v1_hasvalue, v2_hasvalue, n)
</code>```

How can I go from this:

```<code>  v1 v2 v1_hasvalue v2_hasvalue   n
1  A  B           1           1 100
2  A  B           1           0  20
3  A  B           0           1  30
4  A  B           0           0  40

</code>```

to this:

```<code>  varA varB   n
1    1    1 100
2    1    0  20
3    0    1  30
4    0    0  40
</code>```

答:
We may rename the columns as

```<code>names(have)[3:4] <- unlist(have[1, 1:2])
have <- have[-(1:2)]
</code>```

-output

```<code>> have
  varA varB   n
1    1    1 100
2    1    0  20
3    0    1  30
4    0    0  40
</code>```

Body:
I have a long table with groups of rows that look like this. Essentially, I'd like to use the value stored in v1 to rename v1_hasvalue, and likewise for v2.

v1 <- rep(c("varA"), 4)
v2 <- rep(c("varB"), 4)
v1_hasvalue <- c(1,1,0,0)
v2_hasvalue <- c(1,0,1,0)
n <- c(100, 20, 30, 40)

have <- data.frame(v1, v2, v1_hasvalue, v2_hasvalue, n)

How can I go from this:

  v1 v2 v1_hasvalue v2_hasvalue   n
1  A  B           1           1 100
2  A  B           1           0  20
3  A  B           0           1  30
4  A  B           0           0  40

to this:

  varA varB   n
1    1    1 100
2    1    0  20
3    0    1  30
4    0    0  40

Body:
We may rename the columns as

names(have)[3:4] <- unlist(have[1, 1:2])
have <- have[-(1:2)]

-output

> have
  varA varB   n
1    1    1 100
2    1    0  20
3    0    1  30
4    0    0  40


问:
npm ERR! Cannot read properties of null (reading 'pickAlgorithm')
iam getting below error with npm while creating react app

npm ERR! Cannot read properties of null (reading 'pickAlgorithm')

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Nagamanickam\AppData\Local\npm-cache_logs\2021-11-18T12_01_45_525Z-debug.log

答: I resolved it by deleting node_modules and package-lock.json and run npm install again.


问:
Windows Form application could not find axWindowsMediaPlayer
I have created a windows form applicaiton. In fact is a video player(media player) and buttons play stop pause etc. I have designed everything and it was working smoothly until 1hour ago. From that time I am receiving the following message in the form design . The message depicted in the following image:

How can I overcome that issue?

In the designer script I am having:

```<code>private AxWMPLib.AxWindowsMediaPlayer axWindowsMediaPlayer1;
</code>```

My issue began when I tried to create a second form in the same project. When I deleted the second form suddenly I got that message in my first form.

答:
I also had the same problem, after I upgraded VS 2019 to 2022.

My project was built in 2019. What I had done was I closed the main project and opened a new project, then I added Windows Media Player to the project.

That went ahead normally.

I then closed the project and opened a previously loaded project and it worked fine, under VS 2019. (I did this without closing VS' main window. I closed projects using the File menu.)

Body:
I have created a windows form applicaiton. In fact is a video player(media player) and buttons play stop pause etc. I have designed everything and it was working smoothly until 1hour ago. From that time I am receiving the following message in the form design . The message depicted in the following image:

How can I overcome that issue?

In the designer script I am having:

private AxWMPLib.AxWindowsMediaPlayer axWindowsMediaPlayer1;

My issue began when I tried to create a second form in the same project. When I deleted the second form suddenly I got that message in my first form.


问:
Initialising a C vector pointer throws a bus error but initialising a vector doesn't
This C code:

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

typedef struct
{
    int *a;
    int sz, cap;
} Vector;

void vector_init(Vector *v)
{
    v->a = (int *)malloc(sizeof(int));
    v->sz = 0;
    v->cap = 1;
}

int main()
{
    Vector *v;
    vector_init(v);
}
</code>```

throws a bus error.
but replacing Vector *v with Vector v and vector_init(v) with vector_init(&v) solves it. why?

答:
Design your API to parallel malloc() and free()

The way to handle objects in C is to take a pointer on create and pass a pointer on destroy. That is, you should write functions that parallel malloc() and free() (or, in my personal preference, free-and-null):

```<code>Vector * Vector_create( size_t size );
Vector * Vector_destroy( Vector * v );
</code>```

They are used thus:

```<code>Vector * v0   = Vector_create( 0 );    // create an empty vector
Vector * v100 = Vector_create( 100 );  // create a vector with 100 elements
</code>```

```<code>v0 = Vector_destroy( v0 );  // free and null
Vector_destroy( v100 );     // zeroing your pointer is optional
</code>```

Useful operations on your vector should likewise have proper signatures:

```<code>Vector * Vector_copy( Vector * v );  // deep copy a vector
int * Vector_at( Vector * v, size_t index );  // etc
void Vector_push_back( Vector * v, int x );  // may resize the vector!
</code>```

```<code>Vector * v2 = Vector_copy( v );  // create new vector v2 == v
*Vector_at( v, 7 ) = 123456;     // assign value to v[7] = 123456
Vector_push_back( v, 42 );       // increase size of v and assign 42 to new element (possible capacity change)
</code>```

FAM

Depending on the object, I sometimes like to do as 0___________ did in his answer (use a flexible array member), but this does complicate your calling code a little because it removes a level of indirection — you must now pass references to your object as argument to every function (for consistency, even for functions that don’t need it, because some do!):

```<code>Vector * v = Vector_create( 0 );
Vector_push_back( &v, 42 );  // because v may be reallocated!
printf( "%d\n", *Vector_at( &v, 0 ) );
free( v );  // this might still be worth hiding behind a Vector_free() function
</code>```

Body:
This C code:

#include <stdlib.h>

typedef struct
{
    int *a;
    int sz, cap;
} Vector;

void vector_init(Vector *v)
{
    v->a = (int *)malloc(sizeof(int));
    v->sz = 0;
    v->cap = 1;
}

int main()
{
    Vector *v;
    vector_init(v);
}

throws a bus error.
but replacing Vector *v with Vector v and vector_init(v) with vector_init(&v) solves it. why?

Body:
Design your API to parallel malloc() and free()

The way to handle objects in C is to take a pointer on create and pass a pointer on destroy. That is, you should write functions that parallel malloc() and free() (or, in my personal preference, free-and-null):

Vector * Vector_create( size_t size );
Vector * Vector_destroy( Vector * v );

They are used thus:

Vector * v0   = Vector_create( 0 );    // create an empty vector
Vector * v100 = Vector_create( 100 );  // create a vector with 100 elements

v0 = Vector_destroy( v0 );  // free and null
Vector_destroy( v100 );     // zeroing your pointer is optional

Useful operations on your vector should likewise have proper signatures:

Vector * Vector_copy( Vector * v );  // deep copy a vector
int * Vector_at( Vector * v, size_t index );  // etc
void Vector_push_back( Vector * v, int x );  // may resize the vector!

Vector * v2 = Vector_copy( v );  // create new vector v2 == v
*Vector_at( v, 7 ) = 123456;     // assign value to v[7] = 123456
Vector_push_back( v, 42 );       // increase size of v and assign 42 to new element (possible capacity change)

FAM

Depending on the object, I sometimes like to do as 0___________ did in his answer (use a flexible array member), but this does complicate your calling code a little because it removes a level of indirection — you must now pass references to your object as argument to every function (for consistency, even for functions that don’t need it, because some do!):

Vector * v = Vector_create( 0 );
Vector_push_back( &v, 42 );  // because v may be reallocated!
printf( "%d\n", *Vector_at( &v, 0 ) );
free( v );  // this might still be worth hiding behind a Vector_free() function


问:
Signature not showing up in outlook after creating macro in excel
I have been trying to create an automailer in excel but the signature does not come up when I try to send it out. This is the VB script:</p>
```<code>Sub Send_email_fromexcel()
    Dim OApp As Outlook.Application, outlookmailitem As Outlook.MailItem, signature As String
    Dim edress As String
    Dim subj As String
    Dim message As String
    Dim filename As String
    Dim OApp As Object
    Dim outlookmailitem As Object
    Dim signature As String
    Dim myAttachments As Object
    Dim path As String
    Dim lastrow As Integer
    Dim attachment As String
    Dim x As Integer

     x = 2

    Do While Sheet1.Cells(x, 1) <> ""

        Set OApp = CreateObject("Outlook.Application")
        Set outlookmailitem = OApp.createitem(0)
        Set myAttachments = outlookmailitem.Attachments
        path = "H:\Marketing\"

        edress = Sheet1.Cells(x, 1)
        cc = Sheet1.Cells(x, 3)
        subj = Sheet1.Cells(x, 4)
        filename = Sheet1.Cells(x, 5)
        body = Sheet1.Cells(x, 6)
        attachment = path + filename
        signature = outlookmailitem.body

    'With outlookmailitem
            outlookmailitem.To = edress
            outlookmailitem.cc = cc
            outlookmailitem.bcc = ""
            outlookmailitem.Subject = subj
            myAttachments.Add (attachment)
            outlookmailitem.display
            outlookmailitem.body = body & vbNewLine & signature

           ' outlookmailitem.send

            lastrow = lastrow + 1
            edress = ""
        x = x + 1
    Loop
    Set OApp = Nothing
    Set outlookmailitem = Nothing

End Sub
</code>```

答:
In the code you are using a plain text string which represents a message body:

```<code>signature = outlookmailitem.body
'...
outlookmailitem.body = body & vbNewLine & signature
</code>```

Most probably you wanted to use the HTMLBody property which returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately.

Also you may try to call the Display method before getting the  signature from the message body.

Body:
I have been trying to create an automailer in excel but the signature does not come up when I try to send it out. This is the VB script:

Sub Send_email_fromexcel()
    Dim OApp As Outlook.Application, outlookmailitem As Outlook.MailItem, signature As String
    Dim edress As String
    Dim subj As String
    Dim message As String
    Dim filename As String
    Dim OApp As Object
    Dim outlookmailitem As Object
    Dim signature As String
    Dim myAttachments As Object
    Dim path As String
    Dim lastrow As Integer
    Dim attachment As String
    Dim x As Integer

     x = 2

    Do While Sheet1.Cells(x, 1) <> ""

        Set OApp = CreateObject("Outlook.Application")
        Set outlookmailitem = OApp.createitem(0)
        Set myAttachments = outlookmailitem.Attachments
        path = "H:\Marketing\"

        edress = Sheet1.Cells(x, 1)
        cc = Sheet1.Cells(x, 3)
        subj = Sheet1.Cells(x, 4)
        filename = Sheet1.Cells(x, 5)
        body = Sheet1.Cells(x, 6)
        attachment = path + filename
        signature = outlookmailitem.body

    'With outlookmailitem
            outlookmailitem.To = edress
            outlookmailitem.cc = cc
            outlookmailitem.bcc = ""
            outlookmailitem.Subject = subj
            myAttachments.Add (attachment)
            outlookmailitem.display
            outlookmailitem.body = body & vbNewLine & signature

           ' outlookmailitem.send

            lastrow = lastrow + 1
            edress = ""
        x = x + 1
    Loop
    Set OApp = Nothing
    Set outlookmailitem = Nothing

End Sub

Body:
In the code you are using a plain text string which represents a message body:

signature = outlookmailitem.body
'...
outlookmailitem.body = body & vbNewLine & signature

Most probably you wanted to use the HTMLBody property which returns or sets a string representing the HTML body of the specified item. Setting the HTMLBody property will always update the Body property immediately.

Also you may try to call the Display method before getting the  signature from the message body.