问:
HTML meta viewport is cutting my layout. Why is it happening?
I am building a responsive web page. Now I am going to start working with media queries, but when I insert <meta name="viewport" content="width=device-width"> and make the screen get smaller, part of the background of my header, first section and footer is cutted, remaining only a part of them and white space with their text. You can see it in the on the snippet. Why is it happening and what can I do do fix it?

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
body{
    font-family: 'Open Sans', sans-serif;
    margin: 0;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding: 0px 30px;
}
header img{
    width: 45px;
}
header h1{
    font-family: 'Doppio One', cursive;
    margin-left: 10px;
    color: rgb(214, 245, 210);
}
nav ul{
    display: flex;
    list-style: none;
}
nav ul li a{
    margin-left: 55px;
}
nav a{
    color: rgb(230, 245, 229);
    font-size: 17px;
}
nav a:hover{
    background-color: rgb(143, 182, 135);
    padding: 10px 15px;
    margin: 0 -15px 0 40px;
}
#firstsection{
    background-image: url(Images/coffee-3289259_1280.jpg);
    background-size: cover;
    height: 900px;
    position: relative;
}
#firstsection div{
    margin-top: 0;
    position: absolute;
    left: 100px;
    top: 150px;
    color: rgb(47, 119, 27);
    text-align: center;
}
#firstsection h1{
    margin-bottom: 45px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#textboxes{
    display: flex;
    margin-top: 50px;
}
#middlesection div div{
    text-align: center;
    margin: 15px 60px;
    border: 2px solid rgb(93, 158, 76);
    padding: 30px 30px;
}
#middlesection img:first-of-type{
    width: 55px;
}
#middlesection h2{
    text-align: center;
    width: 100%;
}
#lastsection{
    text-align: center;
}
#lastsection img{
    width: 500px;
    margin: 100px auto 0px;
}
#lastsection div{
    position: relative;
    bottom: 450px;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    padding: 15px;
    color: rgb(214, 245, 210);
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
footer img{
    height: 35px;
    width: 35px;
    margin-right: 15px;
}
footer div{
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="stylesheet.css">
        <link rel="stylesheet" type="text/css" href="https://necolas.github.io/normalize.css/8.0.1/normalize.css">
    </head>
    <body>
        <header>
            <img src="Images/icons8-fund-accounting-80.png">
            <h1>Finances</h1>
            <nav>
                <ul>
                    <li>Home</li>
                    <li>About</li>
                    <li>Contact us</li>
                    <li>Register</li>
                    <li>Login</li>
                </ul>
            </nav>
        </header>
        <main>
            <section id="firstsection">
                <div>
                    <h1>Manage your money easily, anywhere, anytime.</h1>
                    Get started
                </div>
            </section>
            <section id="middlesection">
                <div id="textboxes">
                    <div>
                        <img src="Images/icons8-increase-64.png">
                        <h3>Concrete data</h3>
                        <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-navigation-toolbar-left-filled-50 (1).png">
                        <h3>Easy interface</h3>
                        <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
                    </div>
                    <div>
                        <img src="Images/icons8-natural-user-interface-2-filled-50.png">
                        <h3>Fast access</h3>
                        <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
                    </div>
                </div>
            </section>
            <section id="lastsection">
                <img src="Images/board-1362851_1280.png">
                <div>
                    <h2>Register now and enjoy<br>the best of Finances.</h2>
                    Create an account
                </div>
            </section>
        </main>
        <footer>
            <img src="Images/icons8-fund-accounting-80.png">
            <div>
                <p>A work of Bruno Sdoukos.</p>
            </div>
        </footer>
    </body>
</html></code>```

答:
Have made some changes to your code. The initial problem was with the midsection. When the midsection has a width greater than the screen width a horizontal scrollbar appears to allow the user to see the rest of the content.

To fix that you could make the alignment vertical instead of horizontal depending on the width of the screen. In the solution below I wrap the content.

The second problem was when the width of the contents in the header exceeds the width of the screen that is when the width of the container tries to be the same width as the screen(remember the meta name="viewport") but the content overflows(as it has a greater width).

To fix that you could show your header items inside of a menu. In my solution below I have just made it take no space in the header(display: none). E.g solution might be like this.

NOTE: The solution below does not have elegant styling maybe you could add a padding here and there to make it look elegant

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Finances | Manage your money easily</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <meta
      name="description"
      content="Control you spending and manage your money easily. Your finances by the short hairs."
    />
    <meta name="author" content="Bruno M. B. Sdoukos" />
    <meta
      name="keywords"
      content="finances, managing money, spending control"
    />
    <link rel="stylesheet" type="text/css" href="stylesheet.css" />
    <link
      rel="stylesheet"
      type="text/css"
      href="https://necolas.github.io/normalize.css/8.0.1/normalize.css"
    />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
    />
  </head>
  <body>
    <script>
      function myFunction() {
        var x = document.getElementById("topulid");
        if (x.className === "topul") {
          x.className += " responsive";
        } else {
          x.className = "topul";
        }
      }
    </script>
    <header>
      <a href="index.html"><img src="Images/icons8-fund-accounting-80.png"/></a>
      <a href="index.html"><h1>Finances</h1></a>
      <div class="topnav" id="myTopnav">
        <a href="#home" class="active">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="#about">About</a>
        <a href="javascript:void(0);" class="icon" onclick="myFunction()">
          <i class="fa fa-bars"></i>
        </a>
      </div>
    </header>

    <main>
      <section id="firstsection">
        <div>
          <h1>Manage your money easily, anywhere, anytime.</h1>
          <a href="#">Get started</a>
        </div>
      </section>
      <section id="middlesection">
        <div id="textboxes">
          <div>
            <img src="Images/icons8-increase-64.png" />
            <h3>Concrete data</h3>
            <p>
              Simple but concrete data that are the answer to all the quesions
              about your current money, spending and.
            </p>
          </div>
          <div>
            <img
              src="Images/icons8-navigation-toolbar-left-filled-50 (1).png"
            />
            <h3>Easy interface</h3>
            <p>
              An interface easy to use, made to you who want to manage your
              money faster and with no problems.
            </p>
          </div>
          <div>
            <img src="Images/icons8-natural-user-interface-2-filled-50.png" />
            <h3>Fast access</h3>
            <p>
              No complications that make you lose time. Just some clicks and
              done, you are in Finances, with all you need.
            </p>
          </div>
        </div>
      </section>
      <section id="lastsection">
        <img src="Images/board-1362851_1280.png" />
        <div>
          <h2>Register now and enjoy<br />the best of Finances.</h2>
          <a href="#">Create an account</a>
        </div>
      </section>
    </main>
    <footer>
      <img src="Images/icons8-fund-accounting-80.png" />
      <div>
        <p>A work of Bruno Sdoukos.</p>
      </div>
    </footer>
  </body>
</html>
</code>```

```<code>@charset "UTF-8";
@import url("https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap");
body {
  font-family: "Open Sans", sans-serif;
  margin: 0;
}
a {
  text-decoration: none;
  transition: 0.2s linear;
}
header {
  background-color: rgb(93, 158, 76);
  display: flex;
  align-items: center;
}
header img {
  width: 45px;
}
header h1 {
  font-family: "Doppio One", cursive;
  margin-left: 10px;
  color: rgb(214, 245, 210);
}

.topnav {
  overflow: hidden;
  flex: 1;
  display: flex;
  justify-content: space-around;
  align-items: center;
  max-width: 500px;
  padding-left: 50px;
}

.topnav a {
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav .icon {
  display: none;
}

.icon {
  display: none;
}

#firstsection {
  background-image: url(Images/coffee-3289259_1280.jpg);
  background-size: cover;
  height: 900px;
  position: relative;
}
#firstsection div {
  margin-top: 0;
  position: absolute;
  left: 100px;
  top: 150px;
  color: rgb(47, 119, 27);
  text-align: center;
}
#firstsection h1 {
  margin-bottom: 45px;
}
#firstsection div a {
  font-weight: bold;
  border: 2px solid rgb(47, 119, 27);
  padding: 13px 30px;
  font-size: 16.5px;
  color: rgb(47, 119, 27);
}
#firstsection div a:hover {
  color: rgb(133, 163, 131);
  border: 2px solid rgb(133, 163, 131);
}
#textboxes {
  display: flex;
  /* flex-wrap: wrap; */
  margin-top: 50px;
  justify-content: space-around;
  flex-wrap: wrap;
}
#middlesection div div {
  text-align: center;
  /* margin: 15px 0px; */
  border: 2px solid rgb(93, 158, 76);
  padding: 30px 30px;
  max-width: 300px;
}
#middlesection img:first-of-type {
  width: 55px;
}
#middlesection h2 {
  text-align: center;
  width: 100%;
}
#lastsection {
  text-align: center;
}
#lastsection img {
  width: 500px;
  margin: 100px auto 0px;
}
#lastsection div {
  position: relative;
  bottom: 450px;
}
#lastsection div a:visited {
  color: blue;
}
footer {
  background-color: rgb(93, 158, 76);
  padding: 15px;
  color: rgb(214, 245, 210);
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}
footer img {
  height: 35px;
  width: 35px;
  margin-right: 15px;
}
footer div {
  text-align: center;
}

@media screen and (max-width: 830px) {
  .topnav a {
    display: none;
  }
  .icon {
    float: right;
    display: block;
  }
}

</code>```

Body:
I am building a responsive web page. Now I am going to start working with media queries, but when I insert <meta name="viewport" content="width=device-width"> and make the screen get smaller, part of the background of my header, first section and footer is cutted, remaining only a part of them and white space with their text. You can see it in the on the snippet. Why is it happening and what can I do do fix it?

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
body{
    font-family: 'Open Sans', sans-serif;
    margin: 0;
}
a{
    text-decoration: none;
    transition: 0.2s linear;
}
header{
    background-color: rgb(93, 158, 76);
    display: flex;
    align-items: center;
    padding: 0px 30px;
}
header img{
    width: 45px;
}
header h1{
    font-family: 'Doppio One', cursive;
    margin-left: 10px;
    color: rgb(214, 245, 210);
}
nav ul{
    display: flex;
    list-style: none;
}
nav ul li a{
    margin-left: 55px;
}
nav a{
    color: rgb(230, 245, 229);
    font-size: 17px;
}
nav a:hover{
    background-color: rgb(143, 182, 135);
    padding: 10px 15px;
    margin: 0 -15px 0 40px;
}
#firstsection{
    background-image: url(Images/coffee-3289259_1280.jpg);
    background-size: cover;
    height: 900px;
    position: relative;
}
#firstsection div{
    margin-top: 0;
    position: absolute;
    left: 100px;
    top: 150px;
    color: rgb(47, 119, 27);
    text-align: center;
}
#firstsection h1{
    margin-bottom: 45px;
}
#firstsection div a{
    font-weight: bold;
    border: 2px solid rgb(47, 119, 27);
    padding: 13px 30px;
    font-size: 16.5px;
    color: rgb(47, 119, 27);
}
#firstsection div a:hover{
    color: rgb(133, 163, 131);
    border: 2px solid rgb(133, 163, 131);
}
#textboxes{
    display: flex;
    margin-top: 50px;
}
#middlesection div div{
    text-align: center;
    margin: 15px 60px;
    border: 2px solid rgb(93, 158, 76);
    padding: 30px 30px;
}
#middlesection img:first-of-type{
    width: 55px;
}
#middlesection h2{
    text-align: center;
    width: 100%;
}
#lastsection{
    text-align: center;
}
#lastsection img{
    width: 500px;
    margin: 100px auto 0px;
}
#lastsection div{
    position: relative;
    bottom: 450px;
}
#lastsection div a:visited{
    color: blue;
}
footer{
    background-color: rgb(93, 158, 76);
    padding: 15px;
    color: rgb(214, 245, 210);
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
footer img{
    height: 35px;
    width: 35px;
    margin-right: 15px;
}
footer div{
    text-align: center;
}

<!DOCTYPE html>

        <title>Finances | Manage your money easily</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta name="description" content="Control you spending and manage your money easily. Your finances by the short hairs.">
        <meta name="author" content="Bruno M. B. Sdoukos">
        <meta name="keywords" content="finances, managing money, spending control">
        <link rel="stylesheet" type="text/css" href="stylesheet.css">
        <link rel="stylesheet" type="text/css" href="https://necolas.github.io/normalize.css/8.0.1/normalize.css">

Finances

Home

About

Contact us

Register

Login

Manage your money easily, anywhere, anytime.

                    Get started

Concrete data

Simple but concrete data that are the answer to all the quesions about your current money, spending and.

Easy interface

An interface easy to use, made to you who want to manage your money faster and with no problems.

Fast access

No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.

Register now and enjoy
the best of Finances.

                    Create an account

A work of Bruno Sdoukos.

Body:
Have made some changes to your code. The initial problem was with the midsection. When the midsection has a width greater than the screen width a horizontal scrollbar appears to allow the user to see the rest of the content.

To fix that you could make the alignment vertical instead of horizontal depending on the width of the screen. In the solution below I wrap the content.

The second problem was when the width of the contents in the header exceeds the width of the screen that is when the width of the container tries to be the same width as the screen(remember the meta name="viewport") but the content overflows(as it has a greater width).

To fix that you could show your header items inside of a menu. In my solution below I have just made it take no space in the header(display: none). E.g solution might be like this.

NOTE: The solution below does not have elegant styling maybe you could add a padding here and there to make it look elegant

<!DOCTYPE html>
<html>
  <head>
    <title>Finances | Manage your money easily</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <meta
      name="description"
      content="Control you spending and manage your money easily. Your finances by the short hairs."
    />
    <meta name="author" content="Bruno M. B. Sdoukos" />
    <meta
      name="keywords"
      content="finances, managing money, spending control"
    />
    <link rel="stylesheet" type="text/css" href="stylesheet.css" />
    <link
      rel="stylesheet"
      type="text/css"
      href="https://necolas.github.io/normalize.css/8.0.1/normalize.css"
    />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
    />
  </head>
  <body>
    <script>
      function myFunction() {
        var x = document.getElementById("topulid");
        if (x.className === "topul") {
          x.className += " responsive";
        } else {
          x.className = "topul";
        }
      }
    </script>
    <header>
      <a href="index.html"><img src="Images/icons8-fund-accounting-80.png"/></a>
      <a href="index.html"><h1>Finances</h1></a>
      <div class="topnav" id="myTopnav">
        <a href="#home" class="active">Home</a>
        <a href="#news">News</a>
        <a href="#contact">Contact</a>
        <a href="#about">About</a>
        <a href="javascript:void(0);" class="icon" onclick="myFunction()">
          <i class="fa fa-bars"></i>
        </a>
      </div>
    </header>

    <main>
      <section id="firstsection">
        <div>
          <h1>Manage your money easily, anywhere, anytime.</h1>
          <a href="#">Get started</a>
        </div>
      </section>
      <section id="middlesection">
        <div id="textboxes">
          <div>
            <img src="Images/icons8-increase-64.png" />
            <h3>Concrete data</h3>
            <p>
              Simple but concrete data that are the answer to all the quesions
              about your current money, spending and.
            </p>
          </div>
          <div>
            <img
              src="Images/icons8-navigation-toolbar-left-filled-50 (1).png"
            />
            <h3>Easy interface</h3>
            <p>
              An interface easy to use, made to you who want to manage your
              money faster and with no problems.
            </p>
          </div>
          <div>
            <img src="Images/icons8-natural-user-interface-2-filled-50.png" />
            <h3>Fast access</h3>
            <p>
              No complications that make you lose time. Just some clicks and
              done, you are in Finances, with all you need.
            </p>
          </div>
        </div>
      </section>
      <section id="lastsection">
        <img src="Images/board-1362851_1280.png" />
        <div>
          <h2>Register now and enjoy<br />the best of Finances.</h2>
          <a href="#">Create an account</a>
        </div>
      </section>
    </main>
    <footer>
      <img src="Images/icons8-fund-accounting-80.png" />
      <div>
        <p>A work of Bruno Sdoukos.</p>
      </div>
    </footer>
  </body>
</html>

@charset "UTF-8";
@import url("https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap");
body {
  font-family: "Open Sans", sans-serif;
  margin: 0;
}
a {
  text-decoration: none;
  transition: 0.2s linear;
}
header {
  background-color: rgb(93, 158, 76);
  display: flex;
  align-items: center;
}
header img {
  width: 45px;
}
header h1 {
  font-family: "Doppio One", cursive;
  margin-left: 10px;
  color: rgb(214, 245, 210);
}

.topnav {
  overflow: hidden;
  flex: 1;
  display: flex;
  justify-content: space-around;
  align-items: center;
  max-width: 500px;
  padding-left: 50px;
}

.topnav a {
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav .icon {
  display: none;
}

.icon {
  display: none;
}

#firstsection {
  background-image: url(Images/coffee-3289259_1280.jpg);
  background-size: cover;
  height: 900px;
  position: relative;
}
#firstsection div {
  margin-top: 0;
  position: absolute;
  left: 100px;
  top: 150px;
  color: rgb(47, 119, 27);
  text-align: center;
}
#firstsection h1 {
  margin-bottom: 45px;
}
#firstsection div a {
  font-weight: bold;
  border: 2px solid rgb(47, 119, 27);
  padding: 13px 30px;
  font-size: 16.5px;
  color: rgb(47, 119, 27);
}
#firstsection div a:hover {
  color: rgb(133, 163, 131);
  border: 2px solid rgb(133, 163, 131);
}
#textboxes {
  display: flex;
  /* flex-wrap: wrap; */
  margin-top: 50px;
  justify-content: space-around;
  flex-wrap: wrap;
}
#middlesection div div {
  text-align: center;
  /* margin: 15px 0px; */
  border: 2px solid rgb(93, 158, 76);
  padding: 30px 30px;
  max-width: 300px;
}
#middlesection img:first-of-type {
  width: 55px;
}
#middlesection h2 {
  text-align: center;
  width: 100%;
}
#lastsection {
  text-align: center;
}
#lastsection img {
  width: 500px;
  margin: 100px auto 0px;
}
#lastsection div {
  position: relative;
  bottom: 450px;
}
#lastsection div a:visited {
  color: blue;
}
footer {
  background-color: rgb(93, 158, 76);
  padding: 15px;
  color: rgb(214, 245, 210);
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}
footer img {
  height: 35px;
  width: 35px;
  margin-right: 15px;
}
footer div {
  text-align: center;
}

