问:
Vector invalid subscript. SFML
I'm trying to make a snake game and maybe this error is one of possible. So when I'm debugging and stepping over then I getting link to exception in header file of vector and in exception code wrote that vector has invalid subscript. (Error cause can called by vector bodyPart). The compiler message:

Unhandled exception at 0x00007FFA227EA799 in snake.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00000052FA7CDFD0.

```<code>Snake::Snake(RenderWindow& window)
{
    bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    bodyPart.setSize(Vector2f(20.f, 20.f));
    bodyPart.setFillColor(Color(0, 0, 0));
    body.push_back(bodyPart);
}
//Sets default parameters
void Game::restart(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        snake.body.pop_back();
    }
    snake.bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    snake.body.push_back(snake.bodyPart);
}
//Updates game
void Game::tick(RenderWindow& window)
{
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        fruit.fruitX = fieldLCorn + rand() % fieldX * fieldY;
        fruit.fruitY = fieldLCorn + rand() % fieldY * fieldX;
        ui.score++;
        snake.body.reserve(1);
        snake.body.push_back(snake.bodyPart);
    }
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision(RenderWindow& window)
{
    //Is snake met border
    if (snake.body.at(0).getPosition().x > 300) restart(window);
    if (snake.body.at(0).getPosition().y > 300) restart(window);
    if (snake.body.at(0).getPosition().x < -300) restart(window);
    if (snake.body.at(0).getPosition().y < -300) restart(window);
    //If snake eats itself
    for (int k = 0; k < snake.body.size() - 1; k++)
    {
        if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
        {
            restart(window);
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        window.draw(snake.body.at(i));
    }
}
</code>```

答: In your Game::render() function the condition of the loop will obviously give an 'out-of-bound' error because in for (int i = 0; i < snake.body.size() - 1; i++) it will try to access 1-past the last element. So you should either check for <= or remove the -1 (advised).

Title: Vector invalid subscript. SFML

Body:
I'm trying to make a snake game and maybe this error is one of possible. So when I'm debugging and stepping over then I getting link to exception in header file of vector and in exception code wrote that vector has invalid subscript. (Error cause can called by vector bodyPart). The compiler message:

Unhandled exception at 0x00007FFA227EA799 in snake.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00000052FA7CDFD0.

Snake::Snake(RenderWindow& window)
{
    bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    bodyPart.setSize(Vector2f(20.f, 20.f));
    bodyPart.setFillColor(Color(0, 0, 0));
    body.push_back(bodyPart);
}
//Sets default parameters
void Game::restart(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        snake.body.pop_back();
    }
    snake.bodyPart.setPosition(window.getSize().x / 4, window.getSize().y / 4);
    snake.body.push_back(snake.bodyPart);
}
//Updates game
void Game::tick(RenderWindow& window)
{
    if (snake.body.at(0).getPosition().x == fruit.fruitX && snake.body.at(0).getPosition().y == fruit.fruitY)
    {
        fruit.fruitX = fieldLCorn + rand() % fieldX * fieldY;
        fruit.fruitY = fieldLCorn + rand() % fieldY * fieldX;
        ui.score++;
        snake.body.reserve(1);
        snake.body.push_back(snake.bodyPart);
    }
}
void Game::moveSnake()
{
    switch(dir)
    {
    case 1:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y + 10);
        snake.body.pop_back();
    case 2:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(0, snake.body.at(0).getPosition().y - 10);
        snake.body.pop_back();
    case 3:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x + 10, 0);
        snake.body.pop_back();
    case 4:
        snake.body.push_back(snake.tail);
        snake.body.at(0).move(snake.body.at(0).getPosition().x - 10, 0);
        snake.body.pop_back();
    }
}
void Game::countCollision(RenderWindow& window)
{
    //Is snake met border
    if (snake.body.at(0).getPosition().x > 300) restart(window);
    if (snake.body.at(0).getPosition().y > 300) restart(window);
    if (snake.body.at(0).getPosition().x < -300) restart(window);
    if (snake.body.at(0).getPosition().y < -300) restart(window);
    //If snake eats itself
    for (int k = 0; k < snake.body.size() - 1; k++)
    {
        if (snake.body.at(0).getPosition().x == snake.body.at(k).getPosition().y && snake.body.at(0).getPosition().y == snake.body.at(k).getPosition().y)
        {
            restart(window);
        }
    }
}
void Game::render(RenderWindow& window)
{
    for (int i = 0; i < snake.body.size() - 1; i++)
    {
        window.draw(snake.body.at(i));
    }
}


来源: stackexchange

问:
How to decrement items in array Incrementally based on the given quantity in Javascript
I have this sample array of objects

```<code>   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

```<code>   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

```<code>   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]
</code>```

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

```<code>var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})
</code>```

