问:
Pay as you go with Paypal
I want to implement a pay as you go with Paypal, as I read the subscriptions API we need to create a plan and product, and as I understand it, it works based on the regular payments which obviously we don't want that we want if the user's budget is below a certain amount we recharge the user by a fixed amount again, can anybody guide me how to approach and implement pay as go using Paypal?

答:
You are correct, subscriptions bill on a regular schedule whereas what you are describing is the ability to bill an arbitrary amount at any time.

That feature is called "reference transactions", or sometimes "billing agreements". It is not enabled for PayPal business accounts by default. To request the feature, the owner of the PayPal account should contact PayPal's general business support (note: not technical support) and explain the business need for this reference transactions feature.

If it's approved for the account, PayPal can then guide you on which API integration to use; potentially something like the newest v2/vault.

Title: Pay as you go with Paypal


来源: stackexchange

问:
Is it possible to define default value in Sequelize migration?
There is no documentation details about addColumn options, so I'm trying this:

```<code>queryInterface.addColumn('OrderBackups', 'my_column', Sequelize.INTEGER, { defaultValue: 0 })
</code>```

and it does not work.
ps: I'm using postgres

答: addColumn method doesn't support defaultValue option for Postgres. It only works for MSSQL. Check these docs</p>

ContentLicense: CC BY-SA 4.0

Body:
There is no documentation details about addColumn options, so I'm trying this:

queryInterface.addColumn('OrderBackups', 'my_column', Sequelize.INTEGER, { defaultValue: 0 })

and it does not work.
ps: I'm using postgres


问:
How to create a graph chart without using Libraries (Matplotlib) in Python?
I'm new to python. In an interview, the Hr ask me to create the Graph chart without using the Library like matplotlib. I tried a few ways but it does not work for me I've not cleared the interview as well. And people if you know how to make the graph like mentioned below without using a lib. Please share with me. any kind of suggestion is appreciatable.

答:
HHhhmmm.  Sounds like somebody is trying to check your ability to think outside the box and/or your knowledge of print formatting since it is never a good idea to reinvent the wheel on not use a better solution that already exists.  I generated some random numbers and 'plotted' a * using print statements.
I included a Matplotlib plot just to check how close it was.  You could add some code to calculate the derivative and change the symbol based on that.

```<code>import math
import random
import matplotlib.pyplot as plt
x=range(50)
y= [random.randrange(0,5) for i in range(50)]

for yindex in range(5,-1,-1):
    for xindex in range(0,50,1):
        if y[xindex] == yindex:
            print("*", end='')
        else:
            print(" ", end='')
    print()

fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
</code>```

plot

Body:
HHhhmmm.  Sounds like somebody is trying to check your ability to think outside the box and/or your knowledge of print formatting since it is never a good idea to reinvent the wheel on not use a better solution that already exists.  I generated some random numbers and 'plotted' a * using print statements.
I included a Matplotlib plot just to check how close it was.  You could add some code to calculate the derivative and change the symbol based on that.

import math
import random
import matplotlib.pyplot as plt
x=range(50)
y= [random.randrange(0,5) for i in range(50)]

for yindex in range(5,-1,-1):
    for xindex in range(0,50,1):
        if y[xindex] == yindex:
            print("*", end='')
        else:
            print(" ", end='')
    print()

fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()

plot


问:
Behavior of scrollIntoViewIfNeeded
I'm working on creating a web component that, given a list of elements that are focusable, automatically has accessible keyboard navigation.

Part of that is to have the active element scrolled into view if it isn't already, and to do this i'm using the Element.scrollIntoViewIfNeeded (in chrome, so support shouldn't be a problem).

I'm experiencing some weird behavior, that i can't quite figure out. I've created a minimal code sandbox to show the problem.

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next.focus();
        next.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        first.focus();
        first.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous.focus();
        previous.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last.focus();
        last.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}</code>```

<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

```

the centerIfNeeded argument doesn't seem to be respected at all. At times it is respected the first time i focus an element that is outside of the viewport, but not the second time, and sometimes it is just completely ignored.

Is this expected behavior?

答:
The problem is that by default the focus() call will itself internally call scrollIntoView(), and the two calls will conflict.

To prevent that, you can pass the { preventScroll: true } option to your calls to focus().

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next?.focus({ preventScroll: true });
        next?.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        next?.focus({ preventScroll: true });
        first?.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous?.focus({ preventScroll: true });
        previous?.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last?.focus({ preventScroll: true });
        last?.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}</code>```

<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

```

Title: Behavior of scrollIntoViewIfNeeded

Body:
I'm working on creating a web component that, given a list of elements that are focusable, automatically has accessible keyboard navigation.

Part of that is to have the active element scrolled into view if it isn't already, and to do this i'm using the Element.scrollIntoViewIfNeeded (in chrome, so support shouldn't be a problem).

I'm experiencing some weird behavior, that i can't quite figure out. I've created a minimal code sandbox to show the problem.

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next.focus();
        next.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        first.focus();
        first.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous.focus();
        previous.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last.focus();
        last.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);

body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}

<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

the centerIfNeeded argument doesn't seem to be respected at all. At times it is respected the first time i focus an element that is outside of the viewport, but not the second time, and sometimes it is just completely ignored.

Is this expected behavior?

Body:
The problem is that by default the focus() call will itself internally call scrollIntoView(), and the two calls will conflict.

To prevent that, you can pass the { preventScroll: true } option to your calls to focus().

const app = document.getElementById("app");

for (var i = 0; i < 100; i++) {
  const paragraph = document.createElement("p");
  paragraph.innerHTML = "element " + i;
  paragraph.tabIndex = -1;
  app.appendChild(paragraph);
}

const handleKeyDown = (event) => {
  event.preventDefault();

  switch (event.key) {
    case "ArrowDown":
      if (app.contains(document.activeElement)) {
        const next = document.activeElement.nextElementSibling;
        next?.focus({ preventScroll: true });
        next?.scrollIntoViewIfNeeded(false);
      } else {
        const first = app.firstElementChild;
        next?.focus({ preventScroll: true });
        first?.scrollIntoViewIfNeeded(false);
      }
      break;
    case "ArrowUp":
      if (app.contains(document.activeElement)) {
        const previous = document.activeElement.previousElementSibling;
        previous?.focus({ preventScroll: true });
        previous?.scrollIntoViewIfNeeded(false);
      } else {
        const last = app.lastElementChild;
        last?.focus({ preventScroll: true });
        last?.scrollIntoViewIfNeeded(false);
      }
      break;
    default:
      break;
  }
};

document.addEventListener("keydown", handleKeyDown, false);

body {
  font-family: sans-serif;
}

.app {
  display: flex;
  flex-direction: column;
}

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app" class="app"></div>

    <script src="src/index.js"></script>
  </body>
</html>


问:
How to open single accordion panel in mobile, and multiple panels in desktop using JS media queries (matchMedia())?
In the snippet below, I have an accordion. My goal is to be able to open a single panel at a time in media queries less than 992px. In media queries greater than 992px, I want to be able to open multiple panels at once.