@media screen and (max-width: 830px) {
  .topnav a {
    display: none;
  }
  .icon {
    float: right;
    display: block;
  }
}


来源: stackexchange

问:
C++ / GoogleTest - How to test member variable of a class being tested
I'm creating tests for a legacy code and wondering if it is possible to check the values of member variables of a class like this (I know my code below is very lousy, bad example :/. Hope to just please focus on the question):

```<code>class Animal
{
public:
   RESULT getInfo();
   int age_;
};

int main()
{
   Animal animal;
   RESULT result = animal.getInfo();

   return 0;
}

RESULT Animal::getInfo()
{
    age_ = rand() % 10 + 1;
    if (age == 5)
    {
        return success;
    }
    else
    {
        return fail;
    }
}
</code>```

And in my test (using Google Test), I call getInfo():

```<code>EXPECT_EQ(success, sut_->getInfo());
</code>```

However, this just verifies that the result of getInfo() is success.  Is there any other way for me to check the value of age_ without adding a new method/changing the return value?
Thanks!

答: As you have already made age_ public, you can just add another EXPECT_EQ statement. If making age_ public was not intentional then you will have to come with a method to access age_ in GTest code.

ContentLicense: CC BY-SA 4.0

Body:
I'm creating tests for a legacy code and wondering if it is possible to check the values of member variables of a class like this (I know my code below is very lousy, bad example :/. Hope to just please focus on the question):