答:
```<code>var getMangoes = function(requested){
  var remaining = requested;
  var supplied = 0;
  for(var i = 0; i < mangoes.length() && supplied < requested; i++){
    if(mangoes[i].quantity >= remaining){
      mangoes[i].quantity -= remaining;
      supplied += remaining;
    }
    else {
      remaining -= mangoes[i].quantity;
      supplied += mangoes[i].quantity;
    }
  }
  return(supplied);
};

var mangoesIWant = 13;
var mangoesIGot = getMangoes(mangoesIWant);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this sample array of objects

   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})


问:
Border-radius are not centered aligned,when changing screen size
I've fixed everything into the laptop screen size and everything is centred aligned until I begin to switch over to tablet/mobile screen using dev toolbars the top border-radius is shifted towards the left and the bottom 3 circles are not following properly. I heard that px is not suitable to be used instead you should use rem/em in order to be responsive to any screen size, is that true?

.container1 {
    max-width: 1000px;
    margin: 0 auto;
    padding:0 auto;
}
.circle1 p {
    position: absolute;
    transform: translate(60px, 80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    margin: 0;
    position: absolute;
    transform: translate(20px,80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    margin: 0;
    position: absolute;
    transform: translate(50px, 80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    margin:100px 50px 80px 350px;
    border-radius: 100%;
    height: 300px;
    background: white;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
}

.navigation li {
    padding:10px 80px 0px 68px;
    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    transform: translate(150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    transform: translate(-150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;

}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    transform: translate(40px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(50px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

     <body style="height: 130vh;">

        <!-- navigation bar -->
        <div class="container1">
            <nav class="navigation">
                <ul>
                    <br></br>
                    <li style="font-size:80px">Circle</li>
                    <li>in</li>
                </ul>
            </nav>
        </div>

        <div class="border-circle">
            <div class="circle1">
                 <li><span class="fa fa-gamepad fa-9x"></span></li>
                <p> Circle1</p>
            </div>

            <div class="circle2">
                 <li><span class= " fa fa-thumbs-up fa-10x"></span></li>
                <p> Circle2 </p>
            </div>

            <div class="circle3">
                <li><span class="fa fa-gift fa-8x"></span></li>
                <p> Circle3 </p>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

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

答:
You can use flex layout:

.container1 {
    max-width: 1000px;
    margin: 0 auto;
    padding:0 auto;
}
.circle1 p {

    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    margin: 0;

    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    margin: 0;

    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    margin:100px 50px 80px 350px;
    border-radius: 100%;
    height: 300px;
    background: white;
    display: flex;
    justify-content: center;
    align-items: center;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
}

.navigation li {

    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    transform: translate(150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    transform: translate(-150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;

}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    transform: translate(40px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(50px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

.circle {
  display: flex;
  justify-content: center;
  align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

     <body style="height: 130vh;">

        <!-- navigation bar -->
        <div class="container1">
            <nav class="navigation">
                <ul>
                    <br></br>
                    <li style="font-size:80px">Circle</li>
                    <li>in</li>
                </ul>
            </nav>
        </div>

        <div class="border-circle">
            <div class="circle1 circle">
                 <li><span class="fa fa-gamepad fa-9x"></span></li>
                <p> Circle1</p>
            </div>

            <div class="circle2 circle">
                 <li><span class= " fa fa-thumbs-up fa-10x"></span></li>
                <p> Circle2 </p>
            </div>

            <div class="circle3 circle">
                <li><span class="fa fa-gift fa-8x"></span></li>
                <p> Circle3 </p>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

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

Body:
I've fixed everything into the laptop screen size and everything is centred aligned until I begin to switch over to tablet/mobile screen using dev toolbars the top border-radius is shifted towards the left and the bottom 3 circles are not following properly. I heard that px is not suitable to be used instead you should use rem/em in order to be responsive to any screen size, is that true?

.container1 {
    max-width: 1000px;
    margin: 0 auto;
    padding:0 auto;
}
.circle1 p {
    position: absolute;
    transform: translate(60px, 80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    margin: 0;
    position: absolute;
    transform: translate(20px,80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    margin: 0;
    position: absolute;
    transform: translate(50px, 80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    margin:100px 50px 80px 350px;
    border-radius: 100%;
    height: 300px;
    background: white;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
}

.navigation li {
    padding:10px 80px 0px 68px;
    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    transform: translate(150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    transform: translate(-150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;

}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    transform: translate(40px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(50px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

<!DOCTYPE html>

    <jsp:include page="../head.html" />

Circle

in

 Circle1

 Circle2

 Circle3

Body:
You can use flex layout:

.container1 {
    max-width: 1000px;
    margin: 0 auto;
    padding:0 auto;
}
.circle1 p {

    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    margin: 0;

    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    margin: 0;

    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    margin:100px 50px 80px 350px;
    border-radius: 100%;
    height: 300px;
    background: white;
    display: flex;
    justify-content: center;
    align-items: center;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
}

.navigation li {

    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    transform: translate(150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    transform: translate(-150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;

}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    transform: translate(40px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(50px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

.circle {
  display: flex;
  justify-content: center;
  align-items: center;
}

<!DOCTYPE html>
<html>
    <jsp:include page="../head.html" />

     <body style="height: 130vh;">

        <!-- navigation bar -->
        <div class="container1">
            <nav class="navigation">
                <ul>
                    <br></br>
                    <li style="font-size:80px">Circle</li>
                    <li>in</li>
                </ul>
            </nav>
        </div>

        <div class="border-circle">
            <div class="circle1 circle">
                <a href="#"> <li><span class="fa fa-gamepad fa-9x"></span></li> </a>
                <p> Circle1</p>
            </div>

            <div class="circle2 circle">
                <a href="#"> <li><span class= " fa fa-thumbs-up fa-10x"></span></li></a>
                <p> Circle2 </p>
            </div>

            <div class="circle3 circle">
                <a href="#"><li><span class="fa fa-gift fa-8x"></span></li></a>
                <p> Circle3 </p>
            </div>

        </div>

        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    </body>
</html>


问:
Uncaught TypeError: Cannot read property 'style' of undefined at HTMLTableCellElement
I'm trying to do an exercise related to a chess game. I only must represent the chessboard with static X or Y as I have just done. However, I want to add an onClick for each box. The click must display me if I have clicked a black or white box and if it is free or busy. I get an exception when my onClick function is executed and I don't understand why. My solution is:

```<code>
<script>
      let scacchiera = [];

      function createTable() {
        var table = document.createElement("table");
        for (var i = 0; i < 8; i++) {
          var row = document.createElement("tr");
          for (var j = 0; j < 8; j++) {
            var column = document.createElement("td");
            if ((j % 2 === 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
              column.style.backgroundColor = "black";
              if (i < 3) {
                column.textContent = "X";
              }
              if (i > 4) {
                column.textContent = "O";
              }
            }
            column.addEventListener("click", function (column) {
              if (column.style.backgroundColor === "black") {
                if(column.textContent ==="X"){
                    alert("black box and X");
                }else{
                    alert("black box and Y");
                }
              } else {
                if(column.textContent ==="X"){
                    alert("white box and X");
                }else{
                    alert("white box and Y");
                }
              }
            });
            row.appendChild(column);
          }
          table.appendChild(row);
        }
        scacchiera = table;
        return scacchiera;
      }

      createTable();
      document.body.appendChild(scacchiera);
    </script>

</code>```

答:
You need to remove column as an argument to event Listener callback

```<code>column.addEventListener("click", function (column) { ...
</code>```

to

```<code>column.addEventListener("click", function () { ...
</code>```

Body:
You need to remove column as an argument to event Listener callback

column.addEventListener("click", function (column) { ...

to

column.addEventListener("click", function () { ...


问:
What's a good way to find relative paths in Google App Engine?
So I've done the trivial "warmup" apps with GAE.  Now I'd like to build something with a more complex directory structure.  Something along the lines of:

```<code>siteroot/
    models/
    controllers/
        controller1/
        controller2/
        ...
    templates/
        template1/
        template2/
        ...
</code>```

..etc.  The controllers will be Python modules handling requests.  They would then need to locate (Django-style) templates in associated folders.  Most of the demo apps I've seen resolve template paths like this:

```<code>path = os.path.join(os.path.dirname(__file__), 'myPage.html')
</code>```

...the __ file __ property resolves to the currently executing script.  So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.

The solution I've hacked together feels... hacky:

```<code>base_paths = os.path.split(os.path.dirname(__file__))
template_dir = os.path.join(base_paths[0], "templates")
</code>```

So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path.  The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly).  Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.

I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm.  So what's a better way?

答:
The dirname function returns an absolute path, use relative paths. See what is the current directory when your controllers are executed with os.path.abspath(os.path.curdir) and build a path to the templates relative to that location (without the os.path.abspath part of course).

This will only work if the current directory is somewhere inside siteroot, else you could do something like this:

```<code>template_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, "templates")
</code>```

OwnerDisplayName: Rob Collins

ContentLicense: CC BY-SA 2.5

Body:
So I've done the trivial "warmup" apps with GAE.  Now I'd like to build something with a more complex directory structure.  Something along the lines of:

siteroot/
    models/
    controllers/
        controller1/
        controller2/
        ...
    templates/
        template1/
        template2/
        ...

..etc.  The controllers will be Python modules handling requests.  They would then need to locate (Django-style) templates in associated folders.  Most of the demo apps I've seen resolve template paths like this:

path = os.path.join(os.path.dirname(__file__), 'myPage.html')

...the __ file __ property resolves to the currently executing script.  So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.

The solution I've hacked together feels... hacky:

base_paths = os.path.split(os.path.dirname(__file__))
template_dir = os.path.join(base_paths[0], "templates")

So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path.  The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly).  Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.

I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm.  So what's a better way?

LastEditorDisplayName: Gulzar

Body:
The dirname function returns an absolute path, use relative paths. See what is the current directory when your controllers are executed with os.path.abspath(os.path.curdir) and build a path to the templates relative to that location (without the os.path.abspath part of course).

This will only work if the current directory is somewhere inside siteroot, else you could do something like this:

template_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, "templates")

OwnerDisplayName: Toni Ruža

LastEditorDisplayName: Toni Ruža


问:
Redirecting to a 500 page when an AJAX call fails in Ruby on Rails
I'm working with an application built in Ruby on Rails with very poor error handling right now. If a controller method is executed via ajax, and that method results in a 500 (or 404 or any other response) the 500.html page is rendered and returned as the result to the AJAX request. Obviously the javascript doesn't know what to do with that HTML and the web page looks like it's just waiting for a response.

Is there an easy way in rails to render an error.rjs template anytime an error occurs during an AJAX call?

答:
You can use respond_to inside a controller's rescue_action or rescue_action_in_public method. Consider the following controller:</p>

```<code>class DefaultController < ApplicationController

  def index
    raise "FAIL"
  end

  def rescue_action(exception)
    respond_to do |format|
      format.html { render :text => "Rescued HTML" }
      format.js { render :action => "errors" }
    end
  end
end
</code>```

OwnerDisplayName: Kyle Boon

Body:
You can use respond_to inside a controller's rescue_action or rescue_action_in_public method. Consider the following controller:

class DefaultController < ApplicationController

  def index
    raise "FAIL"
  end

  def rescue_action(exception)
    respond_to do |format|
      format.html { render :text => "Rescued HTML" }
      format.js { render :action => "errors" }
    end
  end
end

OwnerDisplayName: cpm


问:
C#: how to handle floats properly
In my code i write the following line:

```<code>return ((value / 120) * 1440).ToString();
</code>```

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960

ContentLicense: CC BY-SA 3.0

Title: C#: how to handle floats properly

Body:
In my code i write the following line:

return ((value / 120) * 1440).ToString();

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960

Body: return ((value / 120.0) * 1440).ToString();


问:
Command prompt changing characters in pasted text
I'm writing a C# console application, and whenever I paste text that contains double quotation marks into the console, it changes them to a regular quotation mark.

Here's an example:
I paste „Hello World!” into the console, but it displays „Hello World!" instead. I tried changing the input and output enconding to unicode, but it didn't help. Pasting into notepad works just fine.

答:
Found solution for pure cmd window as well as for a console application if run by double click from File Explorer. There is a DWORD value
 named FilterOnPaste under registry key HKEY_CURRENT_USER\Console. Defaults to 1 (1 enables new paste behavior), change it to 0.

Check

```<code>reg query HKCU\Console -v FilterOnPaste
</code>```

and if you get default data

```<code>HKEY_CURRENT_USER\Console
    FilterOnPaste    REG_DWORD    0x1
</code>```

or ERROR: The system was unable to find the specified registry key or value then run

```<code>reg add HKCU\Console -v FilterOnPaste -d 0 -t REG_DWORD -f
</code>```

```<code>The operation completed successfully.
</code>```

An explanation at What's New in the Windows Console in Windows Server 2016 => Controlling the new features (valid for Windows 10 console as well).

Another explanation for a cmd shortcut settings with screenshots at How to enable the new console in Windows 10 and what are its defaults?.

Actually I can't understand full meaning and consequences of new paste behavior.

Body:
Found solution for pure cmd window as well as for a console application if run by double click from File Explorer. There is a DWORD value
 named FilterOnPaste under registry key HKEY_CURRENT_USER\Console. Defaults to 1 (1 enables new paste behavior), change it to 0.

Check

reg query HKCU\Console -v FilterOnPaste

and if you get default data

HKEY_CURRENT_USER\Console
    FilterOnPaste    REG_DWORD    0x1

or ERROR: The system was unable to find the specified registry key or value then run

reg add HKCU\Console -v FilterOnPaste -d 0 -t REG_DWORD -f

The operation completed successfully.

An explanation at What's New in the Windows Console in Windows Server 2016 => Controlling the new features (valid for Windows 10 console as well).

Another explanation for a cmd shortcut settings with screenshots at How to enable the new console in Windows 10 and what are its defaults?.

Actually I can't understand full meaning and consequences of new paste behavior.


问:
Using useEffect with React-redux
I have a problem. As I understood hook useEffect doen't run.
I have action that should take data from server.

```<code>export const getProducts = () => {
    return dispatch => {
        dispatch(getProductsStarted());

        fetch('https://shopserver.firebaseapp.com/get-products')
            .then(res => {
                dispatch(getProductsSuccess(res.json()));
            })
            .catch(err => {
                dispatch(getProductsFailure(err.message));
            });
    }
}

const getProductsSuccess = todo => ({
    type: "ADD_TODO_SUCCESS",
    payload: {
        ...todo
    }
});

const getProductsStarted = () => ({
    type: "ADD_TODO_STARTED"
});

const getProductsFailure = error => ({
    type: "ADD_TODO_FAILURE",
    payload: {
        error
    }
});
</code>```

I have a reducer.

```<code>const initialState = {
    loading: false,
    products: [],
    error: null
}

export const ProductReducer = (state = initialState, action) => {
    switch (action.type) {
        case "ADD_TODO_SUCCESS":
            return {
                ...state,
                loading: false,
                error: null,
                todos: [...state.products, action.payload.products]
            }
        case "ADD_TODO_STARTED":
            return {
                ...state,
                loading: true
            }
        case "ADD_TODO_FAILURE":
            return {
                ...state,
                loading: false,
                error: action.payload.error
            }
        default:
            return state
    }
}
</code>```

And I have a Component where I want to render a result.

```<code>import React from 'react';
import { CardItem } from "./cardItem";
import { useSelector } from 'react-redux';
import { useEffect } from 'react';
import { getProducts } from '../Redux/Actions/productAction'

export const ProductCard = () => {

    useEffect(() => {
        getProducts();
        console.log('111111')
    })

    const data = useSelector(state => state.ProductReducer.products);

    return (
        <div>
            {data.map( element =>
                CardItem (element)
            )}
        </div>
    )
}
</code>```

After rendering page nothing happens. ReduxDevTools shows that there was no send actions. Please, help me to fix it. Thank you.

答:
I think you should be calling your async action like this :

```<code>import { useDispatch, useSelector } from 'react-redux';

[...]

export const ProductCard = () => {

  const dispatch = useDispatch();

  useEffect(() => {
      // I guess getProducts is an async redux action using redux-thunk
      dispatch(getProducts());
      console.log('111111')
  }, []);

  [...]

}
</code>```

I assume you want to load products only when component is born, so I pass an empty array as second argument for useEffect (https://reactjs.org/docs/hooks-reference.html#useeffect).

Title: Using useEffect with React-redux

Body:
I have a problem. As I understood hook useEffect doen't run.
I have action that should take data from server.

export const getProducts = () => {
    return dispatch => {
        dispatch(getProductsStarted());

        fetch('https://shopserver.firebaseapp.com/get-products')
            .then(res => {
                dispatch(getProductsSuccess(res.json()));
            })
            .catch(err => {
                dispatch(getProductsFailure(err.message));
            });
    }
}

const getProductsSuccess = todo => ({
    type: "ADD_TODO_SUCCESS",
    payload: {
        ...todo
    }
});

const getProductsStarted = () => ({
    type: "ADD_TODO_STARTED"
});

const getProductsFailure = error => ({
    type: "ADD_TODO_FAILURE",
    payload: {
        error
    }
});

I have a reducer.

const initialState = {
    loading: false,
    products: [],
    error: null
}

export const ProductReducer = (state = initialState, action) => {
    switch (action.type) {
        case "ADD_TODO_SUCCESS":
            return {
                ...state,
                loading: false,
                error: null,
                todos: [...state.products, action.payload.products]
            }
        case "ADD_TODO_STARTED":
            return {
                ...state,
                loading: true
            }
        case "ADD_TODO_FAILURE":
            return {
                ...state,
                loading: false,
                error: action.payload.error
            }
        default:
            return state
    }
}

And I have a Component where I want to render a result.

import React from 'react';
import { CardItem } from "./cardItem";
import { useSelector } from 'react-redux';
import { useEffect } from 'react';
import { getProducts } from '../Redux/Actions/productAction'

export const ProductCard = () => {

    useEffect(() => {
        getProducts();
        console.log('111111')
    })

    const data = useSelector(state => state.ProductReducer.products);

    return (

            {data.map( element =>
                CardItem (element)
            )}

    )
}

After rendering page nothing happens. ReduxDevTools shows that there was no send actions. Please, help me to fix it. Thank you.

Body:
I think you should be calling your async action like this :

import { useDispatch, useSelector } from 'react-redux';

[...]

export const ProductCard = () => {

  const dispatch = useDispatch();

  useEffect(() => {
      // I guess getProducts is an async redux action using redux-thunk
      dispatch(getProducts());
      console.log('111111')
  }, []);

  [...]

}

I assume you want to load products only when component is born, so I pass an empty array as second argument for useEffect (https://reactjs.org/docs/hooks-reference.html#useeffect).


问:
Problems with Jax's JIT and Numpy restrictions
I've recently started experimenting with the interesting python library Jax, which contains a boosted Numpy as well as Automatic Differentiator. What I wanted to try to create, is a crude "differentiable renderer", by writing a shader and loss function in python, then using Jax's AD to find the gradient. We should then be able to inverse render an image by running gradient descent on this loss gradient. I have made it work fairly well with simple shaders, but I have run into problems when I use boolean expressions. This is the code of my shader, which generates a checkerboard pattern:

import jax.numpy as np

class CheckerShader:

    def __init__(self, scale: float, color1: np.ndarray, color2: np.ndarray):
        self.color1 = None
        self.color2 = None
        self.scale = None
        self.scale_min = 0
        self.scale_max = 20
        self.color1 = color1
        self.color2 = color2
        self.scale = scale * 20

    def checker(self, x: float, y: float) -> float:
        xi = np.abs(np.floor(x))
        yi = np.abs(np.floor(y))

        first_col = np.mod(xi, 2) == np.mod(yi, 2)
        return first_col

    def shade(self, x: float, y: float):
        x = x * self.scale
        y = y * self.scale

        first_col = self.checker(x, y)
        if first_col:
            return self.color1
        else:
            return self.color2
```

<p>And this is my render function, which is the first place that JIT fails:</p>

<pre class="lang-py prettyprint-override"><code>import jax.numpy as np
import numpy as onp
import jax

def render(scale, c1, c2):
    img = onp.zeros((WIDTH, HEIGHT, CHANNELS))
    sh = CheckerShader(scale, c1, c2)
    jit_func = jax.jit(sh.shade)

    for y in range(HEIGHT):
        for x in range(WIDTH):
            val = jit_func(x / WIDTH, y / HEIGHT)
            img[y, x, :] = val

    return img
</code>```

The error message I receive is:

```<code>TypeError: Abstract value passed to `bool`, which requires a concrete value. The function to be transformed can't be traced at the required level of abstraction. If using `jit`, try using `static_argnums` or applying `jit` to smaller subfunctions instead.
</code>```

and I guess it is because you can't run JIT on a function with booleans whose values depend on something that is not decided during compile time. But how can I rewrite it to work with JIT? Without JIT, it is painfully slow.

Another question I have is, is there something I can do to speed up Jax's Numpy in general? Rendering my image (100x100 pixels) with normal Numpy takes a few milliseconds, but with Jax's Numpy, it takes seconds! Thanks :D

答:
But how can I rewrite it to work with JIT?

Ivo has a nice answer here - simply use np.where.

Another question I have is, is there something I can do to speed up Jax's Numpy in general?

There are probably three reasons why this is slow.

The first is the nature of JITing. It will be slow the first time you run your code, but if you run the same code multiple times the speed should increase. I would also try to JIT the entire render function if possible, if you plan to run this multiple times.

The second reason is that switching between numpy and jax.numpy will be very slow. You write

img = onp.zeros((WIDTH, HEIGHT, CHANNELS))

but it'll be much faster if you write

img = np.zeros((WIDTH, HEIGHT, CHANNELS))

The third is that you are looping over width and height rather than using vectorized operations. I don't see why you can't do this in fully vectorized form.

Body:
I've recently started experimenting with the interesting python library Jax, which contains a boosted Numpy as well as Automatic Differentiator. What I wanted to try to create, is a crude "differentiable renderer", by writing a shader and loss function in python, then using Jax's AD to find the gradient. We should then be able to inverse render an image by running gradient descent on this loss gradient. I have made it work fairly well with simple shaders, but I have run into problems when I use boolean expressions. This is the code of my shader, which generates a checkerboard pattern:

import jax.numpy as np

class CheckerShader:

    def __init__(self, scale: float, color1: np.ndarray, color2: np.ndarray):
        self.color1 = None
        self.color2 = None
        self.scale = None
        self.scale_min = 0
        self.scale_max = 20
        self.color1 = color1
        self.color2 = color2
        self.scale = scale * 20

    def checker(self, x: float, y: float) -> float:
        xi = np.abs(np.floor(x))
        yi = np.abs(np.floor(y))

        first_col = np.mod(xi, 2) == np.mod(yi, 2)
        return first_col

    def shade(self, x: float, y: float):
        x = x * self.scale
        y = y * self.scale

        first_col = self.checker(x, y)
        if first_col:
            return self.color1
        else:
            return self.color2

And this is my render function, which is the first place that JIT fails:

import jax.numpy as np
import numpy as onp
import jax

def render(scale, c1, c2):
    img = onp.zeros((WIDTH, HEIGHT, CHANNELS))
    sh = CheckerShader(scale, c1, c2)
    jit_func = jax.jit(sh.shade)

    for y in range(HEIGHT):
        for x in range(WIDTH):
            val = jit_func(x / WIDTH, y / HEIGHT)
            img[y, x, :] = val

    return img

The error message I receive is:

TypeError: Abstract value passed to `bool`, which requires a concrete value. The function to be transformed can't be traced at the required level of abstraction. If using `jit`, try using `static_argnums` or applying `jit` to smaller subfunctions instead.

and I guess it is because you can't run JIT on a function with booleans whose values depend on something that is not decided during compile time. But how can I rewrite it to work with JIT? Without JIT, it is painfully slow.

Another question I have is, is there something I can do to speed up Jax's Numpy in general? Rendering my image (100x100 pixels) with normal Numpy takes a few milliseconds, but with Jax's Numpy, it takes seconds! Thanks :D


问:
Is ordered ensured in list iteration in Python?
Let's suppose to have a list of strings, named strings, in Python and to execute this line:

```<code>lengths = [ len(value) for value in strings ]
</code>```

Is the strings list order kept? I mean, can I be sure that lengths[i] corresponds to strings[i]?
I've tryed many times and it works but I'm not sure if my experiments were special cases or the rule.

Thanks in advance

答:
Yes, since list in python are sequences you can be sure that each length that you have in the list of the length is corresponding to the string length in the same index.
like the following code represents

```<code>a = ['a', 'ab', 'abc', 'abcd']
print([len(i) for i in a])
</code>```

Output

```<code>[1, 2, 3, 4]
</code>```

Body:
Let's suppose to have a list of strings, named strings, in Python and to execute this line:

lengths = [ len(value) for value in strings ]

Is the strings list order kept? I mean, can I be sure that lengths[i] corresponds to strings[i]?
I've tryed many times and it works but I'm not sure if my experiments were special cases or the rule.

Thanks in advance

Body:
Yes, since list in python are sequences you can be sure that each length that you have in the list of the length is corresponding to the string length in the same index.
like the following code represents

a = ['a', 'ab', 'abc', 'abcd']
print([len(i) for i in a])

Output

[1, 2, 3, 4]


问:
Running an accuracy formula
I am extremely new to python and i wanted to run an accuracy formula. The formula is like this X - Y(whichever of the two is bigger)/ The biggest number(either X or Y). My Y is this Y = [46.65347546, 49.52538101, 50.71174784, 47.95042085, 53.36249628, 48.50331361, 49.20114466, 55.90266617] and my X is this X = [60,51,54,61,51,50,55,59]. I want to run this formula for each individual value and then the average of all the values. How can i write this formula in python? What i'm not sure how to do is how to subtract and divide with the biggest number of the two.

Title: Running an accuracy formula

Body:
You can first use zip and then compute the accuracy

accuracy = map(lambda t: abs(t[0] - t[1])/max(t[0], t[1]), zip(X, Y))

This returns the expected result (python3)

>>> print(*accuracy)
[0.22244207566666663, 0.02891409784313732, 0.0608935585185185, 0.21392752704918033, 0.04427259676165963, 0.029933727800000014, 0.10543373345454551, 0.052497183559321974]


问:
Remove Numbers and Turn into a List
#

PYTHON
A clearer way of asking the question is:

If I have a string as follows:
'PALM BEACH.Race 6GaveaRace 5MaronasRace 7IOWARace 3ORANGE PARK.Race 5'

How do I turn that string into:
Palm Beach, Gavea, Maronas, Iowa, Orange Park

So that is, make each item in the list 'title'(ie. Uppercase first letter and the rest lower case), delete the numbers and the word 'Race'.

I am setting up to export to Excel.

Thanks in advance - Angus

#

答:
You can do it without importing any library:

```<code>races = """PALM BEACH.Race 6GaveaRace 5MaronasRace 7IOWARace 3ORANGE PARK.Race 5"""
''.join([ch if not ch.isdigit() else 'xxx' for ch in races.replace('Race ','')]).split('xxx')
</code>```

Output:

```<code>['PALM BEACH.', 'Gavea', 'Maronas', 'IOWA', 'ORANGE PARK.', '']
</code>```

Title: Remove Numbers and Turn into a List

Body:
You can do it without importing any library:

races = """PALM BEACH.Race 6GaveaRace 5MaronasRace 7IOWARace 3ORANGE PARK.Race 5"""
''.join([ch if not ch.isdigit() else 'xxx' for ch in races.replace('Race ','')]).split('xxx')

Output:

['PALM BEACH.', 'Gavea', 'Maronas', 'IOWA', 'ORANGE PARK.', '']


问:
Stop Python script with ctrl + c
I have a script which uses threads, but it is unable to catch Ctrl + C.

Here it is the sample code to reproduce this error:

```<code>import threading
import time
import signal

class DummyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self._running = True
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

    def stop(self, signum=None, frame=None):
        self._running = False

    def run(self):
        while self._running:
            time.sleep(1)
            print("Running")

if __name__ == "__main__":
    try:
        t = DummyThread()
        t.start()
        while True:
            print("Main thread running")
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("This never gets printed")
        t.stop()
    finally:
        print("Exit")
</code>```

When I run python3 script.py it starts running, but it does not catch ctrl+c. I have googled it but I have not found a solution. I have to kill the script with SIGTERM, but I want DummyThread to stop gracefully.

答:
The main point is that you can't work with signals in any other Thread except the Main Thread. The Main Thread is the only one which can receive signals and handle them. I can offer the following solution, it is based on Event sync primitive.

According to Python documantation:

Signals and threads
  Python signal handlers are always executed in the main Python thread, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.

Besides, only the main thread is allowed to set a new signal handler.

```<code>from threading import Thread, Event
import time

class DummyThread(Thread):

    def __init__(self, event: Event):
        Thread.__init__(self)
        self.stop_event = event

    def run(self):
        # we are monitoring the event in the Main Thread
        while not self.stop_event.is_set():
            time.sleep(1)
            print("Running")
        # only Main Thread can make the point reachable
        print("I am done !")

if __name__ == "__main__":
    try:
        e = Event()
        t = DummyThread(e)
        t.start()
        while True:
            print("Main thread running")
            time.sleep(0.5)
    except KeyboardInterrupt:
        e.set()
    finally:
        print("Exit")

</code>```

Another possible choice is to use daemon Thread for such tasks like in your code example (when you just printing smth in the screen every second, rather than e.g. close database connection or some similar task). If main thread is stoped the daemon Thread will stop too.

Title: Stop Python script with ctrl + c

Body:
I have a script which uses threads, but it is unable to catch Ctrl + C.

Here it is the sample code to reproduce this error:

import threading
import time
import signal

class DummyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self._running = True
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

    def stop(self, signum=None, frame=None):
        self._running = False

    def run(self):
        while self._running:
            time.sleep(1)
            print("Running")

if __name__ == "__main__":
    try:
        t = DummyThread()
        t.start()
        while True:
            print("Main thread running")
            time.sleep(0.5)
    except KeyboardInterrupt:
        print("This never gets printed")
        t.stop()
    finally:
        print("Exit")

When I run python3 script.py it starts running, but it does not catch ctrl+c. I have googled it but I have not found a solution. I have to kill the script with SIGTERM, but I want DummyThread to stop gracefully.

Body:
The main point is that you can't work with signals in any other Thread except the Main Thread. The Main Thread is the only one which can receive signals and handle them. I can offer the following solution, it is based on Event sync primitive.

According to Python documantation:

Signals and threads
  Python signal handlers are always executed in the main Python thread, even if the signal was received in another thread. This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the threading module instead.

Besides, only the main thread is allowed to set a new signal handler.

from threading import Thread, Event
import time

class DummyThread(Thread):

    def __init__(self, event: Event):
        Thread.__init__(self)
        self.stop_event = event

    def run(self):
        # we are monitoring the event in the Main Thread
        while not self.stop_event.is_set():
            time.sleep(1)
            print("Running")
        # only Main Thread can make the point reachable
        print("I am done !")

if __name__ == "__main__":
    try:
        e = Event()
        t = DummyThread(e)
        t.start()
        while True:
            print("Main thread running")
            time.sleep(0.5)
    except KeyboardInterrupt:
        e.set()
    finally:
        print("Exit")

Another possible choice is to use daemon Thread for such tasks like in your code example (when you just printing smth in the screen every second, rather than e.g. close database connection or some similar task). If main thread is stoped the daemon Thread will stop too.


答:
You should always avoid using a fixed px in css, instead, em or rem which are relative units are always preferred.

The semantic HTML elements are not used as intended here - the text in the circle should not be contained within a list.

It is easier to position in the center by making the circle element a flexbox and using justify-content:center and align-items:center

Title: Border-radius are not centered aligned,when changing screen size

Body:
I've fixed everything into the laptop screen size and everything is centred aligned until I begin to switch over to tablet/mobile screen using dev toolbars the top border-radius is shifted towards the left and the bottom 3 circles are not following properly. I heard that px is not suitable to be used instead you should use rem/em in order to be responsive to any screen size, is that true?

.container1 {
    max-width: 1000px;
    margin: 0 auto;
    padding:0 auto;
}
.circle1 p {
    position: absolute;
    transform: translate(60px, 80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle2 p{
    margin: 0;
    position: absolute;
    transform: translate(20px,80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.circle3 p {
    margin: 0;
    position: absolute;
    transform: translate(50px, 80px);
    font-weight: bold;
    font-family: 'Lato';font-size: 28px;
}
.navigation  {
    position:relative;
    border: 2px solid rgb(211,211,211);
    width: 300px;
    margin:100px 50px 80px 350px;
    border-radius: 100%;
    height: 300px;
    background: white;
}
.navigation ul {
    margin: 0;
    padding: 0;
    text-align: center;
    list-style-type: none;
}

.navigation li {
    padding:10px 80px 0px 68px;
    font-weight: 100;
    letter-spacing: 2px;
    font-size: 35px;
    font-family: 'Roboto', sans-serif;
}

.circle1{
    margin: 0 auto;
    position: relative;
    transform: translate(150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);

}
.circle2{
    margin: 0 auto;
    position: relative;
    transform: translate(0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.circle3{
    margin: 0 auto;
    position: relative;
    transform: translate(-150px, 0px);
    border: 2px solid rgb(211,211,211);
    width: 210px;
    border-radius: 100%;
    height: 200px;
    background:rgb(211,211,211);
}

.border-circle li{
    list-style-type: none;
    text-decoration: none;

}
.border-circle{
    min-width: 1349px;
    width: 100%;
    top: 70%;
    display: flex;
}

.fa-10x{
    opacity: 0.3;
    font-size:7em !important;
    transform: translate(50px, 30px);
    position: relative;
    text-decoration: none;
    color: inherit;
}

.fa-9x{
    position: relative;
    font-size:7em !important;
    transform: translate(40px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

.fa-8x{
    position: relative;
    font-size:7em !important;
    transform: translate(50px, 30px);
    opacity: 0.3;
    color: inherit;
    text-decoration: none;
}

a {
    color: inherit;
}

<!DOCTYPE html>

    <jsp:include page="../head.html" />

Circle

in

 Circle1

 Circle2

 Circle3


答:
For lists, yes. That is one of the fundamental properties of lists: that they're ordered.

It should be noted though that what you're doing though is known as "parallel arrays" (having several "arrays" to maintain a linked state), and is often considered to be poor practice. If you change one list, you must change the other in the same way, or they'll be out of sync, and then you have real problems.

A dictionary would likely be the better option here:

```<code>lengths_dict = {value:len(value) for value in strings}
print(lengths_dict["some_word"])  # Prints its length
</code>```

Or maybe if you want lookups by index, a list of tuples:

```<code>lengths = [(value, len(value)) for value in strings]
word, length = lengths[1]
</code>```

Title: Is ordered ensured in list iteration in Python?

Body:
For lists, yes. That is one of the fundamental properties of lists: that they're ordered.

It should be noted though that what you're doing though is known as "parallel arrays" (having several "arrays" to maintain a linked state), and is often considered to be poor practice. If you change one list, you must change the other in the same way, or they'll be out of sync, and then you have real problems.

A dictionary would likely be the better option here:

lengths_dict = {value:len(value) for value in strings}
print(lengths_dict["some_word"])  # Prints its length

Or maybe if you want lookups by index, a list of tuples:

lengths = [(value, len(value)) for value in strings]
word, length = lengths[1]


问:
How to run quarkus tests using certain profile defined in application.properties
Say I have the following in application.properties:

```<code>quarkus.datasource.url=${db_url:jdbc:postgresql://localhost:5432/ekycapi}
%dockerrun.quarkus.datasource.url=${db_url:jdbc:postgresql://postgres:5432/anotherdb}
</code>```

When running in dev mode, I run as "mvn quarkus:dev -Dquarkus.profile=dockerrun"
But what if I want to use the same profile while running the tests? What is the correct syntax for it? Something like "mvn test -Dquarkus.profile=dockerrun"?

答: Use quarkus.test.profile to set the desired test profile. See more config options on  the all-config page

Body:
Say I have the following in application.properties:

quarkus.datasource.url=${db_url:jdbc:postgresql://localhost:5432/ekycapi}
%dockerrun.quarkus.datasource.url=${db_url:jdbc:postgresql://postgres:5432/anotherdb}

When running in dev mode, I run as "mvn quarkus:dev -Dquarkus.profile=dockerrun"
But what if I want to use the same profile while running the tests? What is the correct syntax for it? Something like "mvn test -Dquarkus.profile=dockerrun"?


问:
Why can't I run phpinfo() in my docker container?
I am trying to get a connection between my php-fpm docker container and an RDS Postregsql. I found that I was getting an error in my php application "call to undefined function pg_connect()". So I thought that maybe the issue was that I didn't have pgsql driver enabled in my php.ini. So I tried to enable it, by first adding a line to my Dockerfile, rebuilding the image, then I brought down the container and brought it up again. But I am getting the same error "call to undefined function pg_connect(). So I'd like to run phpinfo() in the container to see if the pgsql driver is loaded. I tried to run it by using docker exec 4822 /bin/bash to open a cli to the container, but the host cli just comes back with a $. How can I run phpinfo() in the container so I can figure out why $DB2 = $this->load->database('postgres', TRUE) is failing with the above error? I am using Codeigniter and here is the connection array:

```<code>enter code here

enter code here
</code>```

Sorry I can't get the format going. Anyway, here is the dsn
'dsn' => 'jdbc:postgresql://imagesdatabase.cwymdn16cxes.us-east-1.rds.amazonaws.com:5432/postgres'

答:
From the $ prompt:

```<code>php
</code>```

should start the PHP process. Then:

```<code><?php phpinfo();
</code>```

will display phpinfo() output. You will need to end the php process with a Control-D and then all output should be displayed.

Body:
I am trying to get a connection between my php-fpm docker container and an RDS Postregsql. I found that I was getting an error in my php application "call to undefined function pg_connect()". So I thought that maybe the issue was that I didn't have pgsql driver enabled in my php.ini. So I tried to enable it, by first adding a line to my Dockerfile, rebuilding the image, then I brought down the container and brought it up again. But I am getting the same error "call to undefined function pg_connect(). So I'd like to run phpinfo() in the container to see if the pgsql driver is loaded. I tried to run it by using docker exec 4822 /bin/bash to open a cli to the container, but the host cli just comes back with a $. How can I run phpinfo() in the container so I can figure out why $DB2 = $this->load->database('postgres', TRUE) is failing with the above error? I am using Codeigniter and here is the connection array:

enter code here

enter code here

Sorry I can't get the format going. Anyway, here is the dsn
'dsn' => 'jdbc:postgresql://imagesdatabase.cwymdn16cxes.us-east-1.rds.amazonaws.com:5432/postgres'

Body:
From the $ prompt:

php

should start the PHP process. Then:

<?php phpinfo();

will display phpinfo() output. You will need to end the php process with a Control-D and then all output should be displayed.


问:
Xamarin.Forms Android project lost all references in VS2019
EDIT

I decided to just go with a fresh windows install and hope for it to fix my problem - but guess what! It didn't.
My home PC installed VS2019 and AndroidSDK without any problems and it's working flawlessly, but my work laptop just don't work. I'm starting to think it has something to do with my username being "C:/users/LudvigÅslund" while my home PC got "C:/users/ludas".

End of EDIT

As I've got no clue what happened today, I'll try explain as much as possible.

Today when i opened my Xamarin.Forms project, my Android project decided to lose all of its references, and when I try to open the emulator I get the error message:

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT

Emulator tablet_m-dpi_10_1in_pie_9_0_-_api_28 cannot be started.

Not quite sure what's going on. I've tried deleting and recreating my Android Emulator, changed SDK versions, etc etc. And nothing helps.

I can't access Xamarin.Forms in my Android project, nor any of the included dependencies through my PCL, it's just red everywhere.

OnCreate()-method in MainActivity.cs

My iOS project works just fine, and so does my PCL. So it's obviously something with Android - I just don't know what, or how it could become like this from shutting down the PC last night.

I've also tried to create a fresh Xamarin.Forms project and even then my .Droid-project just wont work. I've reinstalled VisualStudio 2019 with both 16.5 and 16.6 versions and nothing works.

AVD path: C:\Users\LudvigÅslund\.android\avd

SDK path: C:\Program Files (x86)\Android\android-sdk

PCL Dependencies

.Droid Depencencies/references

答:
I had the same issue because I used a 'ü' in the solution location which was: 'C:\git\krüfer\'. non of the references could be loaded in the .Android project
The error I had was:
system.xml.xmlexception</p>


问:
NSString with \0
What is the best way to initiate NSString that contains @"\0"?

```<code>NSString* foo = @"bar\0";
</code>```

causes 'CFString literal contains NUL character' warning.

答:
You can put a NUL character into an NSString instance, here's one example:

```<code>int main() {
    NSString *string = [NSString stringWithFormat: @"Hello%CWorld!", 0];
    NSData *bytes = [string dataUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"string: %@", string);
    NSLog(@"bytes: %@", bytes);
    return 0;
}
</code>```

Be aware that at surprising points in your app's execution, the string will be converted into a C string (or something similar) for interacting with lower-level API, and that this will cause the string to be truncated. As an example, the output of the above program is this:

2011-06-02 09:18:30.307
  Untitled[294:707] string: Hello

2011-06-02 09:18:30.309
  Untitled[294:707] bytes: <48656c6c
  6f00576f 726c6421>

Showing that the NSString itself is completely intact but that NSLog() won't display it correctly.

Title: NSString with \0

Body:
What is the best way to initiate NSString that contains @"\0"?

NSString* foo = @"bar\0";

causes 'CFString literal contains NUL character' warning.

Body:
You can put a NUL character into an NSString instance, here's one example:

int main() {
    NSString *string = [NSString stringWithFormat: @"Hello%CWorld!", 0];
    NSData *bytes = [string dataUsingEncoding: NSUTF8StringEncoding];
    NSLog(@"string: %@", string);
    NSLog(@"bytes: %@", bytes);
    return 0;
}

Be aware that at surprising points in your app's execution, the string will be converted into a C string (or something similar) for interacting with lower-level API, and that this will cause the string to be truncated. As an example, the output of the above program is this:

2011-06-02 09:18:30.307
  Untitled[294:707] string: Hello

2011-06-02 09:18:30.309
  Untitled[294:707] bytes: <48656c6c
  6f00576f 726c6421>

Showing that the NSString itself is completely intact but that NSLog() won't display it correctly.


问:
Mule 4 : Is there a way to refer Maven POM properties from a Mule Flow?
I want to refer the project name and version in the URL of the API. For example, my app is called sample-mule-project and has a version "v1". So my final URL should be like /sample-mule-project/v1/

Maven pom has these properties called name and version with which we can refer these values inside the pom file. Is there a way how we can refer these values inside the mule flow?

I tried using ${project.name} and ${project.version} but it did not work which I understand is because these are not defined inside properties file. So is there a way to achieve this?

答:
That's because Maven properties do not exists anymore when the application is executed.

You can use some Maven plugins to replace values in a properties files, that can be used inside the application. For example the Maven Resources plugin. Be careful of not override properties inside other files, like the XML Mule configurations of the application.


问:
Can we type if statement inside the function an argument
For example

```<code>def person(name,if age == 18:...//some instructions and this parameter will be default parameter):
   print(age)
   print(name)

person('Ratheesh')
</code>```

// I Know it sounds dump and silly, but is there any possibility to do that?

I was trying to confirm the user has entered the exact value in argument as i entered...But fortunately i have done it with default argument but whenever i change the parameter value it overrides so, i want to avoid the override...

答:
Do you mean a default parameter?

```<code>def person(name, age=18):
   print(age)
   print(name)

person('Ratheesh')
</code>```

Returns:

```<code>18
Ratheesh
</code>```

And:

```<code>person('Ratheesh', 20)
</code>```

Returns:

```<code>20
Ratheesh
</code>```

Body:
For example

def person(name,if age == 18:...//some instructions and this parameter will be default parameter):
   print(age)
   print(name)

person('Ratheesh')

// I Know it sounds dump and silly, but is there any possibility to do that?

I was trying to confirm the user has entered the exact value in argument as i entered...But fortunately i have done it with default argument but whenever i change the parameter value it overrides so, i want to avoid the override...

Body:
Do you mean a default parameter?

def person(name, age=18):
   print(age)
   print(name)

person('Ratheesh')

Returns:

18
Ratheesh

And:

person('Ratheesh', 20)

Returns:

20
Ratheesh


问:
Wine dataset LDA & PCA comparison - Python
I am trying to run this Comparison of LDA and PCA 2D projection of Iris dataset example  with a WINE dataset that I download from the internet but I get the error:

```<code>d:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py:760: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().   y = column_or_1d(y, warn=True)
--------------------------------------------------------------------------- IndexError                                Traceback (most recent call last) <ipython-input-44-a42b504da984> in <module>
     14
     15 for color, i, target_name in zip(colors, [0, 1, 2], target_names):
---> 16     plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
     17                 label=target_name)
     18 plt.legend(loc='best', shadow=False, scatterpoints=1)

IndexError: too many indices for array

<Figure size 432x288 with 0 Axes>
</code>```

How can I fix it?

Code:

```<code>import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

import pandas as pd

df = pd.read_csv('https://gist.githubusercontent.com/tijptjik/9408623/raw/b237fa5848349a14a14e5d4107dc7897c21951f5/wine.csv')
df.to_numpy()

X  = df.iloc[:,[1,2,3,4,5,6,7,8,9,10,11,12,13]]
X.to_numpy()
y  = df.iloc[:,[0]]
y.to_numpy()
target_names = y

pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
      % str(pca.explained_variance_ratio_))

plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2

for color, i, target_name in zip(colors, [0, 1, 2], target_names):
    plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
                label=target_name)
</code>```

答:
If you look at your y vs the y in the example script, you will see that your y has multiple dimensions even if the second dim is of length 0. You need to remove this 2nd dimension which can be done via np.squeeze

```<code>y = np.squeeze(df.loc[:,['Wine']].to_numpy())
</code>```

Here is the full code

```<code>import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

df = pd.read_csv('https://gist.githubusercontent.com/tijptjik/9408623/raw/b237fa5848349a14a14e5d4107dc7897c21951f5/wine.csv')

X = df.loc[:, df.columns != 'Wine'].to_numpy()
y = np.squeeze(df.loc[:,['Wine']].to_numpy())
target_names = ['first', 'sceond', 'third']

pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
    % str(pca.explained_variance_ratio_))

plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2

for color, i, target_name in zip(colors, [1,2,3], target_names):
    plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
                label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of Wine dataset')

plt.figure()
for color, i, target_name in zip(colors, [1, 2, 3], target_names):
    plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], alpha=.8, color=color,
                label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('LDA of Wine dataset')

plt.show()
</code>```

Body:
I am trying to run this Comparison of LDA and PCA 2D projection of Iris dataset example  with a WINE dataset that I download from the internet but I get the error:

d:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py:760: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().   y = column_or_1d(y, warn=True)
--------------------------------------------------------------------------- IndexError                                Traceback (most recent call last) <ipython-input-44-a42b504da984> in <module>
     14
     15 for color, i, target_name in zip(colors, [0, 1, 2], target_names):
---> 16     plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
     17                 label=target_name)
     18 plt.legend(loc='best', shadow=False, scatterpoints=1)

IndexError: too many indices for array

How can I fix it?

Code:

import matplotlib.pyplot as plt

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

import pandas as pd

df = pd.read_csv('https://gist.githubusercontent.com/tijptjik/9408623/raw/b237fa5848349a14a14e5d4107dc7897c21951f5/wine.csv')
df.to_numpy()

X  = df.iloc[:,[1,2,3,4,5,6,7,8,9,10,11,12,13]]
X.to_numpy()
y  = df.iloc[:,[0]]
y.to_numpy()
target_names = y

pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
      % str(pca.explained_variance_ratio_))

plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2

for color, i, target_name in zip(colors, [0, 1, 2], target_names):
    plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
                label=target_name)

Body:
If you look at your y vs the y in the example script, you will see that your y has multiple dimensions even if the second dim is of length 0. You need to remove this 2nd dimension which can be done via np.squeeze

y = np.squeeze(df.loc[:,['Wine']].to_numpy())

Here is the full code

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

df = pd.read_csv('https://gist.githubusercontent.com/tijptjik/9408623/raw/b237fa5848349a14a14e5d4107dc7897c21951f5/wine.csv')

X = df.loc[:, df.columns != 'Wine'].to_numpy()
y = np.squeeze(df.loc[:,['Wine']].to_numpy())
target_names = ['first', 'sceond', 'third']

pca = PCA(n_components=2)
X_r = pca.fit(X).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)

# Percentage of variance explained for each components
print('explained variance ratio (first two components): %s'
    % str(pca.explained_variance_ratio_))

plt.figure()
colors = ['navy', 'turquoise', 'darkorange']
lw = 2

for color, i, target_name in zip(colors, [1,2,3], target_names):
    plt.scatter(X_r[y == i, 0], X_r[y == i, 1], color=color, alpha=.8, lw=lw,
                label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('PCA of Wine dataset')

plt.figure()
for color, i, target_name in zip(colors, [1, 2, 3], target_names):
    plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], alpha=.8, color=color,
                label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('LDA of Wine dataset')

plt.show()


问:
Capture strings NOT enclosed by balanced parentheses in Lua
Lua patterns include %b() and the like to capture strings enclosed by paired strings (in this case, parentheses). However, what if I want to capture everything except "%b()"?

What I've tried:

str = "A time ago (hello)"
string.gsub(str, "[^%b()]", "a")
```

<p>But the result is <code>aaaaaaaaaaa(aaaaa)</code>, i.e., it replaces everything except paired parentheses. What I want to get is <code>aaaaaaaaaaa(hello)</code> instead.</p>

<h2>Edit</h2>

<p>For more context, what I want is to make the following</p>

<pre class="lang-lua prettyprint-override"><code>myfunction("A nice (house) on an (island)")
--should ignore (house) and (island)
--should work like string.gsub(str, "%w+", "bla"), for instance
--by ignoring enclosed strings
bla bla (house) bla bla (island)
</code>```

答:
Try this code:

```<code>s="A nice (house) on an (island)"
print(s:gsub("(.-)(%b())",function (a,b) return a:gsub("%w+","bla")..b end))
</code>```

This works, except that it does not handle the words after the last parentheses. The solution is to make sure that the input is uniform:

```<code>s="A nice (house) on an (island) in the Pacific" .. "()" -- here!
print(s:gsub("(.-)(%b())",function (a,b) return a:gsub("%w+","bla")..b end))
</code>```

and then remove the trailing () in the output.

Body:
Lua patterns include %b() and the like to capture strings enclosed by paired strings (in this case, parentheses). However, what if I want to capture everything except "%b()"?

What I've tried:

str = "A time ago (hello)"
string.gsub(str, "[^%b()]", "a")

But the result is aaaaaaaaaaa(aaaaa), i.e., it replaces everything except paired parentheses. What I want to get is aaaaaaaaaaa(hello) instead.

Edit

For more context, what I want is to make the following

myfunction("A nice (house) on an (island)")
--should ignore (house) and (island)
--should work like string.gsub(str, "%w+", "bla"), for instance
--by ignoring enclosed strings
bla bla (house) bla bla (island)

Body:
Try this code:

s="A nice (house) on an (island)"
print(s:gsub("(.-)(%b())",function (a,b) return a:gsub("%w+","bla")..b end))

This works, except that it does not handle the words after the last parentheses. The solution is to make sure that the input is uniform:

s="A nice (house) on an (island) in the Pacific" .. "()" -- here!
print(s:gsub("(.-)(%b())",function (a,b) return a:gsub("%w+","bla")..b end))

and then remove the trailing () in the output.


问:
Reverse Integer Catch overflow C++
Hello I am trying a simple reverse integer operation in c++. Code below:

```<code>#include <iostream>
#include <algorithm>
#include <climits>

using namespace std;

class RevInteger {

public:
    int reverse(int x)
    {
        int result = 0;
        bool isNeg = x > 0 ? false : true;
        x = abs(x);

        while (x != 0)
        {
            result = result * 10 + x % 10;
            x = x / 10;
        }

        if (isNeg)
            result *= -1;

        if (result > INT_MAX || result < INT_MIN)
            return 0;
        else
            return (int)result;
    }
};
</code>```

When I give it an input as 1534236469; I want it to return me 0, instead it returns me some junk values. What is wrong in my program.  Also, I am trying to use the climits lib for the purpose, is there a simpler way of doing the same?

答:
```<code>int reverse(int x) {
        int pop = 0;
        int ans = 0;
        while(x) {
            // pop
            pop = x % 10;
            x /= 10;

            // check overflow
            if(ans > INT_MAX/10 || ans == INT_MAX/10 && pop > 7) return 0;
            if(ans < INT_MIN/10 || ans == INT_MIN/10 && pop < -8) return 0;

            // push
            ans = ans * 10 + pop;

        }
        return ans;
    }
</code>```

Title: Reverse Integer Catch overflow C++

Body:
Hello I am trying a simple reverse integer operation in c++. Code below:

#include <iostream>
#include <algorithm>
#include <climits>

using namespace std;

class RevInteger {

public:
    int reverse(int x)
    {
        int result = 0;
        bool isNeg = x > 0 ? false : true;
        x = abs(x);

        while (x != 0)
        {
            result = result * 10 + x % 10;
            x = x / 10;
        }

        if (isNeg)
            result *= -1;

        if (result > INT_MAX || result < INT_MIN)
            return 0;
        else
            return (int)result;
    }
};

When I give it an input as 1534236469; I want it to return me 0, instead it returns me some junk values. What is wrong in my program.  Also, I am trying to use the climits lib for the purpose, is there a simpler way of doing the same?