Part of this is working at the mobile size (I can open the panel, but can't close it). And at desktop, it's not opening at all. I'm not sure where I'm going wrong.

How to control accordion panel open/close behavior based on media queries?

function initAccordion() {
  function handlePanelClick(event) {
    showPanel(event.currentTarget);
  }

  function showPanel(panelHeader) {
    let isActive,
      panel = panelHeader.parentNode,
      expandedPanel = document.querySelector(".panel.active");
    mqTablet = window.matchMedia('(min-width: 992px)');

    isActive = expandedPanel && panel.classList.contains("active") ? true : false;

    if (mqTablet.matches && expandedPanel) {
      expandedPanel.querySelector(".acc-body").style.height = null;
      expandedPanel.classList.remove("active");
    }

    if (!mqTablet.matches && panel && !isActive) {
      panel.classList.add('active');
    }

  }

  let allPanelElements = document.querySelectorAll(".panel");

  for (let i = 0; i < allPanelElements.length; i++) {
    allPanelElements[i]
      .querySelector(".acc-trigger")
      .addEventListener("click", handlePanelClick);
  }

  showPanel(allPanelElements);
}

initAccordion(document.getElementsByClassName("accordion"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
  margin: 50px auto 0;
  display: flex;
  flex-direction: column;
}

.wrapper a {
  text-decoration: none;
}

.wrapper button {
  border-style: none;
  background: white;
}

.wrapper button::-moz-focus-inner {
  border: 0;
}

.wrapper .accordion {
  margin: 0 0.1rem;
}

.wrapper .accordion .panel {
  min-height: 4rem;
  margin: 0 0.1rem;
}

.wrapper .accordion .panel .acc-trigger {
  display: block;
  font-weight: 400;
  margin: 0;
  padding: 0.5em 0;
  position: relative;
  text-align: left;
  width: 100%;
  cursor: pointer;
  background: 0 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title {
  display: flex;
  align-items: center;
  border: transparent 2px solid;
  outline: 0;
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
  transition: all 0.2s ease;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4 {
  font-weight: 800;
  color: #000A70;
  font-size: 1.25rem;
  justify-content: space-between;
  margin-right: 1rem;
  outline: 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4:hover {
  color: #005fec;
}

.wrapper .accordion .panel .acc-trigger .acc-title svg.acc-icon {
  cursor: pointer;
  pointer-events: none;
  margin-left: auto;
  z-index: 3;
}

.wrapper .accordion .panel .acc-body {
  height: 0;
  opacity: 0;
  overflow: hidden;
  visibility: hidden;
  transition: height 0.2s ease-out, opacity 0.2s ease-out;
}

.wrapper .accordion .panel .acc-body ol.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
  counter-reset: my-awesome-counter;
}

.wrapper .accordion .panel .acc-body ol.custom-list li {
  counter-increment: my-awesome-counter;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
  color: #000A70;
}

.wrapper .accordion .panel .acc-body ol.custom-list li::before {
  content: counter(my-awesome-counter) ". ";
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li {
  background-image: url(/assets/svg/bullet.svg);
  background-position: 0 0.5rem;
  background-repeat: no-repeat;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel.active .acc-body {
  opacity: 1;
  height: auto;
  padding: 0.5rem 0;
  visibility: visible;
}

.wrapper .accordion .panel.active .acc-body p {
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel.active .acc-body p+.embed-youtube {
  margin: 1rem 0;
}

.wrapper .accordion .panel.active .acc-body p a {
  color: #005fec;
}

.wrapper .accordion .panel.active .acc-body p a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel.active .acc-icon {
  transform: rotate(180deg);
}

.wrapper .accordion .panel.active .acc-trigger .acc-title {
  border-bottom: 0;
}

.wrapper .accordion .panel.active .acc-trigger .acc-title h4 {
  color: #005fec;
}

.wrapper .accordion .panel.active p:last-child {
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
}

.acc-title svg.acc-icon {
  transition: all 0.2s ease;
  min-width: 1rem;
}

@media (min-width: 768px) {
  .wrapper {
    flex-direction: row;
  }
  .accordion {
    flex: 1;
  }
}</code>```

Any Questions?

            <button class="acc-trigger">

Lorem ipsum dolor sit amet.

                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>

              </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

            <button class="acc-trigger">

Lorem ipsum dolor sit amet.

                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>

              </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

```

答:
You are clubbing many conditions in if statements. Lets simplify things a little bit:

function initAccordion() {
  function handlePanelClick(event) {
    showPanel(event.currentTarget.parentNode);
  }

  function showPanel(panel) {
    let isWide = isWideScreen();
    let isActive = panel.classList.contains("active");

    // handle wide screens
    if (isWide) {
      if (!isActive) { // open the panel
        panel.classList.add('active');
      } else {
        panel.classList.remove('active');
      }
    } else { // handle mobiles
      let panels = document.querySelectorAll('.panel');
      panels.forEach(p => p.classList.remove('active'));
      if (!isActive) { // open the panel
        panel.classList.add('active');
      }
    }
  }

  let allPanelElements = document.querySelectorAll(".panel");
  allPanelElements.forEach(pe => pe.querySelector(".acc-trigger")
    .addEventListener("click", handlePanelClick));

  /*if (isWideScreen()) {
    showPanel(allPanelElements[0]);
  }*/

}

function isWideScreen() {
  return window.matchMedia('(min-width: 992px)').matches;
}
initAccordion(document.getElementsByClassName("accordion"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
  margin: 50px auto 0;
  display: flex;
  flex-direction: column;
}

.wrapper a {
  text-decoration: none;
}

.wrapper button {
  border-style: none;
  background: white;
}

.wrapper button::-moz-focus-inner {
  border: 0;
}

.wrapper .accordion {
  margin: 0 0.1rem;
}

.wrapper .accordion .panel {
  min-height: 4rem;
  margin: 0 0.1rem;
}

.wrapper .accordion .panel .acc-trigger {
  display: block;
  font-weight: 400;
  margin: 0;
  padding: 0.5em 0;
  position: relative;
  text-align: left;
  width: 100%;
  cursor: pointer;
  background: 0 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title {
  display: flex;
  align-items: center;
  border: transparent 2px solid;
  outline: 0;
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
  transition: all 0.2s ease;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4 {
  font-weight: 800;
  color: #000A70;
  font-size: 1.25rem;
  justify-content: space-between;
  margin-right: 1rem;
  outline: 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4:hover {
  color: #005fec;
}

.wrapper .accordion .panel .acc-trigger .acc-title svg.acc-icon {
  cursor: pointer;
  pointer-events: none;
  margin-left: auto;
  z-index: 3;
}

.wrapper .accordion .panel .acc-body {
  height: 0;
  opacity: 0;
  overflow: hidden;
  visibility: hidden;
  transition: height 0.2s ease-out, opacity 0.2s ease-out;
}

.wrapper .accordion .panel .acc-body ol.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
  counter-reset: my-awesome-counter;
}

.wrapper .accordion .panel .acc-body ol.custom-list li {
  counter-increment: my-awesome-counter;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
  color: #000A70;
}

.wrapper .accordion .panel .acc-body ol.custom-list li::before {
  content: counter(my-awesome-counter) ". ";
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li {
  background-image: url(/assets/svg/bullet.svg);
  background-position: 0 0.5rem;
  background-repeat: no-repeat;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel.active .acc-body {
  opacity: 1;
  height: auto;
  padding: 0.5rem 0;
  visibility: visible;
}

.wrapper .accordion .panel.active .acc-body p {
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel.active .acc-body p+.embed-youtube {
  margin: 1rem 0;
}

.wrapper .accordion .panel.active .acc-body p a {
  color: #005fec;
}

.wrapper .accordion .panel.active .acc-body p a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel.active .acc-icon {
  transform: rotate(180deg);
}

.wrapper .accordion .panel.active .acc-trigger .acc-title {
  border-bottom: 0;
}

.wrapper .accordion .panel.active .acc-trigger .acc-title h4 {
  color: #005fec;
}

.wrapper .accordion .panel.active p:last-child {
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
}

.acc-title svg.acc-icon {
  transition: all 0.2s ease;
  min-width: 1rem;
}

@media (min-width: 768px) {
  .wrapper {
    flex-direction: row;
  }
  .accordion {
    flex: 1;
  }
}</code>```

Any Questions?

            <button class="acc-trigger">

Lorem ipsum dolor sit amet.

                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>

              </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

            <button class="acc-trigger">

Lorem ipsum dolor sit amet.

                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>

              </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

```

Body:
In the snippet below, I have an accordion. My goal is to be able to open a single panel at a time in media queries less than 992px. In media queries greater than 992px, I want to be able to open multiple panels at once.

Part of this is working at the mobile size (I can open the panel, but can't close it). And at desktop, it's not opening at all. I'm not sure where I'm going wrong.

How to control accordion panel open/close behavior based on media queries?

function initAccordion() {
  function handlePanelClick(event) {
    showPanel(event.currentTarget);
  }

  function showPanel(panelHeader) {
    let isActive,
      panel = panelHeader.parentNode,
      expandedPanel = document.querySelector(".panel.active");
    mqTablet = window.matchMedia('(min-width: 992px)');

    isActive = expandedPanel && panel.classList.contains("active") ? true : false;

    if (mqTablet.matches && expandedPanel) {
      expandedPanel.querySelector(".acc-body").style.height = null;
      expandedPanel.classList.remove("active");
    }

    if (!mqTablet.matches && panel && !isActive) {
      panel.classList.add('active');
    }

  }

  let allPanelElements = document.querySelectorAll(".panel");

  for (let i = 0; i < allPanelElements.length; i++) {
    allPanelElements[i]
      .querySelector(".acc-trigger")
      .addEventListener("click", handlePanelClick);
  }

  showPanel(allPanelElements);
}

initAccordion(document.getElementsByClassName("accordion"));

.wrapper {
  margin: 50px auto 0;
  display: flex;
  flex-direction: column;
}

.wrapper a {
  text-decoration: none;
}

.wrapper button {
  border-style: none;
  background: white;
}

.wrapper button::-moz-focus-inner {
  border: 0;
}

.wrapper .accordion {
  margin: 0 0.1rem;
}

.wrapper .accordion .panel {
  min-height: 4rem;
  margin: 0 0.1rem;
}

.wrapper .accordion .panel .acc-trigger {
  display: block;
  font-weight: 400;
  margin: 0;
  padding: 0.5em 0;
  position: relative;
  text-align: left;
  width: 100%;
  cursor: pointer;
  background: 0 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title {
  display: flex;
  align-items: center;
  border: transparent 2px solid;
  outline: 0;
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
  transition: all 0.2s ease;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4 {
  font-weight: 800;
  color: #000A70;
  font-size: 1.25rem;
  justify-content: space-between;
  margin-right: 1rem;
  outline: 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4:hover {
  color: #005fec;
}

.wrapper .accordion .panel .acc-trigger .acc-title svg.acc-icon {
  cursor: pointer;
  pointer-events: none;
  margin-left: auto;
  z-index: 3;
}

.wrapper .accordion .panel .acc-body {
  height: 0;
  opacity: 0;
  overflow: hidden;
  visibility: hidden;
  transition: height 0.2s ease-out, opacity 0.2s ease-out;
}

.wrapper .accordion .panel .acc-body ol.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
  counter-reset: my-awesome-counter;
}

.wrapper .accordion .panel .acc-body ol.custom-list li {
  counter-increment: my-awesome-counter;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
  color: #000A70;
}

.wrapper .accordion .panel .acc-body ol.custom-list li::before {
  content: counter(my-awesome-counter) ". ";
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li {
  background-image: url(/assets/svg/bullet.svg);
  background-position: 0 0.5rem;
  background-repeat: no-repeat;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel.active .acc-body {
  opacity: 1;
  height: auto;
  padding: 0.5rem 0;
  visibility: visible;
}

.wrapper .accordion .panel.active .acc-body p {
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel.active .acc-body p+.embed-youtube {
  margin: 1rem 0;
}

.wrapper .accordion .panel.active .acc-body p a {
  color: #005fec;
}

.wrapper .accordion .panel.active .acc-body p a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel.active .acc-icon {
  transform: rotate(180deg);
}

.wrapper .accordion .panel.active .acc-trigger .acc-title {
  border-bottom: 0;
}

.wrapper .accordion .panel.active .acc-trigger .acc-title h4 {
  color: #005fec;
}

.wrapper .accordion .panel.active p:last-child {
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
}

.acc-title svg.acc-icon {
  transition: all 0.2s ease;
  min-width: 1rem;
}

@media (min-width: 768px) {
  .wrapper {
    flex-direction: row;
  }
  .accordion {
    flex: 1;
  }
}

Any Questions?

            <button class="acc-trigger">

Lorem ipsum dolor sit amet.

                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>

              </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

            <button class="acc-trigger">

Lorem ipsum dolor sit amet.

                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>

              </button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.

Body:
You are clubbing many conditions in if statements. Lets simplify things a little bit:

function initAccordion() {
  function handlePanelClick(event) {
    showPanel(event.currentTarget.parentNode);
  }

  function showPanel(panel) {
    let isWide = isWideScreen();
    let isActive = panel.classList.contains("active");

    // handle wide screens
    if (isWide) {
      if (!isActive) { // open the panel
        panel.classList.add('active');
      } else {
        panel.classList.remove('active');
      }
    } else { // handle mobiles
      let panels = document.querySelectorAll('.panel');
      panels.forEach(p => p.classList.remove('active'));
      if (!isActive) { // open the panel
        panel.classList.add('active');
      }
    }
  }

  let allPanelElements = document.querySelectorAll(".panel");
  allPanelElements.forEach(pe => pe.querySelector(".acc-trigger")
    .addEventListener("click", handlePanelClick));

  /*if (isWideScreen()) {
    showPanel(allPanelElements[0]);
  }*/

}

function isWideScreen() {
  return window.matchMedia('(min-width: 992px)').matches;
}
initAccordion(document.getElementsByClassName("accordion"));

.wrapper {
  margin: 50px auto 0;
  display: flex;
  flex-direction: column;
}

.wrapper a {
  text-decoration: none;
}

.wrapper button {
  border-style: none;
  background: white;
}

.wrapper button::-moz-focus-inner {
  border: 0;
}

.wrapper .accordion {
  margin: 0 0.1rem;
}

.wrapper .accordion .panel {
  min-height: 4rem;
  margin: 0 0.1rem;
}

.wrapper .accordion .panel .acc-trigger {
  display: block;
  font-weight: 400;
  margin: 0;
  padding: 0.5em 0;
  position: relative;
  text-align: left;
  width: 100%;
  cursor: pointer;
  background: 0 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title {
  display: flex;
  align-items: center;
  border: transparent 2px solid;
  outline: 0;
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
  transition: all 0.2s ease;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4 {
  font-weight: 800;
  color: #000A70;
  font-size: 1.25rem;
  justify-content: space-between;
  margin-right: 1rem;
  outline: 0;
}

.wrapper .accordion .panel .acc-trigger .acc-title h4:hover {
  color: #005fec;
}

.wrapper .accordion .panel .acc-trigger .acc-title svg.acc-icon {
  cursor: pointer;
  pointer-events: none;
  margin-left: auto;
  z-index: 3;
}

.wrapper .accordion .panel .acc-body {
  height: 0;
  opacity: 0;
  overflow: hidden;
  visibility: hidden;
  transition: height 0.2s ease-out, opacity 0.2s ease-out;
}

.wrapper .accordion .panel .acc-body ol.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
  counter-reset: my-awesome-counter;
}

.wrapper .accordion .panel .acc-body ol.custom-list li {
  counter-increment: my-awesome-counter;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
  color: #000A70;
}

.wrapper .accordion .panel .acc-body ol.custom-list li::before {
  content: counter(my-awesome-counter) ". ";
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ol.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ol.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list {
  list-style-type: none;
  -webkit-margin-before: 0;
  margin-block-start: 0;
  -webkit-margin-after: 0;
  margin-block-end: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li {
  background-image: url(/assets/svg/bullet.svg);
  background-position: 0 0.5rem;
  background-repeat: no-repeat;
  padding-left: 1.125rem;
  margin: 2rem 0;
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a {
  color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:first-child {
  margin-top: 0;
}

.wrapper .accordion .panel .acc-body ul.custom-list li:last-child {
  margin-bottom: 2rem;
}

.wrapper .accordion .panel.active .acc-body {
  opacity: 1;
  height: auto;
  padding: 0.5rem 0;
  visibility: visible;
}

.wrapper .accordion .panel.active .acc-body p {
  font-size: 1rem;
  line-height: 1.5rem;
}

.wrapper .accordion .panel.active .acc-body p+.embed-youtube {
  margin: 1rem 0;
}

.wrapper .accordion .panel.active .acc-body p a {
  color: #005fec;
}

.wrapper .accordion .panel.active .acc-body p a:hover {
  text-decoration: underline;
  text-decoration-color: #005fec;
}

.wrapper .accordion .panel.active .acc-icon {
  transform: rotate(180deg);
}

.wrapper .accordion .panel.active .acc-trigger .acc-title {
  border-bottom: 0;
}

.wrapper .accordion .panel.active .acc-trigger .acc-title h4 {
  color: #005fec;
}

.wrapper .accordion .panel.active p:last-child {
  border-bottom: 1px solid #000A70;
  padding-bottom: 0.5rem;
}

.acc-title svg.acc-icon {
  transition: all 0.2s ease;
  min-width: 1rem;
}

@media (min-width: 768px) {
  .wrapper {
    flex-direction: row;
  }
  .accordion {
    flex: 1;
  }
}

<section id="questions">
  <div class="container">
    <div class="row justify-content-center align-items-start">
      <h3>Any Questions?</h3>
      <div class="wrapper">
        <div class="accordion">
          <div class="panel">
            <button class="acc-trigger">
                <span class="acc-title">
                  <h4>Lorem ipsum dolor sit amet.</h4>
                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>
                </span>
              </button>
            <div class="acc-body">
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.</p>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.</p>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.</p>
            </div>
          </div>
          <div class="panel">
            <button class="acc-trigger">
                <span class="acc-title">
                  <h4>Lorem ipsum dolor sit amet.</h4>
                  <svg class="acc-icon" width="16" height="11" viewBox="0 0 16 11" fill="none"
                    xmlns="http://www.w3.org/2000/svg">
                    <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z"
                      fill="#000A70" />
                  </svg>
                </span>
              </button>
            <div class="acc-body">
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.</p>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.</p>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi enim quas laboriosam itaque harum ab voluptas? Deserunt aliquam pariatur voluptatem odit iure autem eos totam eius consequuntur animi. Omnis, ipsam.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>


问:
Wildcard url in Django using re_path
As per Django documentation ,below url pattern will work for

http://127.0.0.1:8000/index . But I want also to make it work for

http://127.0.0.1:8000/api/index/
http://127.0.0.1:8000/api/json/index/

```<code>from django.urls import include, re_path

urlpatterns = [
    re_path(r'^index/$', views.index, name='index'),
    ...
]
</code>```

How we can achieve it using re_path

答:
you can add multiple entries of re_path with different urls endpoints for same views.index like this .

```<code>urlpatterns = [
    re_path(r'^index/$', views.index, name='index'),
    re_path(r'^api/json/index/$', views.index, name='index'),
    re_path(r'^api/index/$', views.index, name='index'),
    ...
]
</code>```

Title: Wildcard url in Django using re_path

Body:
As per Django documentation ,below url pattern will work for

http://127.0.0.1:8000/index . But I want also to make it work for

http://127.0.0.1:8000/api/index/
http://127.0.0.1:8000/api/json/index/

from django.urls import include, re_path

urlpatterns = [
    re_path(r'^index/$', views.index, name='index'),
    ...
]

How we can achieve it using re_path

Body:
you can add multiple entries of re_path with different urls endpoints for same views.index like this .

urlpatterns = [
    re_path(r'^index/$', views.index, name='index'),
    re_path(r'^api/json/index/$', views.index, name='index'),
    re_path(r'^api/index/$', views.index, name='index'),
    ...
]


问:
Clarifai api referenceerror : process is not defined
I get such an error on npm start on clarifai api
[1]: https://i.stack.imgur.com/pHRNz.png

Open bootstrap:27:

```<code>    // Execute the module function
    try {
        var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };
        __webpack_require__.i.forEach(function(handler) { handler(execOptions); });
        module = execOptions.module;
        execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
    } catch(e) {
        module.error = e;
        throw e;
    }

    // Flag the module as loaded
    module.loaded = true;

    // Return the exports of the module
    return module.exports;
}
</code>```

and my App.js details;

```<code>const app = new Clarifai.App({
  apiKey: '****',
})

///

  onButtonSubmit = () => {
    console.log('click')
    app.models
      .predict(
        '45fb9a671625463fa646c3523a3087d5',
        'https://samples.clarifai.com/metro-north.jpg'
      )
      .then(
        function (response) {
          console.log(response)
        },
        function (err) {
          //
        }
      )
  }
</code>```

I am getting this error before render in console.log. what would be the reason?

Happy coding day! :)

答: As stated in the documentation you need to use Broserify. You are missing NodeJS globals. Please let us know if this does not work for you as this library is unfortunately not under active maintenance currently.</p>

Body:
I get such an error on npm start on clarifai api
[1]: https://i.stack.imgur.com/pHRNz.png

Open bootstrap:27:

    // Execute the module function
    try {
        var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: __webpack_require__ };
        __webpack_require__.i.forEach(function(handler) { handler(execOptions); });
        module = execOptions.module;
        execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
    } catch(e) {
        module.error = e;
        throw e;
    }

    // Flag the module as loaded
    module.loaded = true;

    // Return the exports of the module
    return module.exports;
}

and my App.js details;

const app = new Clarifai.App({
  apiKey: '****',
})

///

  onButtonSubmit = () => {
    console.log('click')
    app.models
      .predict(
        '45fb9a671625463fa646c3523a3087d5',
        'https://samples.clarifai.com/metro-north.jpg'
      )
      .then(
        function (response) {
          console.log(response)
        },
        function (err) {
          //
        }
      )
  }

I am getting this error before render in console.log. what would be the reason?

Happy coding day! :)


问:
Input value didnt display
The code snippet below is form that embeded in the bootstrap modal to allow the user create a new subject for current system. In the form, I have included one text input to accept the data. In that text input, I have assign value = "incomplete" as the default value. However, the default value didnt show as expected when the webpage is running.

```<code><div class="modal-body">
                        <form id="adminAddExamForm" method="POST"
                            th:action="@{/process_AdminAddExam}" th:object="${exam}">
                            <div class="mb-2">
                                <label for="status" class="col-form-label">Status</label>
                                <input type="text" value="incomplete" class="form-control" id="status" th:field="*{status}" autocomplete="off" disabled>
                            </div>
                       </form>
</div>
</code>```

The below code snippet and screenshot is taken from chrome dev tools. Even though I have assign the value, but it still show nothing

```<code><div class="mb-2">
                                <label for="status" class="col-form-label">Status</label>
                                <input type="text" value="" class="form-control" id="status" name="status">
                            </div>
</code>```

答:
No value = "incomplete" found in your codes. only value = ""

Replace

```<code><input type="text" value="" class="form-control" id="status" name="status">
</code>```

with

```<code><input type="text" value="incomplete" class="form-control" id="status" name="status">
</code>```

Update:
If still doesn't show, check the css. Is there a property that makes the text transparent to its background.

Title: Input value didnt display

Body:
The code snippet below is form that embeded in the bootstrap modal to allow the user create a new subject for current system. In the form, I have included one text input to accept the data. In that text input, I have assign value = "incomplete" as the default value. However, the default value didnt show as expected when the webpage is running.

                        <form id="adminAddExamForm" method="POST"
                            th:action="@{/process_AdminAddExam}" th:object="${exam}">

                                Status
                                <input type="text" value="incomplete" class="form-control" id="status" th:field="*{status}" autocomplete="off" disabled>

                       </form>

The below code snippet and screenshot is taken from chrome dev tools. Even though I have assign the value, but it still show nothing

                                Status
                                <input type="text" value="" class="form-control" id="status" name="status">

Body:
No value = "incomplete" found in your codes. only value = ""

Replace

<input type="text" value="" class="form-control" id="status" name="status">

with

<input type="text" value="incomplete" class="form-control" id="status" name="status">

Update:
If still doesn't show, check the css. Is there a property that makes the text transparent to its background.


问:
How to copy in bash all directory and files recursive?
I have script:

```<code>find ./SourceFolder/ -maxdepth 4 -exec cp -R '{}' ./DestFolder/ \;
</code>```

SourceDir contains also sub-folders.

Problem that in DestFolder not only all tree, but in up level all another levels and files.

How to fix ?

答:
also try this cp -r ./dist/* ./out;

this command will copy dist/* files to out dir;

Body:
I have script:

find ./SourceFolder/ -maxdepth 4 -exec cp -R '{}' ./DestFolder/ \;

SourceDir contains also sub-folders.

Problem that in DestFolder not only all tree, but in up level all another levels and files.

How to fix ?


问:
Material not loaded in sdkdemo project or also there is no custom timeline
Recently we have tried to implement your SDK demo in our project, But as per our result we followed every step you mentioned in this doc but there is no material coming from Huwai app gallery column also let us know how can we able to load assets from local

-- need to know the transition and animation pattern so that we can also build custom transitions for our application.

-- Custom timeline that is implemented on the UI SDK is not available on this Demo SDK, where is documentation on how can we implement it custom timeline in our application.

答:
-- Custom timeline that is implemented on the UI SDK is not available on this Demo SDK, where is documentation on how can we implement it custom timeline in our application.

The UI SDK cannot be used to customize the timeline. You need to use video-editor-sdk. pls kindly refer to this docs.


问:
Need assistance on function to determine largest list Haskell
I need to create a function that reads from a list of courses (such as the one shown below), and return which courses has the largest number of programming languages.

Here is the list

```<code>progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"]),
     ("CptS355" , ["Haskell", "Python", "PostScript", "Java"]),
     ("CptS360" , ["C"]),
     ("CptS370" , ["Java"]),
     ("CptS315" , ["Python"]),
     ("CptS411" , ["C", "C++"]),
     ("CptS451" , ["Python", "C#", "SQL"]),
     ("CptS475" , ["Python", "R"])
     ]
</code>```

It needs to be compatible with the following

```<code>The type of the max_count function should be compatible with one of the following:
max_count :: [(a1, [a2])] -> (a1, Int)
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)
</code>```

So far, I have attempted the following code

```<code>max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')
</code>```

This has not worked in the slightest, and I am at a blank for what to do. Any help is appreciated.

答:
You can use foldr and hold the information of max entry in accumulator variable:

maxCount :: Foldable t => [(a1, t a2)] -> (a1, Int)
maxCount [] = error "bad"
maxCount ((c,cs):l) = foldr opr (c, length cs) ((c,cs):l)
  where
    opr (c', xs) (c'', n)
      | length xs > n = (c', length xs)
      | otherwise = (c'', n)
```
<p>I think <code>error "bad"</code> is bad practice here, we can use <code>Maybe</code>:</p>
<pre class="lang-haskell prettyprint-override"><code>
maxCount' :: Foldable t => [(a1, t a2)] -> Maybe (a1, Int)
maxCount' [] = Nothing
maxCount' ((c,cs):l) = Just $ foldr opr (c, length cs) ((c,cs):l)
  where
    opr (c', xs) (c'', n)
      | length xs > n = (c', length xs)
      | otherwise = (c'', n)
</code>```

Body:
I need to create a function that reads from a list of courses (such as the one shown below), and return which courses has the largest number of programming languages.

Here is the list

progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"]),
     ("CptS355" , ["Haskell", "Python", "PostScript", "Java"]),
     ("CptS360" , ["C"]),
     ("CptS370" , ["Java"]),
     ("CptS315" , ["Python"]),
     ("CptS411" , ["C", "C++"]),
     ("CptS451" , ["Python", "C#", "SQL"]),
     ("CptS475" , ["Python", "R"])
     ]

It needs to be compatible with the following

The type of the max_count function should be compatible with one of the following:
max_count :: [(a1, [a2])] -> (a1, Int)
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)

So far, I have attempted the following code

max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')

This has not worked in the slightest, and I am at a blank for what to do. Any help is appreciated.

Body:
You can use foldr and hold the information of max entry in accumulator variable:

maxCount :: Foldable t => [(a1, t a2)] -> (a1, Int)
maxCount [] = error "bad"
maxCount ((c,cs):l) = foldr opr (c, length cs) ((c,cs):l)
  where
    opr (c', xs) (c'', n)
      | length xs > n = (c', length xs)
      | otherwise = (c'', n)

I think error "bad" is bad practice here, we can use Maybe:

maxCount' :: Foldable t => [(a1, t a2)] -> Maybe (a1, Int)
maxCount' [] = Nothing
maxCount' ((c,cs):l) = Just $ foldr opr (c, length cs) ((c,cs):l)
  where
    opr (c', xs) (c'', n)
      | length xs > n = (c', length xs)
      | otherwise = (c'', n)


问:
XmlReader breaks on UTF-8 BOM
I have the following XML Parsing code in my application:

```<code>    public static XElement Parse(string xml, string xsdFilename)
    {
        var readerSettings = new XmlReaderSettings
        {
            ValidationType = ValidationType.Schema,
            Schemas = new XmlSchemaSet()
        };
        readerSettings.Schemas.Add(null, xsdFilename);
        readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        readerSettings.ValidationEventHandler +=
            (o, e) => { throw new Exception("The provided XML does not validate against the request's schema."); };

        var readerContext = new XmlParserContext(null, null, null, XmlSpace.Default, Encoding.UTF8);

        return XElement.Load(XmlReader.Create(new StringReader(xml), readerSettings, readerContext));
    }
</code>```

I am using it to parse strings sent to my WCF service into XML documents, for custom deserialization.

It works fine when I read in files and send them over the wire (the request); I've verified that the BOM is not sent across. In my request handler I'm serializing a response object and sending it back as a string. The serialization process adds a UTF-8 BOM to the front of the string, which causes the same code to break when parsing the response.

```<code>System.Xml.XmlException : Data at the root level is invalid. Line 1, position 1.
</code>```

In the research I've done over the last hour or so, it appears that XmlReader should honor the BOM.  If I manually remove the BOM from the front of the string, the response xml parses fine.

Am I missing something obvious, or at least something insidious?

EDIT: Here is the serialization code I'm using to return the response:

```<code>private static string SerializeResponse(Response response)
{
    var output = new MemoryStream();
    var writer = XmlWriter.Create(output);
    new XmlSerializer(typeof(Response)).Serialize(writer, response);
    var bytes = output.ToArray();
    var responseXml = Encoding.UTF8.GetString(bytes);
    return responseXml;
}
</code>```

If it's just a matter of the xml incorrectly containing the BOM, then I'll switch to

```<code>var responseXml = new UTF8Encoding(false).GetString(bytes);
</code>```

but it was not clear at all from my research that the BOM was illegal in the actual XML string; see e.g. c# Detect xml encoding from Byte Array?

答:
Here is how to convert the MemoryStream to a string that can be used with XmlDocument (the Skip function is Linq):</p>
```<code>    public static string Decode(MemoryStream ms)
    {
      var fileBytes = ms.ToArray();
      var isUnicode = fileBytes[0] == 0xff && fileBytes[1] == 0xfe;  //UTF-16 little endian
      var isUtf8Bom = fileBytes[0] == 0xef && fileBytes[1] == 0xbb && fileBytes[2] == 0xbf;

      string xml = isUnicode ? Encoding.Unicode.GetString(fileBytes) :
                   (isUtf8Bom ? new UTF8Encoding(false, true).GetString(fileBytes.Skip(3).ToArray()) : new UTF8Encoding(false, true).GetString(fileBytes));

       return xml;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: XmlReader breaks on UTF-8 BOM

Body:
I have the following XML Parsing code in my application:

    public static XElement Parse(string xml, string xsdFilename)
    {
        var readerSettings = new XmlReaderSettings
        {
            ValidationType = ValidationType.Schema,
            Schemas = new XmlSchemaSet()
        };
        readerSettings.Schemas.Add(null, xsdFilename);
        readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
        readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
        readerSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        readerSettings.ValidationEventHandler +=
            (o, e) => { throw new Exception("The provided XML does not validate against the request's schema."); };

        var readerContext = new XmlParserContext(null, null, null, XmlSpace.Default, Encoding.UTF8);

        return XElement.Load(XmlReader.Create(new StringReader(xml), readerSettings, readerContext));
    }

I am using it to parse strings sent to my WCF service into XML documents, for custom deserialization.

It works fine when I read in files and send them over the wire (the request); I've verified that the BOM is not sent across. In my request handler I'm serializing a response object and sending it back as a string. The serialization process adds a UTF-8 BOM to the front of the string, which causes the same code to break when parsing the response.

System.Xml.XmlException : Data at the root level is invalid. Line 1, position 1.

In the research I've done over the last hour or so, it appears that XmlReader should honor the BOM.  If I manually remove the BOM from the front of the string, the response xml parses fine.

Am I missing something obvious, or at least something insidious?

EDIT: Here is the serialization code I'm using to return the response:

private static string SerializeResponse(Response response)
{
    var output = new MemoryStream();
    var writer = XmlWriter.Create(output);
    new XmlSerializer(typeof(Response)).Serialize(writer, response);
    var bytes = output.ToArray();
    var responseXml = Encoding.UTF8.GetString(bytes);
    return responseXml;
}

If it's just a matter of the xml incorrectly containing the BOM, then I'll switch to

var responseXml = new UTF8Encoding(false).GetString(bytes);

but it was not clear at all from my research that the BOM was illegal in the actual XML string; see e.g. c# Detect xml encoding from Byte Array?

Body:
Here is how to convert the MemoryStream to a string that can be used with XmlDocument (the Skip function is Linq):

    public static string Decode(MemoryStream ms)
    {
      var fileBytes = ms.ToArray();
      var isUnicode = fileBytes[0] == 0xff && fileBytes[1] == 0xfe;  //UTF-16 little endian
      var isUtf8Bom = fileBytes[0] == 0xef && fileBytes[1] == 0xbb && fileBytes[2] == 0xbf;

      string xml = isUnicode ? Encoding.Unicode.GetString(fileBytes) :
                   (isUtf8Bom ? new UTF8Encoding(false, true).GetString(fileBytes.Skip(3).ToArray()) : new UTF8Encoding(false, true).GetString(fileBytes));

       return xml;
    }


问:
Recovering files deleted by Android studio?
I'm working on an app at the moment, and one of the final steps was to get it built and signed in Android studio.

Unfortunately I was having some problems, and one of the recommended solutions was to remove the project and start again, however when I did this it took all of my files with it, and they're not in the trash (OSX) either.

Is there anyway to recover these files, or are they lost forever? :(

答: Im late but this works. Go to the folder where u want to recover. right-click, local history. select ones you deleted and click revert. :)</p>

ContentLicense: CC BY-SA 3.0


问:
How to connecte to sql sever NET6 visual studio 2022 asp.net mvc project
i try to modify my local db connection (which works fine) in the appsettings.json :

```<code> "ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CateringMilano;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

with the sql server connection :

```<code> "ApplicationDbContextConnection": "Data Source=SQL5101.site4now.net;Initial Catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

but when i run the project i got a strange error:

local host does  not exists..

and also

```<code>An unhandled exception occurred while processing the request.
</code>```

SqlException: Failed to generate SSPI context.
Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

and also i cannot see the sql server db in visual studio sql explorer..

What do i need to connect my website to my sql sever db?  what am i missing to do?

Thanks

答:
It seems you want to connect your remote hosting SQL server instance with your application instead of location database instance. If that is the scenario then your database connection string should like below:

When used in web.config file:

data source=SQL5101.site4now.net;initial catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;integrated security=False;Trusted_Connection=False;MultipleActiveResultSets=True; />

When used in appsettings.json:

```<code>"ConnectionStrings": {

    "DefaultConnection": "Server=SQL5101.site4now.net;Database=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;integrated security=False;Trusted_Connection=False;MultipleActiveResultSets=True;"
  }
</code>```

When used in Ado.net connection string file:

```<code>  using (var connection = new SqlConnection("Server=SQL5101.site4now.net;Database=db_9b307b_cateringmilano; User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;integrated security=False;Trusted_Connection=False;MultipleActiveResultSets=True;"))
            {

            }
</code>```

Tips to check if the connection successful :

Go to your SQL Server Managament Studio and click on below tab:

Then enter your remote SQL server credential like below:

If the connection is alright you should get following:

It means that you have successfully able to connect. So try above steps I have provided.Hope that would guide you accordingly.

Note:

Trusted_Connection=false also allow you connect the database from your SQL server hosting provider But as you are accessing with your
server credential you can set that to Trusted_Connection=true.

Feel free to share if you have any further concern on it.

Body:
i try to modify my local db connection (which works fine) in the appsettings.json :

 "ApplicationDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=CateringMilano;Trusted_Connection=True;MultipleActiveResultSets=true"

with the sql server connection :

 "ApplicationDbContextConnection": "Data Source=SQL5101.site4now.net;Initial Catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;Trusted_Connection=True;MultipleActiveResultSets=true"

but when i run the project i got a strange error:

local host does  not exists..

and also

An unhandled exception occurred while processing the request.

SqlException: Failed to generate SSPI context.
Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

and also i cannot see the sql server db in visual studio sql explorer..

What do i need to connect my website to my sql sever db?  what am i missing to do?

Thanks

Body:
It seems you want to connect your remote hosting SQL server instance with your application instead of location database instance. If that is the scenario then your database connection string should like below:

When used in web.config file:

data source=SQL5101.site4now.net;initial catalog=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;integrated security=False;Trusted_Connection=False;MultipleActiveResultSets=True; />

When used in appsettings.json:

"ConnectionStrings": {

    "DefaultConnection": "Server=SQL5101.site4now.net;Database=db_9b307b_cateringmilano;User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;integrated security=False;Trusted_Connection=False;MultipleActiveResultSets=True;"
  }

When used in Ado.net connection string file:

  using (var connection = new SqlConnection("Server=SQL5101.site4now.net;Database=db_9b307b_cateringmilano; User Id=db_9b307b_cateringmilano_admin;Password=YOUR_DB_PASSWORD;integrated security=False;Trusted_Connection=False;MultipleActiveResultSets=True;"))
            {

            }

Tips to check if the connection successful :

Go to your SQL Server Managament Studio and click on below tab:

Then enter your remote SQL server credential like below:

If the connection is alright you should get following:

It means that you have successfully able to connect. So try above steps I have provided.Hope that would guide you accordingly.

Note:

Trusted_Connection=false also allow you connect the database from your SQL server hosting provider But as you are accessing with your
server credential you can set that to Trusted_Connection=true.

Feel free to share if you have any further concern on it.


问:
Android 12 deep link association by user fails because of crash in Samsung Settings app
I am targeting android 12 and using this user association method to make my deep links be handled by app.

I show a dialog with [GO TO SETTINGS] button asking to add supported links from app settings. On [GO TO SETTINGS] click I run this code

```<code>val intent = Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS,
            Uri.parse("package:${context.packageName}"))
        startActivity(context, intent)
</code>```

Which opens my application [Set as default] section in device settings app, where user can enable supported web addresses.

This works for most devices. But for Samsung galaxy s21 (and maybe all Samsungs with android 12) devices application closes without crash log.

I have found out that crash happens in device settings app, here is the log.

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
    at com.android.settings.applications.intentpicker.AppLaunchSettings.onCreate(AppLaunchSettings.java:142)
    at androidx.fragment.app.Fragment.performCreate(Fragment.java:2976)
    at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:278)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
    at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
    at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
    at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
    at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:501)
    at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
    at com.samsung.android.settings.core.SecMultiPaneActivity.onStart(SecMultiPaneActivity.java:198)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1455)
    at android.app.Activity.performStart(Activity.java:8307)
    at android.app.ActivityThread.handleStartActivity(ActivityThread.java:4047)
    at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
    at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
    at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2425)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8582)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:563)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1133)
</code>```

Is there a way to overcome this? I even can't check this before sending intent, because
intent.resolveActivity returns not null result.
Thanks for help.

答:
Android using custom UI called One UI 4. It not yet update this page, so in Samsung device do not have this page (at this moment).

You can work around by open App Setting page and let user select on "Set as Default" action.

or using

```<code>      Intent intent;
      if (manufactorer.contains("samsung")) {
        intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + localContext.getPackageName()));
      } else {
        intent = new Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS, Uri.parse("package:" + localContext.getPackageName()));
      }
</code>```

Body:
I am targeting android 12 and using this user association method to make my deep links be handled by app.

I show a dialog with [GO TO SETTINGS] button asking to add supported links from app settings. On [GO TO SETTINGS] click I run this code

val intent = Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS,
            Uri.parse("package:${context.packageName}"))
        startActivity(context, intent)

Which opens my application [Set as default] section in device settings app, where user can enable supported web addresses.

This works for most devices. But for Samsung galaxy s21 (and maybe all Samsungs with android 12) devices application closes without crash log.

I have found out that crash happens in device settings app, here is the log.

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
    at com.android.settings.applications.intentpicker.AppLaunchSettings.onCreate(AppLaunchSettings.java:142)
    at androidx.fragment.app.Fragment.performCreate(Fragment.java:2976)
    at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:475)
    at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:278)
    at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
    at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
    at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
    at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
    at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
    at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
    at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:501)
    at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246)
    at com.samsung.android.settings.core.SecMultiPaneActivity.onStart(SecMultiPaneActivity.java:198)
    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1455)
    at android.app.Activity.performStart(Activity.java:8307)
    at android.app.ActivityThread.handleStartActivity(ActivityThread.java:4047)
    at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
    at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
    at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2425)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8582)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:563)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1133)

Is there a way to overcome this? I even can't check this before sending intent, because
intent.resolveActivity returns not null result.
Thanks for help.

Body:
Android using custom UI called One UI 4. It not yet update this page, so in Samsung device do not have this page (at this moment).

You can work around by open App Setting page and let user select on "Set as Default" action.

or using

      Intent intent;
      if (manufactorer.contains("samsung")) {
        intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + localContext.getPackageName()));
      } else {
        intent = new Intent(Settings.ACTION_APP_OPEN_BY_DEFAULT_SETTINGS, Uri.parse("package:" + localContext.getPackageName()));
      }


问:
How to properly link an external library with msvc compiler batch file
I have a project which is using a simple batch file to compile everything I need to work with. But right now I need to use imgui in my project, and I got a problems with linking it correctly to my project. I am trying to use Dear ImGui right now.

In my project, in the moment when I am trying to build it with "linked" imgui library, it complains with error: LNK2019: unresolved external symbol with every imgui function

Basically, I have this project folder set up:

```<code>/project_name
    /imgui
    file1.cpp
    file1.h
    ....
</code>```

And I have this batch file to compile the whole project:

```<code>@echo off
if not defined DevEnvDir (
    call vcvarsall x64
)
REM call vcvarsall x64

set LIB_VCPKG="F:\Env\vcpkg\installed\x64-windows\lib"
set INC_VCPKG="F:\Env\vcpkg\installed\x64-windows\include"
set INC_IMGUI="..\code\imgui"

set CommonCompileFlags=-MT -nologo -fp:fast -EHa -Od -WX- -W4 -Oi -GR- -Gm- -GS -wd4100 -wd4201 -wd4505 -FC -Z7 /I%INC_VCPKG% /I%INC_IMGUI%
set CommonLinkFlags=-opt:ref -incremental:no /NODEFAULTLIB:msvcrt /SUBSYSTEM:CONSOLE /LIBPATH:%LIB_VCPKG%

if not exist ..\build mkdir ..\build
pushd ..\build

REM cl ..\code\imgui\imgui.cpp /c /EHsc
REM lib imgui.obj
cl %CommonCompileFlags% SDL2main.lib SDL2.lib ..\code\display.cpp -LD /link -opt:ref -incremental:no /LIBPATH:%LIB_VCPKG%
cl %CommonCompileFlags% ..\code\main.cpp SDL2main.lib SDL2.lib display.obj /link %CommonLinkFlags%
popd
</code>```

I already tried to compile from imgui a static library, but that did not helped. And I tried to use /I flag - that didn't helped neither.

For example, I am using header only Sean Berrets library in my project and it is working pretty fine here. But I have link issue only with the dear ImGui library. I don't know why.

Is there a possibilities that I just don't understand something and just don't do the link phase correctly? Thanks.

答:
This example helped me to workout my issue:
https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx12

So, basically, I didn't linked to any of the Dear ImGui files. Right now my batch file is looks like this:

```<code>@echo off
if not defined DevEnvDir (
    call vcvarsall x64
)
REM call vcvarsall x64

set LIB_VCPKG="F:\Env\vcpkg\installed\x64-windows\lib"
set INC_VCPKG="F:\Env\vcpkg\installed\x64-windows\include"
set INC_IMGUI="..\code\imgui"

set CommonCompileFlags=-MT -nologo -fp:fast -EHa -Od -WX- -W4 -Oi -GR- -Gm- -GS -wd4100 -wd4201 -wd4505 -FC -Z7 /I%INC_VCPKG% /I%INV_IMGUI%
set CommonLinkFlags=-opt:ref -incremental:no /NODEFAULTLIB:msvcrt /SUBSYSTEM:CONSOLE /LIBPATH:%LIB_VCPKG%

if not exist ..\build mkdir ..\build
pushd ..\build

cl %CommonCompileFlags% SDL2main.lib SDL2.lib imgui.obj imgui_demo.obj imgui_draw.obj imgui_impl_sdl.obj imgui_impl_sdlrenderer.obj imgui_tables.obj imgui_widgets.obj ..\code\display.cpp -LD /link -opt:ref -incremental:no /LIBPATH:%LIB_VCPKG%
cl %CommonCompileFlags% ..\code\main.cpp ..\code\imgui\imgui*.cpp ..\code\imgui\imgui_impl_sdl.cpp SDL2main.lib SDL2.lib display.obj /link %CommonLinkFlags%
popd
</code>```

Body:
I have a project which is using a simple batch file to compile everything I need to work with. But right now I need to use imgui in my project, and I got a problems with linking it correctly to my project. I am trying to use Dear ImGui right now.

In my project, in the moment when I am trying to build it with "linked" imgui library, it complains with error: LNK2019: unresolved external symbol with every imgui function

Basically, I have this project folder set up:

/project_name
    /imgui
    file1.cpp
    file1.h
    ....

And I have this batch file to compile the whole project:

@echo off
if not defined DevEnvDir (
    call vcvarsall x64
)
REM call vcvarsall x64

set LIB_VCPKG="F:\Env\vcpkg\installed\x64-windows\lib"
set INC_VCPKG="F:\Env\vcpkg\installed\x64-windows\include"
set INC_IMGUI="..\code\imgui"

set CommonCompileFlags=-MT -nologo -fp:fast -EHa -Od -WX- -W4 -Oi -GR- -Gm- -GS -wd4100 -wd4201 -wd4505 -FC -Z7 /I%INC_VCPKG% /I%INC_IMGUI%
set CommonLinkFlags=-opt:ref -incremental:no /NODEFAULTLIB:msvcrt /SUBSYSTEM:CONSOLE /LIBPATH:%LIB_VCPKG%

if not exist ..\build mkdir ..\build
pushd ..\build

REM cl ..\code\imgui\imgui.cpp /c /EHsc
REM lib imgui.obj
cl %CommonCompileFlags% SDL2main.lib SDL2.lib ..\code\display.cpp -LD /link -opt:ref -incremental:no /LIBPATH:%LIB_VCPKG%
cl %CommonCompileFlags% ..\code\main.cpp SDL2main.lib SDL2.lib display.obj /link %CommonLinkFlags%
popd

I already tried to compile from imgui a static library, but that did not helped. And I tried to use /I flag - that didn't helped neither.

For example, I am using header only Sean Berrets library in my project and it is working pretty fine here. But I have link issue only with the dear ImGui library. I don't know why.

Is there a possibilities that I just don't understand something and just don't do the link phase correctly? Thanks.

Body:
This example helped me to workout my issue:
https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx12

So, basically, I didn't linked to any of the Dear ImGui files. Right now my batch file is looks like this:

@echo off
if not defined DevEnvDir (
    call vcvarsall x64
)
REM call vcvarsall x64

set LIB_VCPKG="F:\Env\vcpkg\installed\x64-windows\lib"
set INC_VCPKG="F:\Env\vcpkg\installed\x64-windows\include"
set INC_IMGUI="..\code\imgui"

set CommonCompileFlags=-MT -nologo -fp:fast -EHa -Od -WX- -W4 -Oi -GR- -Gm- -GS -wd4100 -wd4201 -wd4505 -FC -Z7 /I%INC_VCPKG% /I%INV_IMGUI%
set CommonLinkFlags=-opt:ref -incremental:no /NODEFAULTLIB:msvcrt /SUBSYSTEM:CONSOLE /LIBPATH:%LIB_VCPKG%

if not exist ..\build mkdir ..\build
pushd ..\build

cl %CommonCompileFlags% SDL2main.lib SDL2.lib imgui.obj imgui_demo.obj imgui_draw.obj imgui_impl_sdl.obj imgui_impl_sdlrenderer.obj imgui_tables.obj imgui_widgets.obj ..\code\display.cpp -LD /link -opt:ref -incremental:no /LIBPATH:%LIB_VCPKG%
cl %CommonCompileFlags% ..\code\main.cpp ..\code\imgui\imgui*.cpp ..\code\imgui\imgui_impl_sdl.cpp SDL2main.lib SDL2.lib display.obj /link %CommonLinkFlags%
popd


问:
Qt: Inherit QObject in parent and other QWidget subclass in child
I am writing a series of custom classes for Qt. What I need is to have a base class that has few custom signals and slots, and children classes will have it. However, I do know that inheriting from the same classes will be thrown an error. I have read the documentation but only dictates that I need to include QObject if I wish to use Q_OBJECT macro. This is the following sample code that I intend to do:

```<code>class Base : public QObject
{
Q_OBJECT

base signals here

public base slots here
}

class Child : public QLabel, public Base
{
// Other codes here
}
</code>```

Will it be possible this way? Since I only wish to use Qt to connect with all children inherits from the parent class.

答:
Multiple inheritance from QObject will not work for several reasons.
(Moc-Compiler does not work correctly and QObject has member variables which makes mutliple inheritance unsafe).

You better work with composition instead of inheritance in case you want to provide the same behavious to several objects.

Body:
I am writing a series of custom classes for Qt. What I need is to have a base class that has few custom signals and slots, and children classes will have it. However, I do know that inheriting from the same classes will be thrown an error. I have read the documentation but only dictates that I need to include QObject if I wish to use Q_OBJECT macro. This is the following sample code that I intend to do:

class Base : public QObject
{
Q_OBJECT

base signals here

public base slots here
}

class Child : public QLabel, public Base
{
// Other codes here
}

Will it be possible this way? Since I only wish to use Qt to connect with all children inherits from the parent class.


问:
django model structure for many to many relasionship based on third model
I currently have three models:

```<code>class Request(models.Model):
    requester=models.CharField()
    dateRequested = models.DateField(auto_now=True)
    title= models.CharField(max_length=255)
    description = models.TextField()

class RequestType(models.Model):
    requestType=models.CharField('Request Type', max_length=256)

class RequestTypeInfo(models.Model):
    requestType=models.ForeignKey('RequestType', verbose_name='Request Type')
    title = models.CharField('title', max_length=256)
    info = models.CharField(max_length=256, blank=True)
</code>```

The idea is that each request shows the information common to all types of requests and additional fields are presented to the users to be filled in depending on the request type selected.

How would I change the models to allow this and how would i write the view to display the form to the user so that the additional information is displayed in-line with the base request. Would it be better to have a second view which asks for the additional information.

The end aim is that the admins can create new request types without creating models in python by just adding a new request and adding any additional info fields.

答:
So are you saying that you want to create a Many-to-many relationship from Request to RequestTypeInfo using RequestType as your intermediate Model?

```<code>class Request(models.Model):
    requester=models.CharField()
    dateRequested = models.DateField(auto_now=True)
    title= models.CharField(max_length=255)
    description = models.TextField()
    request_type = models.ManyToManyField(RequestType, through='RequestTypeInfo')

class RequestType(models.Model):
    requestType=models.CharField('Request Type', max_length=256)

class RequestTypeInfo(models.Model):
    requestType=models.ForeignKey('RequestType', verbose_name='Request Type')
    title = models.CharField('title', max_length=256)
    info = models.CharField(max_length=256, blank=True)
</code>```

We can talk about inline admin models after this gets clarified.

OwnerDisplayName: Morchuboo

Body:
I currently have three models:

class Request(models.Model):
    requester=models.CharField()
    dateRequested = models.DateField(auto_now=True)
    title= models.CharField(max_length=255)
    description = models.TextField()

class RequestType(models.Model):
    requestType=models.CharField('Request Type', max_length=256)

class RequestTypeInfo(models.Model):
    requestType=models.ForeignKey('RequestType', verbose_name='Request Type')
    title = models.CharField('title', max_length=256)
    info = models.CharField(max_length=256, blank=True)

The idea is that each request shows the information common to all types of requests and additional fields are presented to the users to be filled in depending on the request type selected.

How would I change the models to allow this and how would i write the view to display the form to the user so that the additional information is displayed in-line with the base request. Would it be better to have a second view which asks for the additional information.

The end aim is that the admins can create new request types without creating models in python by just adding a new request and adding any additional info fields.

LastEditorDisplayName: Jarret Hardie

Body:
So are you saying that you want to create a Many-to-many relationship from Request to RequestTypeInfo using RequestType as your intermediate Model?

class Request(models.Model):
    requester=models.CharField()
    dateRequested = models.DateField(auto_now=True)
    title= models.CharField(max_length=255)
    description = models.TextField()
    request_type = models.ManyToManyField(RequestType, through='RequestTypeInfo')

class RequestType(models.Model):
    requestType=models.CharField('Request Type', max_length=256)

class RequestTypeInfo(models.Model):
    requestType=models.ForeignKey('RequestType', verbose_name='Request Type')
    title = models.CharField('title', max_length=256)
    info = models.CharField(max_length=256, blank=True)

We can talk about inline admin models after this gets clarified.

OwnerDisplayName: Pete Karl II


问:
How to use Scrapy to parse PDFs without a specific .pdf-link?
I try to download PDFs but in case of https://ratsinformation.stadt-koeln.de/si0057.asp?__ksinr=23723 I see no .pdf links which could be grabbed by Scrapy. This example shows the missing .pdf in the URL https://ratsinformation.stadt-koeln.de/getfile.asp?id=850608&type=do.

Is Scrapy also able to handle getfile.asp links to detect the file itself?

This is the approach to get all the pdf links on a specific page:

```<code>import scrapy
from scrapy.pipelines.files import FilesPipeline

class PdfPipeline(FilesPipeline):
    # to save with the name of the pdf from the website instead of hash
    def file_path(self, request, response=None, info=None):
        file_name = request.url.split('/')[-1]
        return file_name

class StadtKoelnAmtsblattSpider(scrapy.Spider):
    name = 'stadt_koeln_amtsblatt'
    start_urls = ['https://ratsinformation.stadt-koeln.de/si0057.asp?__ksinr=23723']

    custom_settings = {
        "ITEM_PIPELINES": {
            PdfPipeline: 100
        },
        "FILES_STORE": "downloaded_files"
    }

    def parse(self, response):
        links = response.xpath("//a[@class='btn btn-blue']/@href").getall()
        links = [response.urljoin(link) for link in links]  # to make them absolute urls

        yield {
            "file_urls": links
        }
</code>```

I am receiving an error for each of the attempts to download the files.

```<code>OSError: [Errno 22] Invalid argument: 'downloaded_files\\getfile.asp?id=821665&type=do'
</code>```

答:
The error is caused by the PdfPipeline because the url does not have the filename so you have to obtain the filename in the parse method and then capture the name in the pipeline like below.

import scrapy
from scrapy.pipelines.files import FilesPipeline

class PdfPipeline(FilesPipeline):
    # to save with the name of the pdf from the website instead of hash
    def file_path(self, request, response=None, info=None, *, item=None):
        return item["filename"]

class StadtKoelnAmtsblattSpider(scrapy.Spider):
    name = 'stadt_koeln_amtsblatt'
    start_urls = ['https://ratsinformation.stadt-koeln.de/si0057.asp?__ksinr=23723']

    custom_settings = {
        "ITEM_PIPELINES": {
            PdfPipeline: 100
        },
        "FILES_STORE": "downloaded_files",
        "USER_AGENT": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36"
    }

    def parse(self, response):
        for i, item in enumerate(response.xpath("//a[contains(@title, 'Dokument Download')]")):
            title = item.xpath("./text()").get()
            urls = item.xpath("./@href").getall()
            if title:
                yield {
                    "filename": title + str(i) + ".pdf",# to take care of duplicated file names
                    "file_urls": [response.urljoin(url) for url in urls]
                }
```

Body:
I try to download PDFs but in case of https://ratsinformation.stadt-koeln.de/si0057.asp?__ksinr=23723 I see no .pdf links which could be grabbed by Scrapy. This example shows the missing .pdf in the URL https://ratsinformation.stadt-koeln.de/getfile.asp?id=850608&type=do.

Is Scrapy also able to handle getfile.asp links to detect the file itself?

This is the approach to get all the pdf links on a specific page:

import scrapy
from scrapy.pipelines.files import FilesPipeline

class PdfPipeline(FilesPipeline):
    # to save with the name of the pdf from the website instead of hash
    def file_path(self, request, response=None, info=None):
        file_name = request.url.split('/')[-1]
        return file_name

class StadtKoelnAmtsblattSpider(scrapy.Spider):
    name = 'stadt_koeln_amtsblatt'
    start_urls = ['https://ratsinformation.stadt-koeln.de/si0057.asp?__ksinr=23723']

    custom_settings = {
        "ITEM_PIPELINES": {
            PdfPipeline: 100
        },
        "FILES_STORE": "downloaded_files"
    }

    def parse(self, response):
        links = response.xpath("//a[@class='btn btn-blue']/@href").getall()
        links = [response.urljoin(link) for link in links]  # to make them absolute urls

        yield {
            "file_urls": links
        }

I am receiving an error for each of the attempts to download the files.

OSError: [Errno 22] Invalid argument: 'downloaded_files\\getfile.asp?id=821665&type=do'


问:
React-native-maps Blank page Only google logo
I've been trying to install google maps for react-native for a week an still no success. I've searched and tried the solutions in the react-native-maps github issue but still I get a blank page.

What I do:

```<code>react-native init myapp
npm install
yarn add react-native-maps
react-native link react-native-maps
</code>```

In Google Console APIs -> Create new Project -> Enable Google Maps Android API, Google Maps JavaScript API and Places API -> Create credentials

In AndroidManifest.xml

```<code>    <application>
....
       <meta-data
          android:name="com.google.android.geo.API_KEY"
          android:value="XXX"/>
    </application>
</code>```

package.json

```<code>    {
    "name": "maps",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "16.0.0",
        "react-native": "0.50.4",
        "react-native-maps": "^0.18.3"
    },
    "devDependencies": {
        "babel-jest": "21.2.0",
        "babel-preset-react-native": "4.0.0",
        "jest": "21.2.1",
        "react-test-renderer": "16.0.0"
    },
    "jest": {
        "preset": "react-native"
    }
}
</code>```

App.js

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import MapView from 'react-native-maps'

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
      <MapView
        style={styles.map}
        region={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121,
        }}
      >
      </MapView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});
</code>```

Edit:
Because some people asked me for stack trace: Sample 1

答:
Go to your

Google Console Developer Account

Select Your Respective Project

Android

Enable Maps SDK for Android

iOS

Enable Maps SDK for iOS

Body:
I've been trying to install google maps for react-native for a week an still no success. I've searched and tried the solutions in the react-native-maps github issue but still I get a blank page.

What I do:

react-native init myapp
npm install
yarn add react-native-maps
react-native link react-native-maps

In Google Console APIs -> Create new Project -> Enable Google Maps Android API, Google Maps JavaScript API and Places API -> Create credentials

In AndroidManifest.xml

    <application>
....
       <meta-data
          android:name="com.google.android.geo.API_KEY"
          android:value="XXX"/>
    </application>

package.json

    {
    "name": "maps",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start",
        "test": "jest"
    },
    "dependencies": {
        "react": "16.0.0",
        "react-native": "0.50.4",
        "react-native-maps": "^0.18.3"
    },
    "devDependencies": {
        "babel-jest": "21.2.0",
        "babel-preset-react-native": "4.0.0",
        "jest": "21.2.1",
        "react-test-renderer": "16.0.0"
    },
    "jest": {
        "preset": "react-native"
    }
}

App.js

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View
} from 'react-native';
import MapView from 'react-native-maps'

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
      <MapView
        style={styles.map}
        region={{
          latitude: 37.78825,
          longitude: -122.4324,
          latitudeDelta: 0.015,
          longitudeDelta: 0.0121,
        }}
      >
      </MapView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    ...StyleSheet.absoluteFillObject,
    alignItems: 'center',
  },
  map: {
    ...StyleSheet.absoluteFillObject,
  },
});

Edit:
Because some people asked me for stack trace: Sample 1