class Animal
{
public:
   RESULT getInfo();
   int age_;
};

int main()
{
   Animal animal;
   RESULT result = animal.getInfo();

   return 0;
}

RESULT Animal::getInfo()
{
    age_ = rand() % 10 + 1;
    if (age == 5)
    {
        return success;
    }
    else
    {
        return fail;
    }
}

And in my test (using Google Test), I call getInfo():

EXPECT_EQ(success, sut_->getInfo());

However, this just verifies that the result of getInfo() is success.  Is there any other way for me to check the value of age_ without adding a new method/changing the return value?
Thanks!


问:
load a typescript file in another typescript file by using reference
I'm new to Typescript. I'd like to load a Typescript file in another Typescript file by using the <reference> tag.

I did something but it doesn't work! Please help me.

first.ts:

```<code>import * as $ from './JQuery';

alert("Message 2: I want to run!");
$("#myParagraph").click(function () {
    alert("hello!");
});
</code>```

app.ts:

```<code>/// <reference path="./first.ts"/>

alert("Message 1: app.ts loaded!");
</code>```

output app.ts is app.js (automatic generated)

```<code>/// <reference path="./first.ts"/>
alert("Message 1: app.ts loaded!");
</code>```

As you see that, contains of first.ts did not load in app.js file.
How can I solve this problem?

tsconfig.json:

```<code>{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "../wwwroot/scripts",
    "module": "umd"
  }
}
</code>```

答:
Use the --outFile parameter to the TypeScript compiler to concatenate everything into one file. The browser won't parse the <reference> tag.

Like this:

tsc --outFile my-big-javascript.js

Body:
I'm new to Typescript. I'd like to load a Typescript file in another Typescript file by using the <reference> tag.

I did something but it doesn't work! Please help me.

first.ts:

import * as $ from './JQuery';

alert("Message 2: I want to run!");
$("#myParagraph").click(function () {
    alert("hello!");
});

app.ts:

/// <reference path="./first.ts"/>

alert("Message 1: app.ts loaded!");

output app.ts is app.js (automatic generated)

/// <reference path="./first.ts"/>
alert("Message 1: app.ts loaded!");

As you see that, contains of first.ts did not load in app.js file.
How can I solve this problem?

tsconfig.json:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "../wwwroot/scripts",
    "module": "umd"
  }
}


问:
xpath - upper case and lower case button text
I have multiple ok buttons in my application in the combinations: OK, ok, oK and Ok. How can i write a single @findby expression to identify all of them with the one webelement.
Code example</p>

```<code><button type="button">OK</button>
</code>```

答:
Here is the other solution in pure xpath 1.0 using xpath functions.

```<code> //button[contains('OK,ok,Ok,oK',text())][string-length('OK')=2]
</code>```

or

```<code>//button[contains('OK,ok,Ok,oK',text())][string-length(text())=string-length('OK')]
</code>```

Edit: Simple approach using translate

```<code>//button[translate(text(),'ok','OK')='OK']
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have multiple ok buttons in my application in the combinations: OK, ok, oK and Ok. How can i write a single @findby expression to identify all of them with the one webelement.
Code example

<button type="button">OK</button>

Body:
Here is the other solution in pure xpath 1.0 using xpath functions.

 //button[contains('OK,ok,Ok,oK',text())][string-length('OK')=2]

or

//button[contains('OK,ok,Ok,oK',text())][string-length(text())=string-length('OK')]

Edit: Simple approach using translate

//button[translate(text(),'ok','OK')='OK']


问:
What does ' ' (tow single quotations marks, one after the other, not the double that come together) do?
I'm printing this in Python (3.6)

```<code>print(' 'f' ')
</code>```

and it shows nothing!
What is happening?

It sounds like whatever I put inside the inner ' ', vanish.

答:
' ' is a string literal representing a single space. This is something pretty much any Python programmer needs to be thoroughly familiar with.

f' ' is an f-string. If there were any braces in there, it would do string interpolation, but there are no braces. Like ' ', it ends up evaluating to a string representing a single space.

When two string literals appear side by side, Python implicitly concatenates them, as if you had used +, but with super-high precedence. This is an obscure feature that causes more bugs than it's worth.

Putting all that together, ' 'f' ' evaluates to a string containing two spaces, so you don't see anything when you print it, because you can't see spaces.

Body:
I'm printing this in Python (3.6)

print(' 'f' ')

and it shows nothing!
What is happening?

It sounds like whatever I put inside the inner ' ', vanish.


答:
In the above case, Spark is trying to convert the String value to  Boolean. It is not evaluating the expression itself.

And expression evaluation has to be done by the user using an external library or custom code.

The closest(Not the exact scenario though) I could come up is

How to evaluate a math expression given in string form? .

Title: Spark: Aggregation with dynamic filter on a dataframe in scala

Body:
I have a dataframe like

scala> testDf.show()
+------+--------+---------+------------+----------------------------------------+
|    id|    item|    value|  value_name|                               condition|
+------+--------+---------+------------+----------------------------------------+
|    11|    3210|        0|         OFF|                                value==0|
|    12|    3210|        1|         OFF|                                value==0|
|    13|    3210|        0|         OFF|                                value==0|
|    14|    3210|        0|         OFF|                                value==0|
|    15|    3210|        1|         OFF|                                value==0|
|    16|    5440|        5|          ON|                     value>0 && value<10|
|    17|    5440|        0|          ON|                     value>0 && value<10|
|    18|    5440|        6|          ON|                     value>0 && value<10|
|    19|    5440|        7|          ON|                     value>0 && value<10|
|    20|    5440|        0|          ON|                     value>0 && value<10|
|    21|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    22|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    23|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    24|    7780|        C|        TYPE|   Set("A","B").contains(value.toString)|
|    25|    7780|        C|        TYPE|   Set("A","B").contains(value.toString)|
+------+--------+---------+------------+----------------------------------------+

scala> testDf.printSchema
root
 |-- id: string (nullable = true)
 |-- item: string (nullable = true)
 |-- value: string (nullable = true)
 |-- value_name: string (nullable = true)
 |-- condition: string (nullable = true)

I want to remove some rows with 'condition' column.
But I am in trouble.

I tried with below test code.
But it does not seem to work properly.

import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.Row
import scala.collection.mutable

val encoder = RowEncoder(testDf.schema);

testDf.flatMap(row => {
  val result = new mutable.MutableList[Row];
  val setting_value = row.getAs[String]("setting_value").toInt
  val condition = row.getAs[String]("condition").toBoolean
  if (condition){
      result+=row;
  };
  result;
})(encoder).show();

And This is error.

19/05/30 02:04:31 ERROR TaskSetManager: Task 0 in stage 267.0 failed 4 times; aborting job
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 267.0 failed 4 times, most recent failure: Lost task 0.3 in stage 267.0 (TID 3763, .compute.internal, executor 1): java.lang.IllegalArgumentException: For input string: "setting_value==0"
        at scala.collection.immutable.StringLike$class.parseBoolean(StringLike.scala:291)
        at scala.collection.immutable.StringLike$class.toBoolean(StringLike.scala:261)
        at scala.collection.immutable.StringOps.toBoolean(StringOps.scala:29)
        at $anonfun$1.apply(<console>:40)
        at $anonfun$1.apply(<console>:37)
        at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:435)
        at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:441)
        at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:409)
        at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage3.processNext(Unknown Source)
        at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
        at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$11$$anon$1.hasNext(WholeStageCodegenExec.scala:619)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:255)
        at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:247)
        at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)
        at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
        at org.apache.spark.scheduler.Task.run(Task.scala:121)
        at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
        at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

I want to keep rows that match the value of the condition column.
This is the desired result.

+------+--------+---------+------------+----------------------------------------+
|    id|    item|    value|  value_name|                               condition|
+------+--------+---------+------------+----------------------------------------+
|    11|    3210|        0|         OFF|                                value==0|
|    13|    3210|        0|         OFF|                                value==0|
|    14|    3210|        0|         OFF|                                value==0|
|    16|    5440|        5|          ON|                     value>0 && value<10|
|    18|    5440|        6|          ON|                     value>0 && value<10|
|    19|    5440|        7|          ON|                     value>0 && value<10|
|    21|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    22|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
|    23|    7780|        A|        TYPE|   Set("A","B").contains(value.toString)|
+------+--------+---------+------------+----------------------------------------+

Please help me if you have a good idea.
Thanks.


问:
Can someone help me debug my tic tac toe game?
I'm making a tic-tac-toe game using html, css, and javascript. I have managed to make some progress on it, but there are two bugs that I haven't been able to figure out no matter how hard I look.

The first one is that it won't take in an input on the last block (9). After I added the code for checking wins and ties it no longer worked.

The second one is that the AI starts playing on my second move, not on the first one. It must be a simple logic error, but I just don't see it.

Here's my code on repl.it:
https://repl.it/@julkothegu1/Yes

Thanks.

答:
The problem is that you're using the array index as value for your ID. However, the array counting starts at 0 while your ID's start at 1.

This ends up that on the first play, the computes tries to play on id "0", which does not exists.

And when you click on the last element, there's also a missmatch between id and index.

To fix both problems, start your ID count on 0 at your HTML.


问:
error with a drawer navigation in react-native :undefined is not an object (evaluating '_this.props.navigation.openDrawer()')
I had set up a navigator drawer that works perfectly, but since this morning I have this error. I do not know where it came from. Because I did not make any changes on the drawer.
I can't use the function close drawer.

```<code>
   <Left style={{flex :1, flexDirection: 'row'}}>
       <Icon
              onPress={() => this.props.navigation.openDrawer()} name="menu"
              tyle={{color: 'black', marginRight: 15,}} />
   </Left>

</code>```

the error is  :

undefined is not an object (evaluating '_this.props.navigation.openDrawer()')

答:
You can Try this</p>

```<code>import { DrawerActions } from 'react-navigation';

this.props.navigation.dispatch(DrawerActions.closeDrawer());
this.props.navigation.dispatch(DrawerActions.openDrawer());
</code>```

Body:
I had set up a navigator drawer that works perfectly, but since this morning I have this error. I do not know where it came from. Because I did not make any changes on the drawer.
I can't use the function close drawer.

   <Left style={{flex :1, flexDirection: 'row'}}>
       <Icon
              onPress={() => this.props.navigation.openDrawer()} name="menu"
              tyle={{color: 'black', marginRight: 15,}} />
   </Left>

the error is  :

undefined is not an object (evaluating '_this.props.navigation.openDrawer()')

Body:
You can Try this

import { DrawerActions } from 'react-navigation';

this.props.navigation.dispatch(DrawerActions.closeDrawer());
this.props.navigation.dispatch(DrawerActions.openDrawer());


问:
How to mock resttemplate by mockito
I want to mock a resttemplate request,but it seems not work.
Here is the class that i want test:

public class SomeUtil {
    public static OrderInstanceResponse doGet(String url, otherargs...) {
       //some code...
       ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestHeader, String.class, requestMap);
       //another code...
    }
}
```

<p>Here is the Test Class:</p>

<pre class="lang-java prettyprint-override"><code>@RunWith(MockitoJUnitRunner.class)
public class SomeUtilTest {
    @Mock
    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void doGet() {
        OrderInstanceResponse exceptResponse = OrderInstanceResponse.builder().code("123").build();
        OrderInstanceRequest request = OrderInstanceRequest.builder().userId("123").build();

        Map<String, Object> testMap = new HashMap<>(1);
        testMap.put("userId", "123");

        Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.eq(String.class), Mockito.eq(testMap)))
                .thenReturn(new ResponseEntity<>("\"code\":\"123\"", HttpStatus.OK));

        OrderInstanceResponse actualResponse = RestTemplateUtil.doGet("123", request, "123");
        Assert.assertEquals(actualResponse.getCode(), exceptResponse.getCode());
    }
}
</code>```

There are some errors when I run this test:
java.lang.IllegalArgumentException: URI is not absolute.

It seems that mock not work,There was a real request to "123".

How can i fix this bug?thanks

答:
You need to pass a RestTemplate instance to the RestTemplateUtil as a dependency for this to work, rather than instantiating it in the doGet method. Then, in the unit test pass the mock RestTemplate instance to the RestTemplateUtil.

```<code>public class SomeUtil {
    public SomeUtil(RestTemplate restTemplate) { this.restTemplate = restTemplate }
    public OrderInstanceResponse doGet(String url, otherargs...) {
        ResponseEntity<String> responseEntity = this.restTemplate.exchange(...
    }
}
</code>```

Or pass RestTemplate as a parameter if you want to keep it as a static method.

Title: How to mock resttemplate by mockito

Body:
I want to mock a resttemplate request,but it seems not work.
Here is the class that i want test:

public class SomeUtil {
    public static OrderInstanceResponse doGet(String url, otherargs...) {
       //some code...
       ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestHeader, String.class, requestMap);
       //another code...
    }
}

Here is the Test Class:

@RunWith(MockitoJUnitRunner.class)
public class SomeUtilTest {
    @Mock
    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void doGet() {
        OrderInstanceResponse exceptResponse = OrderInstanceResponse.builder().code("123").build();
        OrderInstanceRequest request = OrderInstanceRequest.builder().userId("123").build();

        Map<String, Object> testMap = new HashMap<>(1);
        testMap.put("userId", "123");

        Mockito.when(restTemplate.exchange(Mockito.anyString(), Mockito.any(), Mockito.any(), Mockito.eq(String.class), Mockito.eq(testMap)))
                .thenReturn(new ResponseEntity<>("\"code\":\"123\"", HttpStatus.OK));

        OrderInstanceResponse actualResponse = RestTemplateUtil.doGet("123", request, "123");
        Assert.assertEquals(actualResponse.getCode(), exceptResponse.getCode());
    }
}

There are some errors when I run this test:
java.lang.IllegalArgumentException: URI is not absolute.

It seems that mock not work,There was a real request to "123".

How can i fix this bug?thanks

Body:
You need to pass a RestTemplate instance to the RestTemplateUtil as a dependency for this to work, rather than instantiating it in the doGet method. Then, in the unit test pass the mock RestTemplate instance to the RestTemplateUtil.

public class SomeUtil {
    public SomeUtil(RestTemplate restTemplate) { this.restTemplate = restTemplate }
    public OrderInstanceResponse doGet(String url, otherargs...) {
        ResponseEntity<String> responseEntity = this.restTemplate.exchange(...
    }
}

Or pass RestTemplate as a parameter if you want to keep it as a static method.


问:
Coroutines: Overriding OKHttp's dispatcher to use AsyncTasks's ThreadPoolExecutor so Espresso can assert successfully
I am migrating an app that uses Retrofit to work with coroutines. The app has some UATs that are failing because Espresso does not wait for the coroutines to complete and asserts immediately.

The CoroutineCallAdapterFactory, by default, uses OkHttp's Dispatcher to perform asynchronous requests, but Espresso only monitors the UI Thread and AsyncTaks's Thread pool. One solution I thought of is to force OkHttp's Dispatcher to use AsyncTask's ThreadPoolExecutor.

```<code>val dispatcher = Dispatcher(AsyncTask.THREAD_POOL_EXECUTOR as ExecutorService)
okHttpClientBuilder.dispatcher(dispatcher)
</code>```

This seems to work and the tests pass.

Is this a bad idea? Is registering an IdlingResource still a better option?

答:
Without more details of your setup, I'm not sure if this information will help but I'll mention a few tips that may help with your tests:

Convert Executors

You can also go the other way and create a coroutine dispatcher from any executor using:

```<code>AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
</code>```

And of course, this can be used anyplace you'd have something like Dispatchers.Main meaning you can create a scope from this and launch your coroutines from that scope and Espresso should monitor the underlying executor pool for completion. For example:

```<code>...
val espressoScope = CoroutineScope(AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher())
...
espressoScope.launch { api.getBooks() }
</code>```

Similarly, you can do things like:

```<code>val asyncTaskContext = AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
withContext(asyncTaskContext) {
    api.getBooks()
}

// OR:

@Test
fun someAndroidTest() = runBlocking(asyncTaskContext) {
    // espresso logic
}

</code>```

Join Jobs (recommended)

Last but not least, you can join any jobs that you create in your test and the test will wait until the job completes before exiting. This sounds like the approach that would help most in your situation since you really just want to wait until the coroutines are complete:

```<code>@Test
fun `first book has a title`() = runBlocking {
    launch {
        // run a function that suspends and takes a while
        val firstBook = api.getAllBooks().first()
        assertNotNull(firstBook.title)
    }.join()
}
</code>```

Body:
I am migrating an app that uses Retrofit to work with coroutines. The app has some UATs that are failing because Espresso does not wait for the coroutines to complete and asserts immediately.

The CoroutineCallAdapterFactory, by default, uses OkHttp's Dispatcher to perform asynchronous requests, but Espresso only monitors the UI Thread and AsyncTaks's Thread pool. One solution I thought of is to force OkHttp's Dispatcher to use AsyncTask's ThreadPoolExecutor.

val dispatcher = Dispatcher(AsyncTask.THREAD_POOL_EXECUTOR as ExecutorService)
okHttpClientBuilder.dispatcher(dispatcher)

This seems to work and the tests pass.

Is this a bad idea? Is registering an IdlingResource still a better option?

Body:
Without more details of your setup, I'm not sure if this information will help but I'll mention a few tips that may help with your tests:

Convert Executors

You can also go the other way and create a coroutine dispatcher from any executor using:

AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()

And of course, this can be used anyplace you'd have something like Dispatchers.Main meaning you can create a scope from this and launch your coroutines from that scope and Espresso should monitor the underlying executor pool for completion. For example:

...
val espressoScope = CoroutineScope(AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher())
...
espressoScope.launch { api.getBooks() }

Similarly, you can do things like:

val asyncTaskContext = AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
withContext(asyncTaskContext) {
    api.getBooks()
}

// OR:

@Test
fun someAndroidTest() = runBlocking(asyncTaskContext) {
    // espresso logic
}

Join Jobs (recommended)

Last but not least, you can join any jobs that you create in your test and the test will wait until the job completes before exiting. This sounds like the approach that would help most in your situation since you really just want to wait until the coroutines are complete:

@Test
fun `first book has a title`() = runBlocking {
    launch {
        // run a function that suspends and takes a while
        val firstBook = api.getAllBooks().first()
        assertNotNull(firstBook.title)
    }.join()
}


问:
What namespace does CertificateWebRequestHandlerModifierOptions live in?
Using Sitecore 9.1.1 I am try to connect to my xconnect server with a console app using the sample code found here: https://doc.sitecore.com/developers/90/sitecore-experience-platform/en/create,-retrieve,-and-search-contact-and-interaction-data.html

I have used NuGet (Sitecore MyGet) to retrieve the libraries that are being used:

```<code>using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using Sitecore.XConnect.Schema;
using System;
using System.Threading.Tasks;
using Sitecore.XConnect.Client.WebApi;
using Sitecore.Xdb.Common.Web;
using Sitecore.XConnect.Collection.Model;
using System.Collections.Generic;
using Sitecore.Xdb.Common.Web;
</code>```

However....

With in Visual Studio 2019 CertificateWebRequestHandlerModifierOptions and CertificateWebRequestHandlerModifier are red-lined with "namespace could not be found, are you missing assembly.."

I have googled and cannot find which libraries these classes live in. Can someone tell me please?

答:
Turns out that these two classes have been renamed in Sitecore 9.1.1. Namespace Sitecore.Xdb.Common.Web:

CertificateWebRequestHandlerModifierOptions = CertificateHttpClientHandlerModifierOptions

CertificateWebRequestHandlerModifier = CertificateHttpClientHandlerModifier

Body:
Using Sitecore 9.1.1 I am try to connect to my xconnect server with a console app using the sample code found here: https://doc.sitecore.com/developers/90/sitecore-experience-platform/en/create,-retrieve,-and-search-contact-and-interaction-data.html

I have used NuGet (Sitecore MyGet) to retrieve the libraries that are being used:

using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using Sitecore.XConnect.Schema;
using System;
using System.Threading.Tasks;
using Sitecore.XConnect.Client.WebApi;
using Sitecore.Xdb.Common.Web;
using Sitecore.XConnect.Collection.Model;
using System.Collections.Generic;
using Sitecore.Xdb.Common.Web;

However....

With in Visual Studio 2019 CertificateWebRequestHandlerModifierOptions and CertificateWebRequestHandlerModifier are red-lined with "namespace could not be found, are you missing assembly.."

I have googled and cannot find which libraries these classes live in. Can someone tell me please?


答:
You are running into a 0 vs 1 based issue.  Just change your HTML to this:</p>

```<code><table>
    <tr>
        <td class='block' id='0'></td>
        <td class='block' id='1'></td>
        <td class='block' id='2'></td>
    </tr>
    <tr>
        <td class='block' id='3'></td>
        <td class='block' id='4'></td>
        <td class='block' id='5'></td>
    </tr>
    <tr>
        <td class='block' id='6'></td>
        <td class='block' id='7'></td>
        <td class='block' id='8'></td>
    </tr>
</table>
</code>```

Title: Can someone help me debug my tic tac toe game?

Body:
I'm making a tic-tac-toe game using html, css, and javascript. I have managed to make some progress on it, but there are two bugs that I haven't been able to figure out no matter how hard I look.

The first one is that it won't take in an input on the last block (9). After I added the code for checking wins and ties it no longer worked.

The second one is that the AI starts playing on my second move, not on the first one. It must be a simple logic error, but I just don't see it.

Here's my code on repl.it:
https://repl.it/@julkothegu1/Yes

Thanks.

Body:
You are running into a 0 vs 1 based issue.  Just change your HTML to this:

<table>
    <tr>
        <td class='block' id='0'></td>
        <td class='block' id='1'></td>
        <td class='block' id='2'></td>
    </tr>
    <tr>
        <td class='block' id='3'></td>
        <td class='block' id='4'></td>
        <td class='block' id='5'></td>
    </tr>
    <tr>
        <td class='block' id='6'></td>
        <td class='block' id='7'></td>
        <td class='block' id='8'></td>
    </tr>
</table>


问:
How to implement POST and upload files in ASP C# using API?
I am trying to implement a post HTTP call through ASP C# using an API I have been given. API is not made by me but it works fine in Postman.

Here is a screenshot that worked perfectly in Postman:

and

Now, I just need to convert it to ASP C# which I spent days Googling but failed to find the answer I needed, or I am just bad in finding the right keyword. Here is what I tried, but it's a code from the company that happens to work on his page but not on mine (he's gone BTW).

```<code>public static objWebService PostSomething(string xml, Object md)
    {
        objWebService _webService = new objWebService();
        _webService.result = false;
        DataSet ds = new DataSet();

        XmlDocument xdoc = new XmlDocument(); //seems not used
        string responseString = string.Empty;

        string endpoint = "http://xxxxxxxxxxxxx"; // my post api.

        try
        {

            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            wrWebRequest.Headers["Authorization"] = "Basic xxxxxxxxxxxxx";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
            byte[] newLine = Encoding.UTF8.GetBytes("\r\n");
            byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            byte[] boundaryBytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

            wrWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            wrWebRequest.Method = "POST";
            wrWebRequest.KeepAlive = true;

            Stream requestStream = wrWebRequest.GetRequestStream();

            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"proposal.xml\"\r\nContent-Type: application/xml;\r\n\r\n{1}", "xml", req));
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Write(formItemBytes, 0, formItemBytes.Length);

            if (Utilities.IsFileExist(md.file1_path))
            {
                requestStream.Write(newLine, 0, newLine.Length);
                int bytesRead = 0;
                byte[] buffer = new byte[2048];
                byte[] formFileBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg;\r\n\r\n", "files", md.file1_name));
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                requestStream.Write(formFileBytes, 0, formFileBytes.Length);

                using (FileStream fileStream = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(md.file1_path), FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    fileStream.Close();
                }
            }

            requestStream.Write(newLine, 0, newLine.Length);
            requestStream.Write(trailer, 0, trailer.Length);
            requestStream.Close();

            HttpWebResponse wrWebResponse = wrWebRequest.GetResponse() as HttpWebResponse;

            using (Stream s = wrWebResponse.GetResponseStream())
            {
                ds.ReadXml(s);
            }

            if (ds.Tables["returnObj"] != null)
            {
                _webService.result = true;
                _webService.output = ds;
            }
            else
            {
                _webService.result = false;
            }
        }
        catch (WebException wExp)
        {
            _webService.result = false;
        }
        catch (Exception exp)
        {
            _webService.result = false;
        }
        return _webService;
    }
</code>```

This is a copy paste code I took from my ex coworker and I trim wherever I feel it's safe to trim. Forgive me if its still messy.

Whenever this portion of the code runs, I get these exceptions.

```<code>Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.ArgumentException' in System.Web.dll
</code>```

Can anyone show me how it should be done or link me to an answer if it's been asked before and solved?

答: How embarassing. The problem was the filepath was in the wrong format which is not even available in my code preview. (~/xxx/xx.jpg)</p>

Body:
I am trying to implement a post HTTP call through ASP C# using an API I have been given. API is not made by me but it works fine in Postman.

Here is a screenshot that worked perfectly in Postman:

and

Now, I just need to convert it to ASP C# which I spent days Googling but failed to find the answer I needed, or I am just bad in finding the right keyword. Here is what I tried, but it's a code from the company that happens to work on his page but not on mine (he's gone BTW).

public static objWebService PostSomething(string xml, Object md)
    {
        objWebService _webService = new objWebService();
        _webService.result = false;
        DataSet ds = new DataSet();

        XmlDocument xdoc = new XmlDocument(); //seems not used
        string responseString = string.Empty;

        string endpoint = "http://xxxxxxxxxxxxx"; // my post api.

        try
        {

            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            wrWebRequest.Headers["Authorization"] = "Basic xxxxxxxxxxxxx";

            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
            byte[] newLine = Encoding.UTF8.GetBytes("\r\n");
            byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            byte[] boundaryBytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");

            wrWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            wrWebRequest.Method = "POST";
            wrWebRequest.KeepAlive = true;

            Stream requestStream = wrWebRequest.GetRequestStream();

            byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"proposal.xml\"\r\nContent-Type: application/xml;\r\n\r\n{1}", "xml", req));
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Write(formItemBytes, 0, formItemBytes.Length);

            if (Utilities.IsFileExist(md.file1_path))
            {
                requestStream.Write(newLine, 0, newLine.Length);
                int bytesRead = 0;
                byte[] buffer = new byte[2048];
                byte[] formFileBytes = System.Text.Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg;\r\n\r\n", "files", md.file1_name));
                requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                requestStream.Write(formFileBytes, 0, formFileBytes.Length);

                using (FileStream fileStream = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(md.file1_path), FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    fileStream.Close();
                }
            }

            requestStream.Write(newLine, 0, newLine.Length);
            requestStream.Write(trailer, 0, trailer.Length);
            requestStream.Close();

            HttpWebResponse wrWebResponse = wrWebRequest.GetResponse() as HttpWebResponse;

            using (Stream s = wrWebResponse.GetResponseStream())
            {
                ds.ReadXml(s);
            }

            if (ds.Tables["returnObj"] != null)
            {
                _webService.result = true;
                _webService.output = ds;
            }
            else
            {
                _webService.result = false;
            }
        }
        catch (WebException wExp)
        {
            _webService.result = false;
        }
        catch (Exception exp)
        {
            _webService.result = false;
        }
        return _webService;
    }

This is a copy paste code I took from my ex coworker and I trim wherever I feel it's safe to trim. Forgive me if its still messy.

Whenever this portion of the code runs, I get these exceptions.

Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.Web.HttpException' in System.Web.dll
Exception thrown: 'System.ArgumentException' in System.Web.dll

Can anyone show me how it should be done or link me to an answer if it's been asked before and solved?


问:
Removing nodes from XDocument
This removes all elements from the document:

```<code>        XDocument document = XDocument.Load(inputFile);
        foreach (XElement element in document.Elements())
        {
            element.Remove();
        }
        document.Save(outputFile);
</code>```

This doesn't have any effect:

```<code>        XDocument document = XDocument.Load(inputFile);
        foreach (XElement element in document.Elements())
        {
            //element.Remove();
            foreach (XElement child in element.Elements())
                child.Remove();
        }
        document.Save(outputFile);
</code>```

Am I missing something here? Since these are all references to elements within the XDocument, shouldn't the changes take effect? Is there some other way I should be removing nested children from an XDocument?

Thanks!

答:
When using XDocument try this instead:

```<code>XDocument document = XDocument.Load(inputFile);
foreach (XElement element in document.Elements())
{
     document.Element("Root").SetElementValue(element , null);
}
document.Save(outputFile)
</code>```

Regards,
Todd

ContentLicense: CC BY-SA 2.5

Title: Removing nodes from XDocument

Body:
This removes all elements from the document:

        XDocument document = XDocument.Load(inputFile);
        foreach (XElement element in document.Elements())
        {
            element.Remove();
        }
        document.Save(outputFile);

This doesn't have any effect:

        XDocument document = XDocument.Load(inputFile);
        foreach (XElement element in document.Elements())
        {
            //element.Remove();
            foreach (XElement child in element.Elements())
                child.Remove();
        }
        document.Save(outputFile);

Am I missing something here? Since these are all references to elements within the XDocument, shouldn't the changes take effect? Is there some other way I should be removing nested children from an XDocument?

Thanks!

Body:
When using XDocument try this instead:

XDocument document = XDocument.Load(inputFile);
foreach (XElement element in document.Elements())
{
     document.Element("Root").SetElementValue(element , null);
}
document.Save(outputFile)

Regards,
Todd


问:
What is difference between hint in TextInputLayout vs hint in TextInputEditText
I found crash in crashlog of "NullPointerException: Attempt to invoke virtual method 'void android.view.View.getBoundsOnScreen(android.graphics.Rect)' on a null object reference" and I verified some stackoverflow suggestions for this crash. I found below link suggest to use hint in TextInputLayout instead of TextInputEditText, so I want to know what makes it different?

Below link suggests to use hint in TextInputLayout:
SO
Google shows to use hint in TextInputEditText:
Google_Recommendation

I tried hint in both place of TextInputLayout and TextInputEditText. Hint worked well in both place similarly.

I would like to know what is the difference between both method and which one is more appropriate to use.

答:
In design support library TextInputLayout was introduced to display the floating label on EditText or TextInputEditText . The EditText or TextInputEditText  has to be wrapped by TextInputLayout in order to display the floating label.

Rule of Thumb : TextInputLayout should wrap TextInputEditText

where should you place hint

according to the official documentation

The hint should be set on the TextInputLayout, rather than the EditText. If a hint is specified on the child EditText in XML, the TextInputLayout might still work correctly; TextInputLayout will use the EditText's hint as its floating label. However, future calls to modify the hint will not update TextInputLayout's hint. To avoid unintended behavior, call setHint(CharSequence) and getHint() on TextInputLayout, instead of on EditText.

Note that TextInputEditText is special sub-class of EditText designed for use as a child of TextInputLayout.

hope it's helpful


问:
Python Change Return Program: Error in counting change
The problem is when counting the pennies, the pennies are sometime short 1 penny and change is equal to .01 at the end when it should be 0 once pennies are accounted for.

```<code>import os
clear = lambda: os.system('cls')

def dollar_counter(num):

    if num // 1 >= 1:
        dollars = num // 1
    else:
        pass
    return dollars

def quarter_counter(num):

    quarters = 0
    if num // .25 >= 1:
        quarters = num // .25
    else:
        pass
    return quarters

def dime_counter(num):

    dimes = 0
    if num // .10 >= 1:
        dimes = num // .10
    else:
        pass
    return dimes

def nickel_counter(num):

    nickels = 0
    if num // .05 >= 1:
        nickels = num // .05
    else:
        pass
    return nickels

def penny_counter(num):

    pennies = 0
    if num // .01 >= 1:
        pennies = num // .01
    else:
       pass
    return pennies

#Run Program
while True:

    try:
        #get info from user
        payment = float(input("Enter what the customer paid: "))
        cost = float(input("Enter the cost: "))

        #round change to 2 decimals and output change due
        change = round(payment - cost,2)
        print("Change due: {}".format(change))

        #count dollars
        print(int(dollar_counter(change)), "dollars")
        change = change - float(dollar_counter(change))
        print(round(change,2)) #print the change each time for troubleshooting problems

        #count quarters
        print(int(quarter_counter(change)), "quarters")
        change = change - float(quarter_counter(change)*.25)
        print(round(change,2))

        #count dimes
        print(int(dime_counter(change)), "dimes")
        change = change - float(dime_counter(change)*.1)
        print(round(change,2))

        #count nickels
        print(int(nickel_counter(change)), "nickels")
        change = change - float(nickel_counter(change)*.05)
        print(round(change,2))

        #count pennies
        print(int(penny_counter(change)), "pennies")
        change = change - float(penny_counter(change)*.01)
        print(round(change,2))

    except UnboundLocalError:
        print("Cost can be higher than amount paid. Try again.\n")
        continue
    else:
        replay = input("Are you done? Enter 'Yes' to continue or 'No' to quit: ")
        if replay[0].lower() == 'y':
            clear()
            continue
        else:
            break
</code>```

I expect the change, after counting pennies, to be 0 but in most cases it ends with change == .01. Why is penny_counter() not accounting for the leftover change

答: In the function dollar_counter, you need to initialize dollars=0. As for the issue you're running into, I suggest printing out the variable num in penny_counter. You will see that it is not exactly 0.01, so after the division it will get rounded to 0. To fix this, I suggest either rounding the result before you pass it to the function, or convert the units to pennies for everything(so you can avoid floats entirely).</p>

Body:
The problem is when counting the pennies, the pennies are sometime short 1 penny and change is equal to .01 at the end when it should be 0 once pennies are accounted for.

import os
clear = lambda: os.system('cls')

def dollar_counter(num):

    if num // 1 >= 1:
        dollars = num // 1
    else:
        pass
    return dollars

def quarter_counter(num):

    quarters = 0
    if num // .25 >= 1:
        quarters = num // .25
    else:
        pass
    return quarters

def dime_counter(num):

    dimes = 0
    if num // .10 >= 1:
        dimes = num // .10
    else:
        pass
    return dimes

def nickel_counter(num):

    nickels = 0
    if num // .05 >= 1:
        nickels = num // .05
    else:
        pass
    return nickels

def penny_counter(num):

    pennies = 0
    if num // .01 >= 1:
        pennies = num // .01
    else:
       pass
    return pennies

#Run Program
while True:

    try:
        #get info from user
        payment = float(input("Enter what the customer paid: "))
        cost = float(input("Enter the cost: "))

        #round change to 2 decimals and output change due
        change = round(payment - cost,2)
        print("Change due: {}".format(change))

        #count dollars
        print(int(dollar_counter(change)), "dollars")
        change = change - float(dollar_counter(change))
        print(round(change,2)) #print the change each time for troubleshooting problems

        #count quarters
        print(int(quarter_counter(change)), "quarters")
        change = change - float(quarter_counter(change)*.25)
        print(round(change,2))

        #count dimes
        print(int(dime_counter(change)), "dimes")
        change = change - float(dime_counter(change)*.1)
        print(round(change,2))

        #count nickels
        print(int(nickel_counter(change)), "nickels")
        change = change - float(nickel_counter(change)*.05)
        print(round(change,2))

        #count pennies
        print(int(penny_counter(change)), "pennies")
        change = change - float(penny_counter(change)*.01)
        print(round(change,2))

    except UnboundLocalError:
        print("Cost can be higher than amount paid. Try again.\n")
        continue
    else:
        replay = input("Are you done? Enter 'Yes' to continue or 'No' to quit: ")
        if replay[0].lower() == 'y':
            clear()
            continue
        else:
            break

I expect the change, after counting pennies, to be 0 but in most cases it ends with change == .01. Why is penny_counter() not accounting for the leftover change


问:
in onPurchasesUpdated, how to get accountid which was setted in BillingFlowParams
I am using com.android.billingclient:billing:1.1 for android's in app billing. I start pay in below code:

```<code>BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                            .setSku(productId)
                            .setType(BillingClient.SkuType.INAPP)
                            .setAccountId(accountId)
                            .build();
billingClient.launchBillingFlow(this, flowParams);
</code>```

It will callback on:

```<code>void onPurchasesUpdated(@BillingResponse int responseCode, @Nullable List<Purchase> purchases);
</code>```

The question is how to get account which was seated in BillingFlowParams?

答:
First we have to override the onPurchasesUpdated() to handle response codes.

```<code>@Override
void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
    if (billingResult.getResponseCode() == BillingResponse.OK
            && purchases != null) {
        for (Purchase purchase : purchases) {
            handlePurchase(purchase);
        }
    } else if (billingResult.getResponseCode() == BillingResponse.USER_CANCELED) {
        // Handle an error caused by a user cancelling the purchase flow.
    } else {
        // Handle any other error codes.
    }
}
</code>```

Then we have to get the purchase token to acknowledge any transactions that was correctly held to get the accounts that is needed only if the billingResult.getResponseCode() is and BillingResponse.OK.

```<code>BillingClient client = ...
AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = ...

void handlePurchase(Purchase purchase) {
    if (purchase.getState() == PurchaseState.PURCHASED) {
        // Grant entitlement to the user.
        ...

        // Acknowledge the purchase if it hasn't already been acknowledged.
        if (!purchase.isAcknowledged()) {
            AcknowledgePurchaseParams acknowledgePurchaseParams =
                AcknowledgePurchaseParams.newBuilder()
                    .setPurchaseToken(purchase.getPurchaseToken())
                    .build();
            client.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
        }
    }
}
</code>```

Then only one thing remains:

```<code>void handlePurchase(Purchase purchase) {
    if (purchase.getState() == PurchaseState.PURCHASED) {
        // Acknowledge purchase and grant the item to the user
    } else if (purchase.getState() == PurchaseState.PENDING) {
        // Here you can confirm to the user that they've started the pending
    }
}
</code>```

Here the class Purchase has numerous public methods like getOrderId() and getOriginalJson() to get the details of the account which was seated on billing.
More details.

Body:
I am using com.android.billingclient:billing:1.1 for android's in app billing. I start pay in below code:

BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                            .setSku(productId)
                            .setType(BillingClient.SkuType.INAPP)
                            .setAccountId(accountId)
                            .build();
billingClient.launchBillingFlow(this, flowParams);

It will callback on:

void onPurchasesUpdated(@BillingResponse int responseCode, @Nullable List<Purchase> purchases);

The question is how to get account which was seated in BillingFlowParams?

Body:
First we have to override the onPurchasesUpdated() to handle response codes.

@Override
void onPurchasesUpdated(BillingResult billingResult, List<Purchase> purchases) {
    if (billingResult.getResponseCode() == BillingResponse.OK
            && purchases != null) {
        for (Purchase purchase : purchases) {
            handlePurchase(purchase);
        }
    } else if (billingResult.getResponseCode() == BillingResponse.USER_CANCELED) {
        // Handle an error caused by a user cancelling the purchase flow.
    } else {
        // Handle any other error codes.
    }
}

Then we have to get the purchase token to acknowledge any transactions that was correctly held to get the accounts that is needed only if the billingResult.getResponseCode() is and BillingResponse.OK.

BillingClient client = ...
AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = ...

void handlePurchase(Purchase purchase) {
    if (purchase.getState() == PurchaseState.PURCHASED) {
        // Grant entitlement to the user.
        ...

        // Acknowledge the purchase if it hasn't already been acknowledged.
        if (!purchase.isAcknowledged()) {
            AcknowledgePurchaseParams acknowledgePurchaseParams =
                AcknowledgePurchaseParams.newBuilder()
                    .setPurchaseToken(purchase.getPurchaseToken())
                    .build();
            client.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
        }
    }
}

Then only one thing remains:

void handlePurchase(Purchase purchase) {
    if (purchase.getState() == PurchaseState.PURCHASED) {
        // Acknowledge purchase and grant the item to the user
    } else if (purchase.getState() == PurchaseState.PENDING) {
        // Here you can confirm to the user that they've started the pending
    }
}

Here the class Purchase has numerous public methods like getOrderId() and getOriginalJson() to get the details of the account which was seated on billing.
More details.


问:
How to do a Xamarin.iOS Folding Cell
I have found swift code and a plugin to do the a Folding Cell. However, is there any code or plugin to do this in Xamarin.iOS. This is what i found https://github.com/0ber/Folding-cell-programmatically. There is a plugin available for Android Xam.Plugins.Android.FoldingCell but i can't find anything for Xamarin.iOS. Would really appreciate some help on this.</p>

答:
i am not familiar with Xamarin, but you can try using sharpie to convert the ios code to Xamarin bindings

You can refer to this post:
Using Swift library in Xamarin

Title: How to do a Xamarin.iOS Folding Cell


问:
Getting a null object exception when using an interface
I have created a shopping cart via recyclerview. Each viewholder also has a + and - button to add or remove quantity. This functionality is done in the adapter and I have to notify the parent fragment of the updated total amount. This last bit is done via an interface. The problem is, I am getting the following error:

```<code>Process: com.ecomm.market, PID: 6630
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.ecomm.market.SelectionAdapter$OnUpdateCartListener.onUpdateCart(int)' on a null object reference
        at com.ecomm.market.SelectionAdapter$ViewHolder$1.onClick(SelectionAdapter.java:103)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

The selected item and corresponding quantity are stored in a hashmap that I convert to an array to populate the recycler view cart. This is what the relevant part of my main fragment MenuFragment looks like:

```<code>
                // Using the adapter interface to add items to cart and adding up total amount
                menuItemAdapter.setOnAddToCartListener(new MenuItemAdapter.OnAddToCartListener() {
                    @Override
                    public void onAddToCart(final HashMap selectionItemsHashMap) {

                        setupSelectionRecycler(menuView);
                        totalAmount = mapToArray(selectionItemsHashMap);

                            selectionAdapter = new SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

                        selectionRecycler.setAdapter(selectionAdapter);
                        cartItemsHashmap = selectionItemsHashMap;

                        selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                            @Override
                            public void onUpdateCart(int updatedTotalAmount) {

                                String stringTotalAmount = Integer.toString(updatedTotalAmount);
                                Log.d(TAG, "received total:" +stringTotalAmount);
                                tvTotalAmount.setText("$"+ stringTotalAmount);
                                totalAmount = updatedTotalAmount;
                            }
                        });
                    }
                });
            }
</code>```

And here is an excerpt from my adapter SelectionAdapter:

```<code>public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.ViewHolder> {

    private static final String TAG = SelectionAdapter.class.getSimpleName();

    private ArrayList<SelectionItem> selectionItemArrayList = new ArrayList<>();
    public HashMap<String, Integer> selectionItemsHashMap = new HashMap<String, Integer>();
    public int totalAmount;

    private OnUpdateCartListener updateCartListener;

    public interface OnUpdateCartListener {
        void onUpdateCart(int totalAmount);
    }

    public void setUpdateCartListener(OnUpdateCartListener updateCartListener) {
        this.updateCartListener = updateCartListener;
    }

    public SelectionAdapter(ArrayList<SelectionItem> selectionItemArrayList, HashMap<String, Integer> selectionItemsHashMap, int currentTotalAmount) {
        this.selectionItemArrayList = selectionItemArrayList;
        this.selectionItemsHashMap = selectionItemsHashMap;
        this.totalAmount = currentTotalAmount;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.selection_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
        String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
        viewHolder.tvDishQuantity.setText(quantity);
    }

    @Override
    public int getItemCount() {
        return selectionItemArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvSelectItem, tvDishQuantity;
        ImageView addQuantity, subtractQuantity, deleteItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvSelectItem = itemView.findViewById(R.id.dish_selection);
            tvDishQuantity = itemView.findViewById(R.id.dish_quantity);

            addQuantity = itemView.findViewById(R.id.button_add);
            subtractQuantity = itemView.findViewById(R.id.button_subtract);
            deleteItem = itemView.findViewById(R.id.delete_item);

            addQuantity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Find the name of the menu item
                    int position = getAdapterPosition();
                    String itemName = selectionItemArrayList.get(position).getSelectionName();

                    // Increase quantity
                    int currentQuantity = selectionItemsHashMap.get(itemName);

                    currentQuantity += 1;
                    // Update the hashmap with the new quantity
                    selectionItemsHashMap.put(itemName,currentQuantity);

                    //Update total amount
                    for (Object name: selectionItemsHashMap.keySet()) {
                        String key = (String) name;
                        if (key.equals(selectionItemArrayList.get(position).getSelectionName())) {
                            int eachPrice = Integer.parseInt(selectionItemArrayList.get(position).getSelectionPrice());
                            totalAmount += eachPrice;
                        }
                    }
                    // Display the new quantity
                    String stringCurrentQuantity = Integer.toString(currentQuantity);
                    tvDishQuantity.setText(stringCurrentQuantity);
                    //updateCartListener.onUpdateCart(totalAmount);
                }
            });
}
</code>```

EDIT
A couple of points:
- When the cart is initially filled, I use this same code and it works fine.
- The problem occurs once the user returns to the cart and I have to repopulate it from a bundle. Everything works fine, except when the user goes straight to the cart and attempts to alter the quantity from there.

答:
So you try to access the listener inside the ViewHolder which is probably the cause of the crash, what the standard way is setting the OnClickListener inside your adapter

```<code>@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
    String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
    viewHolder.tvDishQuantity.setText(quantity);
    viewHolder.addQuantity.setOnClickListener(new View.OnClickListener() {
    ...
    }
}
</code>```

Body:
I have created a shopping cart via recyclerview. Each viewholder also has a + and - button to add or remove quantity. This functionality is done in the adapter and I have to notify the parent fragment of the updated total amount. This last bit is done via an interface. The problem is, I am getting the following error:

Process: com.ecomm.market, PID: 6630
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.ecomm.market.SelectionAdapter$OnUpdateCartListener.onUpdateCart(int)' on a null object reference
        at com.ecomm.market.SelectionAdapter$ViewHolder$1.onClick(SelectionAdapter.java:103)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

The selected item and corresponding quantity are stored in a hashmap that I convert to an array to populate the recycler view cart. This is what the relevant part of my main fragment MenuFragment looks like:

                // Using the adapter interface to add items to cart and adding up total amount
                menuItemAdapter.setOnAddToCartListener(new MenuItemAdapter.OnAddToCartListener() {
                    @Override
                    public void onAddToCart(final HashMap selectionItemsHashMap) {

                        setupSelectionRecycler(menuView);
                        totalAmount = mapToArray(selectionItemsHashMap);

                            selectionAdapter = new SelectionAdapter(selectionItemArrayList, selectionItemsHashMap, totalAmount);

                        selectionRecycler.setAdapter(selectionAdapter);
                        cartItemsHashmap = selectionItemsHashMap;

                        selectionAdapter.setUpdateCartListener(new SelectionAdapter.OnUpdateCartListener() {
                            @Override
                            public void onUpdateCart(int updatedTotalAmount) {

                                String stringTotalAmount = Integer.toString(updatedTotalAmount);
                                Log.d(TAG, "received total:" +stringTotalAmount);
                                tvTotalAmount.setText("$"+ stringTotalAmount);
                                totalAmount = updatedTotalAmount;
                            }
                        });
                    }
                });
            }

And here is an excerpt from my adapter SelectionAdapter:

public class SelectionAdapter extends RecyclerView.Adapter<SelectionAdapter.ViewHolder> {

    private static final String TAG = SelectionAdapter.class.getSimpleName();

    private ArrayList<SelectionItem> selectionItemArrayList = new ArrayList<>();
    public HashMap<String, Integer> selectionItemsHashMap = new HashMap<String, Integer>();
    public int totalAmount;

    private OnUpdateCartListener updateCartListener;

    public interface OnUpdateCartListener {
        void onUpdateCart(int totalAmount);
    }

    public void setUpdateCartListener(OnUpdateCartListener updateCartListener) {
        this.updateCartListener = updateCartListener;
    }

    public SelectionAdapter(ArrayList<SelectionItem> selectionItemArrayList, HashMap<String, Integer> selectionItemsHashMap, int currentTotalAmount) {
        this.selectionItemArrayList = selectionItemArrayList;
        this.selectionItemsHashMap = selectionItemsHashMap;
        this.totalAmount = currentTotalAmount;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.selection_card, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
        String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
        viewHolder.tvDishQuantity.setText(quantity);
    }

    @Override
    public int getItemCount() {
        return selectionItemArrayList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvSelectItem, tvDishQuantity;
        ImageView addQuantity, subtractQuantity, deleteItem;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tvSelectItem = itemView.findViewById(R.id.dish_selection);
            tvDishQuantity = itemView.findViewById(R.id.dish_quantity);

            addQuantity = itemView.findViewById(R.id.button_add);
            subtractQuantity = itemView.findViewById(R.id.button_subtract);
            deleteItem = itemView.findViewById(R.id.delete_item);

            addQuantity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Find the name of the menu item
                    int position = getAdapterPosition();
                    String itemName = selectionItemArrayList.get(position).getSelectionName();

                    // Increase quantity
                    int currentQuantity = selectionItemsHashMap.get(itemName);

                    currentQuantity += 1;
                    // Update the hashmap with the new quantity
                    selectionItemsHashMap.put(itemName,currentQuantity);

                    //Update total amount
                    for (Object name: selectionItemsHashMap.keySet()) {
                        String key = (String) name;
                        if (key.equals(selectionItemArrayList.get(position).getSelectionName())) {
                            int eachPrice = Integer.parseInt(selectionItemArrayList.get(position).getSelectionPrice());
                            totalAmount += eachPrice;
                        }
                    }
                    // Display the new quantity
                    String stringCurrentQuantity = Integer.toString(currentQuantity);
                    tvDishQuantity.setText(stringCurrentQuantity);
                    //updateCartListener.onUpdateCart(totalAmount);
                }
            });
}

EDIT
A couple of points:
- When the cart is initially filled, I use this same code and it works fine.
- The problem occurs once the user returns to the cart and I have to repopulate it from a bundle. Everything works fine, except when the user goes straight to the cart and attempts to alter the quantity from there.

Body:
So you try to access the listener inside the ViewHolder which is probably the cause of the crash, what the standard way is setting the OnClickListener inside your adapter

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
    viewHolder.tvSelectItem.setText(selectionItemArrayList.get(position).getSelectionName());
    String quantity = Integer.toString(selectionItemArrayList.get(position).getSelectionQuantity());
    viewHolder.tvDishQuantity.setText(quantity);
    viewHolder.addQuantity.setOnClickListener(new View.OnClickListener() {
    ...
    }
}


问:
using type in place of cat
I'm currently working through Wes McKinney's Python for Data Analysis book. I ran into a problem on one of his examples on chapter 6.

His entry into Jupyter:

```<code>!cat examples/cs1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
</code>```

There is a short box afterwards that says if you're using Windows, to use the type command in place of cat.
I entered the following:

```<code>!type examples/ex1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo
</code>```

But got an error:

```<code>NameError: name 'a' is not defined
</code>```

How do I use the type command in place of cat for this instance? Running Python 3.6.5 on Windows 10.

答:
!type+path is used for read the existed data instead of writing the data into the file.

the following content is what you read from the CSV file, you should not type this.

a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo

you can download those csv files from GitHub

Title: using type in place of cat

Body:
I'm currently working through Wes McKinney's Python for Data Analysis book. I ran into a problem on one of his examples on chapter 6.

His entry into Jupyter:

!cat examples/cs1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo

There is a short box afterwards that says if you're using Windows, to use the type command in place of cat.
I entered the following:

!type examples/ex1.csv
a,b,c,d,message
1,2,3,4,hello
5,6,7,8,world
9,10,11,12,foo

But got an error:

NameError: name 'a' is not defined

How do I use the type command in place of cat for this instance? Running Python 3.6.5 on Windows 10.


问:
Problem running PHP temperature converter
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!</p>

```<code><?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

<html>

<head>
    <title>Temperature converter</title>
</head>

<body>
    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    <label>Temperature <input type="text" name="temperature"></label>
    <label>Celcius <input type="radio" name="scale" value="cel"></label>
    <label>Fahrenheit <input type="radio" name="scale" value="fah"></label>
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>
</body>

</html>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>
</code>```

答:
You have mismatched conditionals.

You're getting a blank screen because parsing your script fails and you have error reporting turned off.

Body:
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!

<?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

    <title>Temperature converter</title>

    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    Temperature <input type="text" name="temperature">
    Celcius <input type="radio" name="scale" value="cel">
    Fahrenheit <input type="radio" name="scale" value="fah">
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>


问:
Modal is closed when cursor is released outside the modal after Chrome update (angularjs and bootstrap-ui)
Sometimes when I want to quickly select the entire text of an input (within a modal), I begin selecting from the end of the text and move the mouse to the left until the entire text is selected and then I release.

Sometimes this release will occur outside the modal because the mouse movement is fast.

Picture describing the movement:

The problem is that the modal is closed when I release outside.

Question: how can I prevent the modal from closing when releasing outside?

I'm okay with the modal being closed with a click outside. But not okay with the release event.

I'm using:

angularjs 1.5.8

angular-bootstrap 2.5.0 (aka bootstrap-ui)

bootstrap 3.3.7 (only css!!! not js, because js is provided by the above)

Update:
I've created a plunkr and a GIF:
https://plnkr.co/edit/mxDLAdnrQ4p0KKyw?p=info

```<code><div class="modal-body">
  <div class="form-group">
    <label for="">Foo</label>
    <input type="text" class="form-control input-sm" ng-model="foo">

    <p>Do this: select the text from right to left and release the mouse outside the modal.</p>
  </div>
</div>
</code>```

GIF:

Update 2

I have new information! This started happening after the last Goole Chrome update! I tried with another computer that had the previous version of Chrome and the modal doesn't close.

答:
Yes, this started happening again after the last Goole Chrome update Version 74.0.3729.169, is this a bug with Chrome we can't fix and that we'll just have to wait for a Chrome update for it to be resolved?

or a bootstrap maintainer will update the code for fixing this?

Issue url: https://github.com/twbs/bootstrap/issues/28844

Body:
Sometimes when I want to quickly select the entire text of an input (within a modal), I begin selecting from the end of the text and move the mouse to the left until the entire text is selected and then I release.

Sometimes this release will occur outside the modal because the mouse movement is fast.

Picture describing the movement:

The problem is that the modal is closed when I release outside.

Question: how can I prevent the modal from closing when releasing outside?

I'm okay with the modal being closed with a click outside. But not okay with the release event.

I'm using:

angularjs 1.5.8

angular-bootstrap 2.5.0 (aka bootstrap-ui)

bootstrap 3.3.7 (only css!!! not js, because js is provided by the above)

Update:
I've created a plunkr and a GIF:
https://plnkr.co/edit/mxDLAdnrQ4p0KKyw?p=info

    Foo
    <input type="text" class="form-control input-sm" ng-model="foo">

Do this: select the text from right to left and release the mouse outside the modal.

GIF:

Update 2

I have new information! This started happening after the last Goole Chrome update! I tried with another computer that had the previous version of Chrome and the modal doesn't close.