问:
Why am I getting "PG::NotNullViolation null value in column "id" violates not-null constraint" whenever I login in my rails app?
After dumping, downloading and pg_restoring a DB from Heroku, any time I try to login in my rails application I get the above error.

It somehow seems that the user id is seen as nil (even though I can see an id value in the DB).

I also read that it may be due to the id being a simple int instead of a serial, however, as you can see in my schema:

```<code>create_table "users", id: :serial, force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string "current_sign_in_ip"
    t.string "last_sign_in_ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "name"
    t.string "last_name"
    t.string "provider"
    t.string "uid"
    t.boolean "admin", default: false, null: false
    t.boolean "affiliate_approved", default: false, null: false
    t.integer "cart_id"
    t.float "rev_share"
    t.boolean "notice", default: false, null: false
    t.string "iban"
    t.string "piva"
    t.string "invitation_token"
    t.datetime "invitation_created_at"
    t.datetime "invitation_sent_at"
    t.datetime "invitation_accepted_at"
    t.integer "invitation_limit"
    t.string "invited_by_type"
    t.integer "invited_by_id"
    t.integer "invitations_count", default: 0
    t.string "username"
    t.string "slug"
    t.integer "enrolls_count", default: 0
    t.integer "partner_id"
    t.string "country"
    t.integer "referrer"
    t.boolean "gdpr_marketing"
    t.boolean "privacy_policy"
    t.boolean "subscription", default: false
    t.date "account_created_at"
    t.boolean "profilazione"
    t.boolean "terms_and_conditions"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["invitation_token"], name: "index_users_on_invitation_token", unique: true
    t.index ["invitations_count"], name: "index_users_on_invitations_count"
    t.index ["invited_by_id"], name: "index_users_on_invited_by_id"
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["username"], name: "index_users_on_username", unique: true
  end
</code>```

And it seems that the id is used already as serial.

Do you have any idea of what may be going wrong? This application is live in production with a couple of thousands of users who aren't being impacted by this issue, which makes me think there's something wrong with my local PG setup.

Edit - full error message

```<code>PG::NotNullViolation at /auth/google_oauth2/callback
ERROR:  null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, 9367, 127.0.0.1, 2018-09-17 09:51:59.463125, 2018-09-17 09:51:59.463125).
</code>```

Edit - more findings

In user.rb (the model file) there's an after_update hook where the following is executed:

```<code>def change_log
  UserChange.create(ip_request: current_sign_in_ip, user: self)
end
</code>```

This is so that we can track everything a user changes along with their IP (GDPR reasons).

After commenting that out, it all works alright and my user gets logged in as planned

答:
I just had the same error after pulling a copy of the DB from Heroku:

PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint DETAIL: Failing row contains ...etc

It was happening every time I tried to create a new record.  I'm guessing that when you log in, your app is creating a new record somewhere (possibly some login tracking/logging you are doing?) that is triggering the error.  If you can't access the app through a web browser, you could try opening up the Rails console and see what happens if you try to create a new record directly.  If you still get the error, the issue is not actually with your login but with your DB.

The issue for me was that I was using a different version of Postgres on my dev machine to the version on Heroku that created the dump file.  After switching to the matching version of Postgres an re-pulling the DB, everything is working as expected again.

If you're using Postgres on Mac, when you add a new Postgres server, you can choose which version of Postgres it should use.  You want to make your development and production environments as similar as possible so you definitely want to make sure that your DB versions match.

Body:
After dumping, downloading and pg_restoring a DB from Heroku, any time I try to login in my rails application I get the above error.

It somehow seems that the user id is seen as nil (even though I can see an id value in the DB).

I also read that it may be due to the id being a simple int instead of a serial, however, as you can see in my schema:

create_table "users", id: :serial, force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string "current_sign_in_ip"
    t.string "last_sign_in_ip"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "name"
    t.string "last_name"
    t.string "provider"
    t.string "uid"
    t.boolean "admin", default: false, null: false
    t.boolean "affiliate_approved", default: false, null: false
    t.integer "cart_id"
    t.float "rev_share"
    t.boolean "notice", default: false, null: false
    t.string "iban"
    t.string "piva"
    t.string "invitation_token"
    t.datetime "invitation_created_at"
    t.datetime "invitation_sent_at"
    t.datetime "invitation_accepted_at"
    t.integer "invitation_limit"
    t.string "invited_by_type"
    t.integer "invited_by_id"
    t.integer "invitations_count", default: 0
    t.string "username"
    t.string "slug"
    t.integer "enrolls_count", default: 0
    t.integer "partner_id"
    t.string "country"
    t.integer "referrer"
    t.boolean "gdpr_marketing"
    t.boolean "privacy_policy"
    t.boolean "subscription", default: false
    t.date "account_created_at"
    t.boolean "profilazione"
    t.boolean "terms_and_conditions"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["invitation_token"], name: "index_users_on_invitation_token", unique: true
    t.index ["invitations_count"], name: "index_users_on_invitations_count"
    t.index ["invited_by_id"], name: "index_users_on_invited_by_id"
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["username"], name: "index_users_on_username", unique: true
  end

And it seems that the id is used already as serial.

Do you have any idea of what may be going wrong? This application is live in production with a couple of thousands of users who aren't being impacted by this issue, which makes me think there's something wrong with my local PG setup.

Edit - full error message

PG::NotNullViolation at /auth/google_oauth2/callback
ERROR:  null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, 9367, 127.0.0.1, 2018-09-17 09:51:59.463125, 2018-09-17 09:51:59.463125).

Edit - more findings

In user.rb (the model file) there's an after_update hook where the following is executed:

def change_log
  UserChange.create(ip_request: current_sign_in_ip, user: self)
end

This is so that we can track everything a user changes along with their IP (GDPR reasons).

After commenting that out, it all works alright and my user gets logged in as planned


来源: stackexchange

问:
What does #define macro() <...> do?
What does this line do?
I doubt its a template or expression. (doing those divies and naming a member hpp is a bad idea)

```<code># define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>
</code>```

Full file

```<code># /* **************************************************************************
#  *                                                                          *
#  *     (C) Copyright Paul Mensonides 2005.                                  *
#  *     Distributed under the Boost Software License, Version 1.0. (See      *
#  *     accompanying file LICENSE_1_0.txt or copy at                         *
#  *     http://www.boost.org/LICENSE_1_0.txt)                                *
#  *                                                                          *
#  ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
# define BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
#
# include <boost/preprocessor/slot/detail/def.hpp>
#
# /* BOOST_PP_COUNTER */
#
# define BOOST_PP_COUNTER 0
#
# /* BOOST_PP_UPDATE_COUNTER */
#
# define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>
#
# endif
</code>```

答:
Apparently it does some auto-incrementing magic.

Here's the documentation.

I have no idea how it works. What I do know is that the magic is in counter.hpp itself; that the definition you posted has brackets in it is just so that you can write the vaguely user-friendly:

```<code>#include BOOST_PP_UPDATE_COUNTER()
</code>```

to invoke said magic.

ContentLicense: CC BY-SA 3.0

Title: What does #define macro() <...> do?

Body:
What does this line do?
I doubt its a template or expression. (doing those divies and naming a member hpp is a bad idea)

# define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>

Full file

# /* **************************************************************************
#  *                                                                          *
#  *     (C) Copyright Paul Mensonides 2005.                                  *
#  *     Distributed under the Boost Software License, Version 1.0. (See      *
#  *     accompanying file LICENSE_1_0.txt or copy at                         *
#  *     http://www.boost.org/LICENSE_1_0.txt)                                *
#  *                                                                          *
#  ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
# define BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
#
# include <boost/preprocessor/slot/detail/def.hpp>
#
# /* BOOST_PP_COUNTER */
#
# define BOOST_PP_COUNTER 0
#
# /* BOOST_PP_UPDATE_COUNTER */
#
# define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>
#
# endif

Body:
Apparently it does some auto-incrementing magic.

Here's the documentation.

I have no idea how it works. What I do know is that the magic is in counter.hpp itself; that the definition you posted has brackets in it is just so that you can write the vaguely user-friendly:

#include BOOST_PP_UPDATE_COUNTER()

to invoke said magic.


问:
How to use setTimeout to make a list item wait for some time to restore its original color after a click?
I have list items, clicking a list item should turn it red, i want every clicked item to wait for 3000ms to restore its black color again, this is my code

my trial is to use setTimeout in useEffect and setting all red fields to false but this didn't work, especially i need to make every red item to wait 3000ms from turning red to turn black again

The first item to click turn to black after 3000ms correctly, but after that items going black faster!!

```<code>  const App = () => {
        const items = [
            {
                name: 'mark',
                id: 1,
                red: false
            },
            {
                name: 'peter',
                id: 2,
                red: false
            },
            {
                name: 'john',
                id: 3,
                red: false
            }
        ]

        const [names, setNames] = useState(items);

        const turnItemRed= (id) => {
            setNames(
                names.map(i =>  i.id === id ? {...i, red: true} : i))
        }

     // this doesn't work
     useEffect(() => {
         setTimeout(() => {
             setNames( prev => prev.map( i => ({...i, red: false})))
         }, 3000)
     })

        return (
            <div class="items-cont">
                <ul class="items">
                    {
                        names.map(i => {
                            return (
                                <Item
                                    item={i}
                                    turnItemRed={turnItemRed}
                                />
                            )
                        })
                    }
                </ul>
            </div>
        )
    }

    const Item = ({ item, ...props }) => {
        const { turnItemRed } = props;
        return (
            <li
                className={`${item.red ? 'red' : ''}`}
                onClick={() => {
                    turnItemRed(item.id)
                }}
            >
                {item.name}
            </li>
        )
    }
    ReactDOM.render(<App />, document.getElementById('root'))
</code>```

CSS:

```<code>.red {
     color: red
  }

</code>```

答:
First of all, your useEffect is running every 3 seconds, which means your component is re-rendering every 3 seconds with no UI actual updates.

useEffect(() => {
  setTimeout(() => {
    setNames( prev => prev.map( i => ({...i, red: false})))
  }, 3000)
})
```

<p>You need to change your <code>useEffect</code> to run only when <code>names</code> changes. Also make sure it runs only if some name has <code>red</code> property set to `true.</p>

<pre class="lang-js prettyprint-override"><code>useEffect(() => {
  if (names.some(item => item.red)) {
    setTimeout(() => {
      setNames(prev => prev.map(i => ({ ...i, red: false })));
    }, 3000);
  }
}, [names]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have list items, clicking a list item should turn it red, i want every clicked item to wait for 3000ms to restore its black color again, this is my code

my trial is to use setTimeout in useEffect and setting all red fields to false but this didn't work, especially i need to make every red item to wait 3000ms from turning red to turn black again

The first item to click turn to black after 3000ms correctly, but after that items going black faster!!

  const App = () => {
        const items = [
            {
                name: 'mark',
                id: 1,
                red: false
            },
            {
                name: 'peter',
                id: 2,
                red: false
            },
            {
                name: 'john',
                id: 3,
                red: false
            }
        ]

        const [names, setNames] = useState(items);

        const turnItemRed= (id) => {
            setNames(
                names.map(i =>  i.id === id ? {...i, red: true} : i))
        }

     // this doesn't work
     useEffect(() => {
         setTimeout(() => {
             setNames( prev => prev.map( i => ({...i, red: false})))
         }, 3000)
     })

        return (

                    {
                        names.map(i => {
                            return (
                                <Item
                                    item={i}
                                    turnItemRed={turnItemRed}
                                />
                            )
                        })
                    }

        )
    }

    const Item = ({ item, ...props }) => {
        const { turnItemRed } = props;
        return (
            <li
                className={`${item.red ? 'red' : ''}`}
                onClick={() => {
                    turnItemRed(item.id)
                }}
            >
                {item.name}

        )
    }
    ReactDOM.render(<App />, document.getElementById('root'))

CSS:

.red {
     color: red
  }

Body:
First of all, your useEffect is running every 3 seconds, which means your component is re-rendering every 3 seconds with no UI actual updates.

useEffect(() => {
  setTimeout(() => {
    setNames( prev => prev.map( i => ({...i, red: false})))
  }, 3000)
})

You need to change your useEffect to run only when names changes. Also make sure it runs only if some name has red property set to `true.

useEffect(() => {
  if (names.some(item => item.red)) {
    setTimeout(() => {
      setNames(prev => prev.map(i => ({ ...i, red: false })));
    }, 3000);
  }
}, [names]);


问:
html table focus-highlight
I have this table and script in my html, i Just want that if the user click the " Select " button it will change the color of what the user selected.

```<code><table id="myTable" class="my_table">
    <tr>
        <th>Control #</th>
        <th>Name</th>
        <th>Education Level</th>
        <th>Section</th>
        <th>Course/Track</th>
        <th>Strand</th>
        <th>Payment Type</th>
        <th>Date</th>
        <th>Operation</th>
    </tr>
    {% for article in object_list %}
    <tr>
        <td>{{ article.id }}</td>
        <td>{{ article.Student_Users }}</td>
        <td>{{article.Education_Levels}}</td>
        <td>{{article.Section}}</td>
        <td>{{article.Courses}}</td>
        <td>{{article.strands}}</td>
        <td>{{article.Payment_Type}}</td>
        <td>{{article.Date_Time}}</td>
        <td><a href="{% url 'selectrecord' %}?StudentID={{ article.id }}"><button>Select</button></a><a href="#"></a></td>
    </tr>
    {% empty %}
    <tr>
        <td>No Data yet.</td>
    </tr>
    {% endfor %}
</table>
</code>```

```<code><script>
.my_table tr:focus {
  background-color: red;
  outline: 0; /*remove outline*/
}
</script>
</code>```

答:
Just add a class on TR on click of select button and change the CSS accordingly

$(document).ready(function(){
  $('.select').click(function(){
    $('tr').removeClass('selected');
    $(this).closest('tr').addClass('selected');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#myTable th, #myTable td {border-bottom: 1px solid; white-space: pre-wrap;}
#myTable tr.selected td {background: #ddd;}</code>```

        Control #
        Name
        Education Level
        Section

    {% for article in object_list %}

        {{ article.id }}
        {{ article.Student_Users }}
        {{article.Education_Levels}}
        <button class="select">Select</button>

        {{ article.id }}
        {{ article.Student_Users }}
        {{article.Education_Levels}}
        <button class="select">Select</button>

        {{ article.id }}
        {{ article.Student_Users }}
        {{article.Education_Levels}}
        <button class="select">Select</button>

    {% endfor %}

```

Title: html table focus-highlight

Body:
I have this table and script in my html, i Just want that if the user click the " Select " button it will change the color of what the user selected.

        Control #
        Name
        Education Level
        Section
        Course/Track
        Strand
        Payment Type
        Date
        Operation

    {% for article in object_list %}

        {{ article.id }}
        {{ article.Student_Users }}
        {{article.Education_Levels}}
        {{article.Section}}
        {{article.Courses}}
        {{article.strands}}
        {{article.Payment_Type}}
        {{article.Date_Time}}
        <button>Select</button>

    {% empty %}

        No Data yet.

    {% endfor %}

Body:
Just add a class on TR on click of select button and change the CSS accordingly

$(document).ready(function(){
  $('.select').click(function(){
    $('tr').removeClass('selected');
    $(this).closest('tr').addClass('selected');
  });
});

#myTable th, #myTable td {border-bottom: 1px solid; white-space: pre-wrap;}
#myTable tr.selected td {background: #ddd;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="my_table">
    <tr>
        <th>Control #</th>
        <th>Name</th>
        <th>Education Level</th>
        <th>Section</th>

    </tr>
    {% for article in object_list %}
    <tr>
        <td>{{ article.id }}</td>
        <td>{{ article.Student_Users }}</td>
        <td>{{article.Education_Levels}}</td>
        <td><a href="#javascript:void(0)"><button class="select">Select</button></a><a href="#"></a></td>
    </tr>
<tr>
        <td>{{ article.id }}</td>
        <td>{{ article.Student_Users }}</td>
        <td>{{article.Education_Levels}}</td>
        <td><a href="#javascript:void(0)"><button class="select">Select</button></a><a href="#"></a></td>
    </tr>
<tr>
        <td>{{ article.id }}</td>
        <td>{{ article.Student_Users }}</td>
        <td>{{article.Education_Levels}}</td>
        <td><a href="#javascript:void(0)"><button class="select">Select</button></a><a href="#"></a></td>
    </tr>
    {% endfor %}
</table>


问:
How can I access a private field from a struct in a submodule?
I want to split my rust module in separate files. So I used a submodule. The problem is I cant access private fields from a struct defined in a submodule. Here is an example:

```<code>// mod1.rs
mod point;

struct Point1 {
    x: i32,
    y: i32,
}

impl Point1 {
    pub fn new(x: i32, y: i32) -> Point1 {
        Point1 { x: x, y: y }
    }
}

pub fn run() {
    let a = Point1::new(1, 2);
    let b = point::Point2::new(3, 4);

    println!("{}, {}", a.x, a.y); // 1, 2
    println!("{}, {}", b.x, b.y); // error
}

// point.rs
pub struct Point2 {
    x: i32,
    y: i32,
}

impl Point2 {
    pub fn new(x: i32, y: i32) -> Point2 {
        Point2 { x: x, y: y }
    }
}
</code>```

How can I split the code in separate files and still access the private members of a struct?

答:
You can use pub (super) to make something only public to its parent module.

```<code>pub struct Point2 {
    pub (super) x: i32,
    pub (super) y: i32,
}
</code>```

Have a look at the rust docs on Visibility and Privacy.

Body:
I want to split my rust module in separate files. So I used a submodule. The problem is I cant access private fields from a struct defined in a submodule. Here is an example:

// mod1.rs
mod point;

struct Point1 {
    x: i32,
    y: i32,
}

impl Point1 {
    pub fn new(x: i32, y: i32) -> Point1 {
        Point1 { x: x, y: y }
    }
}

pub fn run() {
    let a = Point1::new(1, 2);
    let b = point::Point2::new(3, 4);

    println!("{}, {}", a.x, a.y); // 1, 2
    println!("{}, {}", b.x, b.y); // error
}

// point.rs
pub struct Point2 {
    x: i32,
    y: i32,
}

impl Point2 {
    pub fn new(x: i32, y: i32) -> Point2 {
        Point2 { x: x, y: y }
    }
}

How can I split the code in separate files and still access the private members of a struct?

Body:
You can use pub (super) to make something only public to its parent module.

pub struct Point2 {
    pub (super) x: i32,
    pub (super) y: i32,
}

Have a look at the rust docs on Visibility and Privacy.


问:
Invalid Data After Declaration - Kivy
I'm not sure where my error is.  I declare two labels in my kv file.  The first one works fine, but the second catches an error "Invalid data after declaration."  Here's the code in my kv file:

```<code><LoadingScreen>:
    elsaLabel: label
    Label
        id: label
        text: "ELSA"
        font_size: 80
        color: 0.28, 0.69, 0.77, 1
        opacity: 0

    startLabel: label
    Label
        id: start
        text: "Welcome"
        font_size: 25
        color: 0.28, 0.69, 0.77, 1
        opacity: 0
        pos: 0, -150
</code>```

The error occurs on the line "startLabel: label".  Any help would be appreciated.

答: According to the documentation, the properties (elsaLabel and startLabel) should appear before the children Widgets. Try moving startLabel: label to before the first Label rule.

Title: Invalid Data After Declaration - Kivy

Body:
I'm not sure where my error is.  I declare two labels in my kv file.  The first one works fine, but the second catches an error "Invalid data after declaration."  Here's the code in my kv file:

<LoadingScreen>:
    elsaLabel: label
    Label
        id: label
        text: "ELSA"
        font_size: 80
        color: 0.28, 0.69, 0.77, 1
        opacity: 0

    startLabel: label
    Label
        id: start
        text: "Welcome"
        font_size: 25
        color: 0.28, 0.69, 0.77, 1
        opacity: 0
        pos: 0, -150

The error occurs on the line "startLabel: label".  Any help would be appreciated.


问:
Adding MS Graph API Oauth in Azure Bot Services using REST API
I am using REST API for Azure Bot Services and GRAPH API for creating MS Teams Bot.

I have been using two different oauths for my application since I require my bot to get details from GRAPH API.

https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token  - for bot services
https://login.microsoftonline.com/common/oauth2/v2.0/token - for graph api

Is there a way to combine them, and use single ouath for both the purpsoses? I went through the documentaion and there is a way where bot can ask for graph api authentication from user.

I saw many examples for SDKs but I am not able to figure out how to do this in REST API.

I have followed this documnetation uptil here.

Can anyone please let me know if I am doing it right and further steps to be taken to add MS Graph API Oauth in Bot itself?

答:
No. There is no way to combine them. We can only use a one token for one purpose.

The document you provided is to tell that we can use a bot to call Microsoft Graph. See reference here: Add authentication to a bot.

Creating the bot and use the bot to call Microsoft Graph should be should be two separate processes.

After creating the bot, you need to configure the AAD authentication to it, then you could use it to call Microsoft Graph.

See the Bot Graph sample.


答:
Because your code basically set all item back to original color at once.
Try the following code:
Note: This is simple way but the color when you can see it red then turn back to original color is not guarantee 3000 ms, because it take abit time to re-render component to show red

import React from "react";
import "./styles.css";

const App = () => {
  const items = [
      {
          name: 'mark',
          id: 1,
          red: false
      },
      {
          name: 'peter',
          id: 2,
          red: false
      },
      {
          name: 'john',
          id: 3,
          red: false
      }
  ]

  const [names, setNames] = useState(items);

  const turnItemRed= (id) => {
      setNames(
          names.map(i =>  i.id === id ? {...i, red: true} : i))
      // move set timout here
      setTimeout(() => {
         setNames( prev => prev.map( i => i.id === id ? {...i, red: false} : i))
       }, 3000)
  }

  return (

              {
                  names.map(i => {
                      return (
                          <Item
                              item={i}
                              turnItemRed={turnItemRed}
                          />
                      )
                  })
              }

  )
}

const Item = ({ item, ...props }) => {
  const { turnItemRed } = props;
  return (
      <li
          className={`${item.red ? 'red' : ''}`}
          onClick={() => {
              turnItemRed(item.id)
          }}
      >
          {item.name}

  )
}
ReactDOM.render(<App />, document.getElementById('root'))```

Title: How to use setTimeout to make a list item wait for some time to restore its original color after a click?

Body:
Because your code basically set all item back to original color at once.
Try the following code:
Note: This is simple way but the color when you can see it red then turn back to original color is not guarantee 3000 ms, because it take abit time to re-render component to show red

import React from "react";
import "./styles.css";

const App = () => {
  const items = [
      {
          name: 'mark',
          id: 1,
          red: false
      },
      {
          name: 'peter',
          id: 2,
          red: false
      },
      {
          name: 'john',
          id: 3,
          red: false
      }
  ]

  const [names, setNames] = useState(items);

  const turnItemRed= (id) => {
      setNames(
          names.map(i =>  i.id === id ? {...i, red: true} : i))
      // move set timout here
      setTimeout(() => {
         setNames( prev => prev.map( i => i.id === id ? {...i, red: false} : i))
       }, 3000)
  }

  return (
      <div class="items-cont">
          <ul class="items">
              {
                  names.map(i => {
                      return (
                          <Item
                              item={i}
                              turnItemRed={turnItemRed}
                          />
                      )
                  })
              }
          </ul>
      </div>
  )
}

const Item = ({ item, ...props }) => {
  const { turnItemRed } = props;
  return (
      <li
          className={`${item.red ? 'red' : ''}`}
          onClick={() => {
              turnItemRed(item.id)
          }}
      >
          {item.name}
      </li>
  )
}
ReactDOM.render(<App />, document.getElementById('root'))


问:
Javascript variable can't be overwritten after the first declaration
I have a function that will refresh the page based on the number chosen:

prodName="doesn't matter, not directly $.ajax related"

function searchProduct() {
  var prodName = $("#admin-search-product").val().trim();
  var pagenumb = 1;
  $(".page-item").click(function() {
    pagenumb = $(this).children('.page-link').attr('value');
  });
  alert(pagenumb);
  if (prodName == "") {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 0,
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  } else {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 1,
        searchName: prodName,
        pagenumb: pagenumb
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="admin-search-product">

<div class="page-item">
<input class="page-link">
</div>

<button onclick="searchProduct()">clickme</button></code>```

Everything works well, except the problem is that the pagenumb variable stays on "1" even though the code "pagenumb = $(this).children('.page-link').attr('value');" can retrieve the value of the page clicked, tested with alert() function and it can return the value of "2" if put within the click function.

However if I test the alert() function outside the click function, it shows that the pagenumb variable stayed the same. I don't know why it doesnt want to change the received value even though I'm able to receive it.

答:
You should bind the event handler once when the page is ready, not every time you searchProducts().

You want the change event, not click.  pagenumb should be updated when the input's value changes.  Click will only try to update the value when you focus the input box, which is not what you want.

prodName = "doesn't matter, not directly $.ajax related"

var pagenumb = 1;

// you should bind this event handler _once_ when the _page is ready_
// you want the change event, not click. update pagenumb whenever value _changes_
$(".page-item").change(function() {
  // coerce to number using + operator
  pagenumb = +$(this).children('.page-link').val();
});

function searchProduct() {
  var prodName = $("#admin-search-product").val().trim();

  alert(pagenumb);
  if (prodName == "") {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 0,
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  } else {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 1,
        searchName: prodName,
        pagenumb: pagenumb
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="admin-search-product">

<div class="page-item">
  <input class="page-link">
</div>

<button onclick="searchProduct()">clickme</button></code>```

Body:
I have a function that will refresh the page based on the number chosen:

prodName="doesn't matter, not directly $.ajax related"

function searchProduct() {
  var prodName = $("#admin-search-product").val().trim();
  var pagenumb = 1;
  $(".page-item").click(function() {
    pagenumb = $(this).children('.page-link').attr('value');
  });
  alert(pagenumb);
  if (prodName == "") {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 0,
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  } else {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 1,
        searchName: prodName,
        pagenumb: pagenumb
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  }
}

<input id="admin-search-product">

<input class="page-link">

<button onclick="searchProduct()">clickme</button>

Everything works well, except the problem is that the pagenumb variable stays on "1" even though the code "pagenumb = $(this).children('.page-link').attr('value');" can retrieve the value of the page clicked, tested with alert() function and it can return the value of "2" if put within the click function.

However if I test the alert() function outside the click function, it shows that the pagenumb variable stayed the same. I don't know why it doesnt want to change the received value even though I'm able to receive it.

Body:
You should bind the event handler once when the page is ready, not every time you searchProducts().

You want the change event, not click.  pagenumb should be updated when the input's value changes.  Click will only try to update the value when you focus the input box, which is not what you want.

prodName = "doesn't matter, not directly $.ajax related"

var pagenumb = 1;

// you should bind this event handler _once_ when the _page is ready_
// you want the change event, not click. update pagenumb whenever value _changes_
$(".page-item").change(function() {
  // coerce to number using + operator
  pagenumb = +$(this).children('.page-link').val();
});

function searchProduct() {
  var prodName = $("#admin-search-product").val().trim();

  alert(pagenumb);
  if (prodName == "") {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 0,
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  } else {
    $.ajax({
      type: "POST",
      url: "admin_search_product.php",
      data: {
        search_prod: 1,
        searchName: prodName,
        pagenumb: pagenumb
      },
      success: function(respond) {
        $("#admin_content").html(respond).show();
        $("#admin-search-product").focus().val('').val(prodName);
      }
    });
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="admin-search-product">

<div class="page-item">
  <input class="page-link">
</div>

<button onclick="searchProduct()">clickme</button>


答:
You can do this:

```<code>import numpy as np

matching_column_indices = np.empty(len(df))
matching_column_indices[0] = np.nan

for row_index in range(1, len(df)):
    row_matching_column_indices = df.loc[row_index] == df.loc["key"]
    matching_column_indices[row_index] = row_matching_column_indices.idxmax()

df["trace"] = matching_column_indices
</code>```

row_matching_column_indices.idxmax() returns the column index of the first True value observed, corresponding to the first match in the columns between the row at row_index and "key".

Resulting df:

```<code>     0  1  2  3  4  5  6  7  8  9  trace
key  2  3  4  3  6  2  3  4  3  6    NaN
1    7  6  3  4  5  4  3  2  1  2    6.0
2    5  4  3  2  3  6  7  6  7  6    9.0
3    4  5  4  3  6  7  6  3  4  5    2.0
4    2  3  4  5  4  3  6  7  6  3    0.0
5    7  6  3  4  3  2  1  2  3  6    5.0
</code>```

Title: Find first dupe across axis based on key row

Body:
This is my dataframe

df = pd.DataFrame({0: {'key': 2, 1: 7, 2: 5, 3: 4, 4: 2, 5: 7}, 1: {'key': 3, 1: 6, 2: 4, 3: 5, 4: 3, 5: 6}, 2: {'key': 4, 1: 3, 2: 3, 3: 4, 4: 4, 5: 3}, 3: {'key': 3, 1: 4, 2: 2, 3: 3, 4: 5, 5: 4}, 4: {'key': 6, 1: 5, 2: 3, 3: 6, 4: 4, 5: 3}, 5: {'key': 2, 1: 4, 2: 6, 3: 7, 4: 3, 5: 2}, 6: {'key': 3, 1: 3, 2: 7, 3: 6, 4: 6, 5: 1}, 7: {'key': 4, 1: 2, 2: 6, 3: 3, 4: 7, 5: 2}, 8: {'key': 3, 1: 1, 2: 7, 3: 4, 4: 6, 5: 3}, 9: {'key': 6, 1: 2, 2: 6, 3: 5, 4: 3, 5: 6}})

     0  1  2  3  4  5  6  7  8  9
key  2  3  4  3  6  2  3  4  3  6
1    7  6  3  4  5  4  3  2  1  2
2    5  4  3  2  3  6  7  6  7  6
3    4  5  4  3  6  7  6  3  4  5
4    2  3  4  5  4  3  6  7  6  3
5    7  6  3  4  3  2  1  2  3  6

I need to find the columns where the index in question matches the key row going from left to right.

For example at index 1, column 6 has the same value as the key row, index 2 matches the key row at column 9 and no value before. The same logic can be applied to index 3, 4 and 5.

I only need the first instance where the index matches the key value, all values after don't matter.

Expected output

      0   1   2   3   4   5   6   7   8   9   trace
key   2   3   4   3   6   2   3   4   3   6   NaN
1     7   6   3   4   5   4   3   2   1   2   6
2     5   4   3   2   3   6   7   6   7   6   9
3     4   5   4   3   6   7   6   3   4   5   2
4     2   3   4   5   4   3   6   7   6   3   0
5     7   6   3   4   3   2   1   2   3   6   5

I have tried many variations of duplicates but nothing seems to work.

Body:
You can do this:

import numpy as np

matching_column_indices = np.empty(len(df))
matching_column_indices[0] = np.nan

for row_index in range(1, len(df)):
    row_matching_column_indices = df.loc[row_index] == df.loc["key"]
    matching_column_indices[row_index] = row_matching_column_indices.idxmax()

df["trace"] = matching_column_indices

row_matching_column_indices.idxmax() returns the column index of the first True value observed, corresponding to the first match in the columns between the row at row_index and "key".

Resulting df:

     0  1  2  3  4  5  6  7  8  9  trace
key  2  3  4  3  6  2  3  4  3  6    NaN
1    7  6  3  4  5  4  3  2  1  2    6.0
2    5  4  3  2  3  6  7  6  7  6    9.0
3    4  5  4  3  6  7  6  3  4  5    2.0
4    2  3  4  5  4  3  6  7  6  3    0.0
5    7  6  3  4  3  2  1  2  3  6    5.0


问:
Understanding clickhouse partitions
I see that clickhouse created multiple directories for each partition key(in each node).
Documentation says the directory name format is : partition ID_minimum block number_maximum block number_level.
Any idea what is level here?
347 distinct partition keys on one node(for one table) created 1358 directories.   (custom partitioning)

The documentation recommends not to have more than 1000 partitions. Should we just keep in mind the number of partitions keys or the number of directories also?

Also, Is there a configuration on how to control this number of directories?

答:
Adding to this discussion, you can check parts and partition in the following ways :

For active partition :

```<code>select count(distinct partition)  from system.parts  where the table in ('table_name') and active
</code>```

For Active parts :

```<code>select count() from system.parts  where   table in ('table_name') and active
</code>```

Inactive parts will be removed soon in less than 10 minutes.

Furthermore, you can also read more here about parts, partition and how merging happens.

To view table parts and partition together :

```<code>SELECT
    partition,
    name,
    active
FROM system.parts
WHERE table = 'table_name'
</code>```

Title: Understanding clickhouse partitions

Body:
Adding to this discussion, you can check parts and partition in the following ways :

For active partition :

select count(distinct partition)  from system.parts  where the table in ('table_name') and active

For Active parts :

select count() from system.parts  where   table in ('table_name') and active

Inactive parts will be removed soon in less than 10 minutes.

Furthermore, you can also read more here about parts, partition and how merging happens.

To view table parts and partition together :

SELECT
    partition,
    name,
    active
FROM system.parts
WHERE table = 'table_name'


问:
bash copy the first file form source folder to destination folder
I am using mac os. I am in a situation that I need to copy the only first file private key which ends with _sk to another directory. Please any suggestion would help me.

答:
You could loop over the files ending with _sk and break the loop after copying the first file. If that's really the "first file" you wanted to copy is another question.

```<code>for i in /path/to/source/*_sk; do cp "$i" /path/to/destination/; break; done
</code>```

Body:
You could loop over the files ending with _sk and break the loop after copying the first file. If that's really the "first file" you wanted to copy is another question.

for i in /path/to/source/*_sk; do cp "$i" /path/to/destination/; break; done


问:
UI Selenium tests on Azure Devops 2019
What is the correct way to run automated UI tests by a self-hosted agent?
I tried to add a tests step in the release pipeline but it's not working because the agent cannot find  the DLLs with tests (they are in a few separate projects)

```<code>##[warning]No test assemblies found matching the pattern: **\Test.UI.dll,!**\*TestAdapter.dll,!**\obj\**.
</code>```

Currently, the release pipeline is simple: one artifact from the build pipeline and one stage with the following steps:

```<code>1. IIS Web App Deploy
2. IIS Web App Manage
3. VsTest: tests are selected using Test assemblies option
</code>```

答:
No test assemblies found matching the pattern.

It seems that the .dll files don't exist in the artifact or under the path of the release agent. You may need to share more information about the Pipeline. (e.g. build agent, pipeline definition and vstest task definition)

Before this, you can refer to the following steps for troubleshooting.

First of all, you need to make sure that the .dll files exist in the build artifacts.

You could check this in Build Summary -> Artifacts. You could download it and check the files in the artifact.

If the files don't exist, you could add a Copy files task before the Publish Artifacts task.

For example:

```<code>- task: CopyFiles@2
  displayName: 'Copy Files to: $(build.artifactstagingdirectory)'
  inputs:
    SourceFolder: '$(agent.builddirectory)'
    TargetFolder: '$(build.artifactstagingdirectory)'
  enabled: false
</code>```

Then the "VsTest" task will find the files in $(System.DefaultWorkingDirectory) by default(No customization). In release pipeline, the path is equals to C:\agent\_work\rx\a (e.g. C:\agent\_work\r1\a)

Since you are using the self-hosted agent , you could directly check the files in the target path on your local machine.

If you couldn't find the target files, you may need to modify the search folder or Test files path.

You also could check the file path in the Release Pipeline log -> Download Artifacts Step.

Title: UI Selenium tests on Azure Devops 2019

Body:
What is the correct way to run automated UI tests by a self-hosted agent?
I tried to add a tests step in the release pipeline but it's not working because the agent cannot find  the DLLs with tests (they are in a few separate projects)

##[warning]No test assemblies found matching the pattern: **\Test.UI.dll,!**\*TestAdapter.dll,!**\obj\**.

Currently, the release pipeline is simple: one artifact from the build pipeline and one stage with the following steps:

1. IIS Web App Deploy
2. IIS Web App Manage
3. VsTest: tests are selected using Test assemblies option

Body:
No test assemblies found matching the pattern.

It seems that the .dll files don't exist in the artifact or under the path of the release agent. You may need to share more information about the Pipeline. (e.g. build agent, pipeline definition and vstest task definition)

Before this, you can refer to the following steps for troubleshooting.

First of all, you need to make sure that the .dll files exist in the build artifacts.

You could check this in Build Summary -> Artifacts. You could download it and check the files in the artifact.

If the files don't exist, you could add a Copy files task before the Publish Artifacts task.

For example:

- task: CopyFiles@2
  displayName: 'Copy Files to: $(build.artifactstagingdirectory)'
  inputs:
    SourceFolder: '$(agent.builddirectory)'
    TargetFolder: '$(build.artifactstagingdirectory)'
  enabled: false

Then the "VsTest" task will find the files in $(System.DefaultWorkingDirectory) by default(No customization). In release pipeline, the path is equals to C:\agent\_work\rx\a (e.g. C:\agent\_work\r1\a)

Since you are using the self-hosted agent , you could directly check the files in the target path on your local machine.

If you couldn't find the target files, you may need to modify the search folder or Test files path.

You also could check the file path in the Release Pipeline log -> Download Artifacts Step.


问:
Update based on same column
I have a table like this:

```<code>ID | Flag
-----------
 1 | True
 1 | True
 1 | NULL
 1 | True
 1 | NULL
 2 | False
 2 | False
 2 | False
 2 | NULL
 2 | NULL
</code>```

And I want an output like this:

```<code>ID | Flag
-----------
 1 | True
 1 | True
 1 | True
 1 | True
 1 | True
 2 | False
 2 | False
 2 | False
 2 | False
 2 | False
</code>```

I want to replace nulls with the value assigned in different records. Is there a way to do it in a single update statement?

答:
Assuming (like your sample data suggests):

There can never be the same id with true and false in the set. Else, you'd have to define what to do.

null values remain unchanged if there is no non-null value for the same id.

This should give you best performance:

```<code>UPDATE tbl t
SET    flag = t1.flag
FROM  (
   SELECT DISTINCT ON (id)
          id, flag
   FROM   tbl
   ORDER  BY id, flag
   ) t1                      -- avoid repeated computation for same id
WHERE  t.id = t1.id
AND    t.flag IS NULL        -- avoid costly no-op updates
AND    t1.flag IS NOT NULL;  -- avoid costly no-op updates;
</code>```

db<>fiddle here

The subquery t1 distills target values per id once.

```<code>SELECT DISTINCT ON (id)
       id, flag
FROM   tbl
ORDER  BY id, flag;
</code>```

Since null sorts last, it effectively grabs the first non-null value per id. false sorts before true, but that has no bearing on the case as there can never be both for the same id. See:

Sort NULL values to the end of a table

Select first row in each GROUP BY group?

If you have many rows per id, there are faster techniques:

Optimize GROUP BY query to retrieve latest row per user

The added conditions in the outer query prevent all no-op updates from happening, thus avoiding major cost. Only rows are updated where a null value actually changes. See:

How do I (or can I) SELECT DISTINCT on multiple columns?

Title: Update based on same column

Body:
I have a table like this:

ID | Flag
-----------
 1 | True
 1 | True
 1 | NULL
 1 | True
 1 | NULL
 2 | False
 2 | False
 2 | False
 2 | NULL
 2 | NULL

And I want an output like this:

ID | Flag
-----------
 1 | True
 1 | True
 1 | True
 1 | True
 1 | True
 2 | False
 2 | False
 2 | False
 2 | False
 2 | False

I want to replace nulls with the value assigned in different records. Is there a way to do it in a single update statement?

Body:
Assuming (like your sample data suggests):

There can never be the same id with true and false in the set. Else, you'd have to define what to do.

null values remain unchanged if there is no non-null value for the same id.

This should give you best performance:

UPDATE tbl t
SET    flag = t1.flag
FROM  (
   SELECT DISTINCT ON (id)
          id, flag
   FROM   tbl
   ORDER  BY id, flag
   ) t1                      -- avoid repeated computation for same id
WHERE  t.id = t1.id
AND    t.flag IS NULL        -- avoid costly no-op updates
AND    t1.flag IS NOT NULL;  -- avoid costly no-op updates;

db<>fiddle here

The subquery t1 distills target values per id once.

SELECT DISTINCT ON (id)
       id, flag
FROM   tbl
ORDER  BY id, flag;

Since null sorts last, it effectively grabs the first non-null value per id. false sorts before true, but that has no bearing on the case as there can never be both for the same id. See:

Sort NULL values to the end of a table

Select first row in each GROUP BY group?

If you have many rows per id, there are faster techniques:

Optimize GROUP BY query to retrieve latest row per user

The added conditions in the outer query prevent all no-op updates from happening, thus avoiding major cost. Only rows are updated where a null value actually changes. See:

How do I (or can I) SELECT DISTINCT on multiple columns?


答:
you can use idxmax with axis along the columns, after checking where the values in df equal (eq)to the key row.

```<code>df["trace"] = df.iloc[1:, :].eq(df.loc['key', :]).idxmax(axis=1)
print (df)
     0  1  2  3  4  5  6  7  8  9  trace
key  2  3  4  3  6  2  3  4  3  6    NaN
1    7  6  3  4  5  4  3  2  1  2    6.0
2    5  4  3  2  3  6  7  6  7  6    9.0
3    4  5  4  3  6  7  6  3  4  5    2.0
4    2  3  4  5  4  3  6  7  6  3    0.0
5    7  6  3  4  3  2  1  2  3  6    5.0
</code>```

Body:
you can use idxmax with axis along the columns, after checking where the values in df equal (eq)to the key row.

df["trace"] = df.iloc[1:, :].eq(df.loc['key', :]).idxmax(axis=1)
print (df)
     0  1  2  3  4  5  6  7  8  9  trace
key  2  3  4  3  6  2  3  4  3  6    NaN
1    7  6  3  4  5  4  3  2  1  2    6.0
2    5  4  3  2  3  6  7  6  7  6    9.0
3    4  5  4  3  6  7  6  3  4  5    2.0
4    2  3  4  5  4  3  6  7  6  3    0.0
5    7  6  3  4  3  2  1  2  3  6    5.0


问:
How to get node-fetch's data in PHP?
I'm trying to make an application that sends JSON data to PHP server, and get responses from it. I'm using JavaScript node-fetch library for it.

Here is my sample code:

```<code>    const fetch = require("node-fetch");
    let data = JSON.stringify(something);

    fetch("https://example.com/api", {
        method: "post",
        body: data,
        headers: { 'Content-Type': 'application/json' }
    })
        .then(res => res.text())
        .then(ret=>{
            console.log(ret);
        });
</code>```

I'm trying to get this with $_POST in PHP:

```<code>var_dump($_POST);
</code>```

But it returns empty array.

How can I get this on PHP, or do I do something wrong?

答:
$_POST is only filled with values when receiving a request body with the application/x-www-form-urlencoded or multipart/form-data Content-Type header.

So you need to handle the JSON body like this:

```<code>$inputJSON = file_get_contents("php://input");
$input = json_decode($inputJSON, true);

var_dump($input);
</code>```

Title: How to get node-fetch's data in PHP?

Body:
I'm trying to make an application that sends JSON data to PHP server, and get responses from it. I'm using JavaScript node-fetch library for it.

Here is my sample code:

    const fetch = require("node-fetch");
    let data = JSON.stringify(something);

    fetch("https://example.com/api", {
        method: "post",
        body: data,
        headers: { 'Content-Type': 'application/json' }
    })
        .then(res => res.text())
        .then(ret=>{
            console.log(ret);
        });

I'm trying to get this with $_POST in PHP:

var_dump($_POST);

But it returns empty array.

How can I get this on PHP, or do I do something wrong?

Body:
$_POST is only filled with values when receiving a request body with the application/x-www-form-urlencoded or multipart/form-data Content-Type header.

So you need to handle the JSON body like this:

$inputJSON = file_get_contents("php://input");
$input = json_decode($inputJSON, true);

var_dump($input);


问:
How can I change this to not allow a negative number in the final count?
I'm having an issue with this assignment. It's something where the last week won't adjust the final interest/principal payment so that the balance can't go below zero. I thought that making my code while startBalance > 0 would stop it would allowing that?

```<code>price = float(input("Enter the purchase price: "))
down = .10
apr = .12
monthlyRate = .05
month = 0
downPayment = price * down
startBalance = price - downPayment
payment = startBalance * monthlyRate

print("%s%19s%18s%19s%10s%17s" % ("Month", "Starting Balance", "Interest to Pay", "Principal to Pay", "Payment", "Ending Balance"))

while startBalance > 0:
    month += 1
    interest = startBalance * apr / 12
    principal = payment - interest
    endBalance = startBalance - principal

    print("%2d%16.2f%16.2f%18.2f%18.2f%15.2f" % (month, startBalance, interest, principal, payment, endBalance))

    startBalance = endBalance
</code>```

答:
The problem is that you could technically have startBalance > 0 but when you calculate principal, principal > startBalance

One way to handle this is by adjusting the payment to be the minimum of the normal calculated amount and the remainingBalance

```<code>payment = startBalance * monthlyRate

print("%s%19s%18s%19s%10s%17s" % ("Month", "Starting Balance", "Interest to Pay",
"Principal to Pay", "Payment", "Ending Balance"))

while startBalance > 0:
    month += 1
    interest = startBalance * apr / 12
    principal = min(payment - interest, remainingBalance)
    endBalance = startBalance - principal

    print("%2d%16.2f%16.2f%18.2f%18.2f%15.2f" % (month, startBalance, interest, principal, payment, endBalance))

    startBalance = endBalance
</code>```

Body:
I'm having an issue with this assignment. It's something where the last week won't adjust the final interest/principal payment so that the balance can't go below zero. I thought that making my code while startBalance > 0 would stop it would allowing that?

price = float(input("Enter the purchase price: "))
down = .10
apr = .12
monthlyRate = .05
month = 0
downPayment = price * down
startBalance = price - downPayment
payment = startBalance * monthlyRate

print("%s%19s%18s%19s%10s%17s" % ("Month", "Starting Balance", "Interest to Pay", "Principal to Pay", "Payment", "Ending Balance"))

while startBalance > 0:
    month += 1
    interest = startBalance * apr / 12
    principal = payment - interest
    endBalance = startBalance - principal

    print("%2d%16.2f%16.2f%18.2f%18.2f%15.2f" % (month, startBalance, interest, principal, payment, endBalance))

    startBalance = endBalance

Body:
The problem is that you could technically have startBalance > 0 but when you calculate principal, principal > startBalance

One way to handle this is by adjusting the payment to be the minimum of the normal calculated amount and the remainingBalance

payment = startBalance * monthlyRate

print("%s%19s%18s%19s%10s%17s" % ("Month", "Starting Balance", "Interest to Pay",
"Principal to Pay", "Payment", "Ending Balance"))

while startBalance > 0:
    month += 1
    interest = startBalance * apr / 12
    principal = min(payment - interest, remainingBalance)
    endBalance = startBalance - principal

    print("%2d%16.2f%16.2f%18.2f%18.2f%15.2f" % (month, startBalance, interest, principal, payment, endBalance))

    startBalance = endBalance


问:
Change page source without using document.write()
I want to change/replace the full page source of a page using JS (this is what happens when you use document.write), but document.write() is not recommended. I've tried document.innerHTML and some others, but I can't find one that works. Is there a way to 'rewrite' the page source using JS that respects best practices? Thanks in advance! (This is my first question, so tell me if I'm doing something wrong)

Edit: I mean change all of the page source (including head), not just the body.

Example:
Before running JS, the page source is:
Hi

After running JS: <title>ttl</title>Hi!!M

答:
Try to use</p>

```<code><script>
window.onload = function() {
    document.getElementsByTagName('body')[0].innerHTML="JavaScript";
}
</script>
</code>```

Body:
Try to use

<script>
window.onload = function() {
    document.getElementsByTagName('body')[0].innerHTML="JavaScript";
}
</script>


问:
Python script not finding imported function
I have 2 extremely simple python files. I am doing this as a test to see if blah2.py sees the updated version of the two variables initially declared as None after the 2 second sleep. The files are as below:

blah1.py

```<code>from time import sleep
import blah2

movingVariable1 = None
movingVariable2 = None

sleep(2)
movingVariable1 = "sup"
movingVariable2 = "blahhh"
blah2.myFunc()
</code>```

blah2.py

```<code>from blah1 import movingVariable1
from blah1 import movingVariable2

def myFunc():
    global movingVariable1
    global movingVariable2
    print(movingVariable1)
    print(movingVariable2)
</code>```

I am getting the following error though, and I'm not sure why.

```<code> Traceback (most recent call last):
  File "blah1.py", line 2, in <module>
    import blah2
  File "/home/pi/blah2.py", line 1, in <module>
    from blah1 import movingVariable1
  File "/home/pi/blah1.py", line 10, in <module>
    blah2.myFunc()
AttributeError: module 'blah2' has no attribute 'myFunc'
</code>```

myFunc() clearly is defined as a function though in blah2.py. Can anyone explain what I am doing wrong in this basic example?

答:
You are creating a circular dependency in blah2.py

In your example blah1 imports blah2 which in turn imports blah1 which will again import blah2 and so on...

Make movingVariable & movingVariable2 parameters for myFunc and remove import of blah1.py in blah2.py.

Reply to follow-up

```<code># blah1.py
from blah1 import movingVariable1
from blah1 import movingVariable2

def myFunc():
    global movingVariable1
    global movingVariable2
    print(movingVariable1)
    print(movingVariable2)
</code>```

```<code># blah2.py
from time import sleep

movingVariable1 = None
movingVariable2 = None

if __name__ =='__main__':
    import blah2
    sleep(2)
    movingVariable1 = "sup"
    movingVariable2 = "blahhh"
    blah2.myFunc()
</code>```

If you change it like this it will work. Since when blah2 import blah1.py it does not see import blah2 since then __name__ will not be equal to __main__.

Body:
I have 2 extremely simple python files. I am doing this as a test to see if blah2.py sees the updated version of the two variables initially declared as None after the 2 second sleep. The files are as below:

blah1.py

from time import sleep
import blah2

movingVariable1 = None
movingVariable2 = None

sleep(2)
movingVariable1 = "sup"
movingVariable2 = "blahhh"
blah2.myFunc()

blah2.py

from blah1 import movingVariable1
from blah1 import movingVariable2

def myFunc():
    global movingVariable1
    global movingVariable2
    print(movingVariable1)
    print(movingVariable2)

I am getting the following error though, and I'm not sure why.

 Traceback (most recent call last):
  File "blah1.py", line 2, in <module>
    import blah2
  File "/home/pi/blah2.py", line 1, in <module>
    from blah1 import movingVariable1
  File "/home/pi/blah1.py", line 10, in <module>
    blah2.myFunc()
AttributeError: module 'blah2' has no attribute 'myFunc'

myFunc() clearly is defined as a function though in blah2.py. Can anyone explain what I am doing wrong in this basic example?

Body:
You are creating a circular dependency in blah2.py

In your example blah1 imports blah2 which in turn imports blah1 which will again import blah2 and so on...

Make movingVariable & movingVariable2 parameters for myFunc and remove import of blah1.py in blah2.py.

Reply to follow-up

# blah1.py
from blah1 import movingVariable1
from blah1 import movingVariable2

def myFunc():
    global movingVariable1
    global movingVariable2
    print(movingVariable1)
    print(movingVariable2)

# blah2.py
from time import sleep

movingVariable1 = None
movingVariable2 = None

if __name__ =='__main__':
    import blah2
    sleep(2)
    movingVariable1 = "sup"
    movingVariable2 = "blahhh"
    blah2.myFunc()

If you change it like this it will work. Since when blah2 import blah1.py it does not see import blah2 since then __name__ will not be equal to __main__.


问:
Adding Multiple CSV Fields within a singular ListBox
I've been trying to create a leaderboard a little maze game I'm creating and im using a CSV File to store my data. I have two fields per row, something akin to
James, 20
Luke, 34
Which is "playername" and "score".

Whenever i run the code [below], my listbox displays;

James

20

Luke

34

I'm attempting to display it as something such as

James 20

Luke 34

I've tried to store the first field as a string and grab the next field and concatenate the two together to display it on one line, however i was unable to grab the next field as it would result in a recoding of the reading function.

```<code>                                FileIO.TextFieldParser(
                                  "C:\Users\zamks1622\Desktop\Computing\SAT\Leaderboard.csv")
            MyReader.TextFieldType = FileIO.FieldType.Delimited
            MyReader.SetDelimiters(",")
            Dim currentRow As String()
            While Not MyReader.EndOfData
                Try
                    currentRow = MyReader.ReadFields()
                    Dim currentField As String
                    For Each currentField In currentRow
                        ListLeaderboard.Items.Add(currentField)
                    Next
                Catch ex As Microsoft.VisualBasic.
                            FileIO.MalformedLineException
                    MsgBox("Line " & ex.Message &
                    "is not valid and will be skipped.")
                End Try
            End While
        End Using
</code>```

答:
I think this may help</p>

```<code>Try
    currentRow = MyReader.ReadFields()
    ListLeaderboard.Items.Add(Join(currentRow , " "))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
</code>```

Body:
I've been trying to create a leaderboard a little maze game I'm creating and im using a CSV File to store my data. I have two fields per row, something akin to
James, 20
Luke, 34
Which is "playername" and "score".

Whenever i run the code [below], my listbox displays;

James

20

Luke

34

I'm attempting to display it as something such as

James 20

Luke 34

I've tried to store the first field as a string and grab the next field and concatenate the two together to display it on one line, however i was unable to grab the next field as it would result in a recoding of the reading function.

                                FileIO.TextFieldParser(
                                  "C:\Users\zamks1622\Desktop\Computing\SAT\Leaderboard.csv")
            MyReader.TextFieldType = FileIO.FieldType.Delimited
            MyReader.SetDelimiters(",")
            Dim currentRow As String()
            While Not MyReader.EndOfData
                Try
                    currentRow = MyReader.ReadFields()
                    Dim currentField As String
                    For Each currentField In currentRow
                        ListLeaderboard.Items.Add(currentField)
                    Next
                Catch ex As Microsoft.VisualBasic.
                            FileIO.MalformedLineException
                    MsgBox("Line " & ex.Message &
                    "is not valid and will be skipped.")
                End Try
            End While
        End Using

Body:
I think this may help

Try
    currentRow = MyReader.ReadFields()
    ListLeaderboard.Items.Add(Join(currentRow , " "))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException


问:
Expose environment variables to Apache and PHP

Background

I'm trying to use Wercker to run my test for a PHP application. Wercker uses Docker containers to setup a test environment to execute tests in. It uses Environment Variables to expose the connection params for any connected services like MySQL and Elasticsearch. Example MYSQL_PORT_3306_TCP_ADDR = 127.0.1.1

My core Docker containers is running Ubuntu 14.04 with PHP and Apache already installed on the container.

Problem

I can't seem to access the Environment Variables via php $_SERVER or $_ENV when running via Apache. It works fine if I run the script via CLI php ./db_connect.php or if I run PHP using its build in server php -S localhost:8000. However If I try and access a page via the Apache virtual host, the Environment Variables are not available.

Progress

I have setup Apache with the mod used to allow environmental variables "I think"

```<code>sudo a2enmod env
sudo service apache2 restart
</code>```

I'm trying to access the Environment Variables in my script.

```<code>$database_host      = $_SERVER["MYSQL_PORT_3306_TCP_ADDR"];
$database_username  = $_SERVER["MYSQL_ENV_MYSQL_USER"];
$database_password  = $_SERVER["MYSQL_ENV_MYSQL_PASSWORD"];
$database_name      = $_SERVER["MYSQL_ENV_MYSQL_DATABASE"];
$elasticsearch_host = $_SERVER["ELASTICSEARCH_PORT_9300_TCP_ADDR"];
</code>```

I can add new variables in my .htaccess, I just don't get all the system environmental variables.

```<code>SetEnv TEST_VAR test
</code>```

I have read this question How to get system environment variables into PHP while running CLI & Apache2Handler? but i'm not sure what its suggesting to do.

Question

How do I expose System Environment Variables to Apache and PHP?

答:
you can check get env with php command like below

```<code>php -r "echo getenv('MYSQL_USER');"
</code>```

Body:
Background

I'm trying to use Wercker to run my test for a PHP application. Wercker uses Docker containers to setup a test environment to execute tests in. It uses Environment Variables to expose the connection params for any connected services like MySQL and Elasticsearch. Example MYSQL_PORT_3306_TCP_ADDR = 127.0.1.1

My core Docker containers is running Ubuntu 14.04 with PHP and Apache already installed on the container.

Problem

I can't seem to access the Environment Variables via php $_SERVER or $_ENV when running via Apache. It works fine if I run the script via CLI php ./db_connect.php or if I run PHP using its build in server php -S localhost:8000. However If I try and access a page via the Apache virtual host, the Environment Variables are not available.

Progress

I have setup Apache with the mod used to allow environmental variables "I think"

sudo a2enmod env
sudo service apache2 restart

I'm trying to access the Environment Variables in my script.

$database_host      = $_SERVER["MYSQL_PORT_3306_TCP_ADDR"];
$database_username  = $_SERVER["MYSQL_ENV_MYSQL_USER"];
$database_password  = $_SERVER["MYSQL_ENV_MYSQL_PASSWORD"];
$database_name      = $_SERVER["MYSQL_ENV_MYSQL_DATABASE"];
$elasticsearch_host = $_SERVER["ELASTICSEARCH_PORT_9300_TCP_ADDR"];

I can add new variables in my .htaccess, I just don't get all the system environmental variables.

SetEnv TEST_VAR test

I have read this question How to get system environment variables into PHP while running CLI & Apache2Handler? but i'm not sure what its suggesting to do.

Question

How do I expose System Environment Variables to Apache and PHP?

Body:
you can check get env with php command like below

php -r "echo getenv('MYSQL_USER');"


问:
disabling one of the options in WTForms SelectField
What is the simplest way to assign 'disabled' html attribute to one of the options in SelectField in WTForms?

This is my previous code

```<code><select class="form-control" name="division" data-error="Required!" required>
     <option value="default" disabled selected>Select something</option>
     <option value="option1">Option 1</option>
     <option value="option2">Option 2</option>
 </select>
</code>```

As you can see I would like to set 'disabled' only to first option.

My code for this task is:

```<code>next(form.division.__iter__())(**{'disabled':'true'})
</code>```

And using print function in console I can see the proper output:

```<code><option disabled="true" selected value="default">Select something</option>
</code>```

The line is working, but somehow this output is not passed to the template.
Instead this is what's passed:

```<code><option selected value="default">Select something</option>
</code>```

Please someone make it clear.

答:
If you simply just want a disabled and selected option as the first option of your select, I found this to be simpler than extending the SelectField class:

Just loop over the option and check for first loop iteration

<select name="my_select" id="my_select">
    {% for option in form.my_select %}
        {% if loop.first %}
            <option value="" disabled selected>select something</option>
        {% endif %}
        {{ option }}
    {% endfor %}
</select>
```

Body:
What is the simplest way to assign 'disabled' html attribute to one of the options in SelectField in WTForms?

This is my previous code

<select class="form-control" name="division" data-error="Required!" required>
     <option value="default" disabled selected>Select something</option>
     <option value="option1">Option 1</option>
     <option value="option2">Option 2</option>
 </select>

As you can see I would like to set 'disabled' only to first option.

My code for this task is:

next(form.division.__iter__())(**{'disabled':'true'})

And using print function in console I can see the proper output:

<option disabled="true" selected value="default">Select something</option>

The line is working, but somehow this output is not passed to the template.
Instead this is what's passed:

<option selected value="default">Select something</option>

Please someone make it clear.


问:
Upload file with Ajax XMLHttpRequest
I am trying to send file with XMLHttpRequest with this code.

var url= "http://localhost:80/....";
$(document).ready(function(){
    document.getElementById('upload').addEventListener('change', function(e) {
        var file = this.files[0];
        var xhr = new XMLHttpRequest();
        xhr.file = file; // not necessary if you create scopes like this
        xhr.addEventListener('progress', function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
        }, false);
        if ( xhr.upload ) {
            xhr.upload.onprogress = function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
            };
        }
        xhr.onreadystatechange = function(e) {
            if ( 4 == this.readyState ) {
                console.log(['xhr upload complete', e]);
            }
        };
        xhr.open('post', url, true);
        xhr.setRequestHeader("Content-Type","multipart/form-data");
        xhr.send(file);
    }, false);
});
```

I get this error: T

The request was rejected because no multipart boundary was found.

What am I doing wrong?

答:
There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.

xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

```<code>var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
</code>```

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Title: Upload file with Ajax XMLHttpRequest

Body:
I am trying to send file with XMLHttpRequest with this code.

var url= "http://localhost:80/....";
$(document).ready(function(){
    document.getElementById('upload').addEventListener('change', function(e) {
        var file = this.files[0];
        var xhr = new XMLHttpRequest();
        xhr.file = file; // not necessary if you create scopes like this
        xhr.addEventListener('progress', function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
            console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
        }, false);
        if ( xhr.upload ) {
            xhr.upload.onprogress = function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
            };
        }
        xhr.onreadystatechange = function(e) {
            if ( 4 == this.readyState ) {
                console.log(['xhr upload complete', e]);
            }
        };
        xhr.open('post', url, true);
        xhr.setRequestHeader("Content-Type","multipart/form-data");
        xhr.send(file);
    }, false);
});

I get this error: T

The request was rejected because no multipart boundary was found.

What am I doing wrong?

Body:
There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.

xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.


问:
How do I prompt for an MFA key to generate and use credentials for AWS CLI access?
I have several Bash scripts that invoke AWS CLI commands for which permissions have changed to require MFA, and I want to be able to prompt for a code generated by my MFA device in these scripts so that they can run with the necessary authentication.

But there seems to be no simple built in way to do this. The only documentation I can find involves a complicated process of using aws sts get-session-token and then saving each value in a configuration, which it is then unclear how to use.

To be clear what I'd like is that when I run one of my scripts that that contains AWS CLI commands that require MFA, I'm simply prompted for the code, so that providing it allows the AWS CLI operations to complete. Something like:

```<code>#!/usr/bin/env bash

# (1) prompt for generated MFA code
# ???

# (2) use entered code to generate necessary credentials
aws sts get-session-token ... --token-code $ENTERED_VALUE

# (3) perform my AWS CLI commands requiring MFA
# ....
</code>```

It's not clear to me how to prompt for this when needed (which is probably down to not being proficient with bash) or how to use the output of get-session-token once I have it.

Is there a way to do what I'm looking for?

I've tried to trigger a prompt by specifying a --profile with a mfa_serial entry; but that doesn't work either.

答:
Inspired by @strongjz and @Nick answers, I wrote a small Python command to which you can pipe the output of the aws sts command.

To install:

pip install sts2credentials

To use:

```<code>aws sts get-session-token \
    --serial-number arn:aws:iam::123456789012:mfa/your-iam-user \
    --token-code 123456 \
    --profile=your-profile-name  \
    | sts2credentials
</code>```

This will automatically add the access key ID, the secret access key, and the session token under a new "sts" profile in your ~/.aws/credentials file.

Body:
I have several Bash scripts that invoke AWS CLI commands for which permissions have changed to require MFA, and I want to be able to prompt for a code generated by my MFA device in these scripts so that they can run with the necessary authentication.

But there seems to be no simple built in way to do this. The only documentation I can find involves a complicated process of using aws sts get-session-token and then saving each value in a configuration, which it is then unclear how to use.

To be clear what I'd like is that when I run one of my scripts that that contains AWS CLI commands that require MFA, I'm simply prompted for the code, so that providing it allows the AWS CLI operations to complete. Something like:

#!/usr/bin/env bash

# (1) prompt for generated MFA code
# ???

# (2) use entered code to generate necessary credentials
aws sts get-session-token ... --token-code $ENTERED_VALUE

# (3) perform my AWS CLI commands requiring MFA
# ....

It's not clear to me how to prompt for this when needed (which is probably down to not being proficient with bash) or how to use the output of get-session-token once I have it.

Is there a way to do what I'm looking for?

I've tried to trigger a prompt by specifying a --profile with a mfa_serial entry; but that doesn't work either.

Body:
Inspired by @strongjz and @Nick answers, I wrote a small Python command to which you can pipe the output of the aws sts command.

To install:

pip install sts2credentials

To use:

aws sts get-session-token \
    --serial-number arn:aws:iam::123456789012:mfa/your-iam-user \
    --token-code 123456 \
    --profile=your-profile-name  \
    | sts2credentials

This will automatically add the access key ID, the secret access key, and the session token under a new "sts" profile in your ~/.aws/credentials file.


问:
Inverting UTF16 to UTF8 conversion for astral characters
My question is simple. Start with a character that is not in the basic multilingual plane, say var original = "" or equivalently

```<code>var original=`\u{1f3ae}`
</code>```

Javascript stores this string in memory via UTF-16 encoding. Unfortunately, you give the string to some database/application (specifics irrelevant) and it mis-interprets the UTF-16 bytes as UTF-8 bytes, and when you read out the string from the database/application what it actually gives you is precisely

```<code>var switchedEncoding = Buffer.from(original, 'utf16le').toString('utf8')
</code>```

If you log switchedEncoding in this case you get <خ�. Not good. Okay, so you try to switch it back:

```<code>var switchedBack = Buffer.from(switchedEncoding,'utf8').toString('utf16le')
</code>```

If you log switchedBack in this case you get �붿 not . Bummer.

On the otherhand if your original string is in the BMP, switchedBack recovers the original just fine. My question is whether or not information is irreversibly lost by the incorrect decoding done by the application/database? If not, I would like a clever function that can invert it even for characters in the astral planes.

Thanks for your help!

答:
Answer was as follows. I could get the database (a leveldb) to read things out into a buffer, and then I used the following approach using the iconv package in node:

```<code>const Iconv = require("iconv").Iconv;
let iconv = new Iconv("UTF-8","UTF-16LE");
let iconv2 = new Iconv("UTF-16LE","UTF-8");
let original = "\u{1f3ae}"
let switched = iconv.convert(original)
let switchedBack = iconv2.convert(switched)
console.log(original)
console.log(switched.toString())
console.log(switchedBack.toString())

// So it's the switched.toString() which is not recoverable;
// switched itself (a Buffer) is;
</code>```

Good to know that Buffer.toString('someEncoding') is not always invertible if the encoding of the bytes in the buffer isn't someEncoding.

Body:
My question is simple. Start with a character that is not in the basic multilingual plane, say var original = "" or equivalently

var original=`\u{1f3ae}`

Javascript stores this string in memory via UTF-16 encoding. Unfortunately, you give the string to some database/application (specifics irrelevant) and it mis-interprets the UTF-16 bytes as UTF-8 bytes, and when you read out the string from the database/application what it actually gives you is precisely

var switchedEncoding = Buffer.from(original, 'utf16le').toString('utf8')

If you log switchedEncoding in this case you get <خ�. Not good. Okay, so you try to switch it back:

var switchedBack = Buffer.from(switchedEncoding,'utf8').toString('utf16le')

If you log switchedBack in this case you get �붿 not . Bummer.

On the otherhand if your original string is in the BMP, switchedBack recovers the original just fine. My question is whether or not information is irreversibly lost by the incorrect decoding done by the application/database? If not, I would like a clever function that can invert it even for characters in the astral planes.

Thanks for your help!

Body:
Answer was as follows. I could get the database (a leveldb) to read things out into a buffer, and then I used the following approach using the iconv package in node:

const Iconv = require("iconv").Iconv;
let iconv = new Iconv("UTF-8","UTF-16LE");
let iconv2 = new Iconv("UTF-16LE","UTF-8");
let original = "\u{1f3ae}"
let switched = iconv.convert(original)
let switchedBack = iconv2.convert(switched)
console.log(original)
console.log(switched.toString())
console.log(switchedBack.toString())

// So it's the switched.toString() which is not recoverable;
// switched itself (a Buffer) is;

Good to know that Buffer.toString('someEncoding') is not always invertible if the encoding of the bytes in the buffer isn't someEncoding.


问:
Homework Assignment infile / outfiles
My assignment states the following :

Three employees in a company are up for a special pay increase. You are given a file, Ch3_Ex7Data.txt, with the following data:

Miller Andrew 65789.87 5

Green Sheila 75892.56 6

Sethi Amit 74900.50 6.1

Each input line consists of an employee's last name, first name, current salary, and percent pay increase.

For example, in the first input line, the last name of the employee is Miller, the first name is Andrew, the current salary is 65789.87, and the pay increase is 5 %.

Write a program that reads data from the specified file and stores the output in the file Ch3_Ex7Output.dat. For each employee, the data must be output in the following form:
firstName lastName updatedSalary
 Format the output of decimal numbers to two decimal places.

My code is the following.

```<code>#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    //Declaring the variables
    string firstName;
    string lastName;
    double payIncrease;
    double pay;
    ifstream inFile;
    ofstream outFile;

    inFile.open("C:\\Users\\Megan\\Ch3_Ex7Data.txt"); //opens the input file
    outFile.open("C:\\Users\\Megan\\Ch3_Ex7Output.dat"); //opens a output file

    outFile << fixed << showpoint;
    outFile << setprecision(2); // Output file only having two decimal places
    cout << "Processing Data....." endl;  //program message

    while (!inFile.eof() //loop
        inFile >> lastName >> firstName >> pay >> payIncrease;
        pay = pay*(pay*payIncrease);
        outFile << firstName << " " << lastName << " " << pay << "/n";

    inFile.close();
    outFile.close();

    return 0;
}
</code>```

For some reason I cannot seem to get the code to open my existing .txt file, read it and then translate it to another file. Does anybody see anything wrong with this that could help me out?

答:
This was my solution</p>

```<code>#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main() {
    // Write your main here
    //Declarations
    string FirstName;
    string LastName;
    double Pay;
    double Increase;
    double UpdatedSalery;

    //File object and open txt and dat files per instructions and use user input for    the txt input file
    ifstream FileIn;
    string FileName;
    cout << "enter a file name: ";
    cin >> FileName;
    FileIn.open(FileName);

    ofstream FileOut("Ch3_Ex5Output.dat");
    FileOut << setprecision(8);

    while(FileIn >> LastName >> FirstName >> Pay >> Increase){
        UpdatedSalery = ((Pay*(Increase/100))+Pay);
        FileOut << " " << FirstName << " " << LastName << " " << UpdatedSalery << endl;
    }
    FileIn.close();
    FileOut.close();
    return 0;
}
</code>```

Title: Homework Assignment infile / outfiles

Body:
My assignment states the following :

Three employees in a company are up for a special pay increase. You are given a file, Ch3_Ex7Data.txt, with the following data:

Miller Andrew 65789.87 5

Green Sheila 75892.56 6

Sethi Amit 74900.50 6.1

Each input line consists of an employee's last name, first name, current salary, and percent pay increase.

For example, in the first input line, the last name of the employee is Miller, the first name is Andrew, the current salary is 65789.87, and the pay increase is 5 %.

Write a program that reads data from the specified file and stores the output in the file Ch3_Ex7Output.dat. For each employee, the data must be output in the following form:
firstName lastName updatedSalary
 Format the output of decimal numbers to two decimal places.

My code is the following.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
    //Declaring the variables
    string firstName;
    string lastName;
    double payIncrease;
    double pay;
    ifstream inFile;
    ofstream outFile;

    inFile.open("C:\\Users\\Megan\\Ch3_Ex7Data.txt"); //opens the input file
    outFile.open("C:\\Users\\Megan\\Ch3_Ex7Output.dat"); //opens a output file

    outFile << fixed << showpoint;
    outFile << setprecision(2); // Output file only having two decimal places
    cout << "Processing Data....." endl;  //program message

    while (!inFile.eof() //loop
        inFile >> lastName >> firstName >> pay >> payIncrease;
        pay = pay*(pay*payIncrease);
        outFile << firstName << " " << lastName << " " << pay << "/n";

    inFile.close();
    outFile.close();

    return 0;
}

For some reason I cannot seem to get the code to open my existing .txt file, read it and then translate it to another file. Does anybody see anything wrong with this that could help me out?

Body:
This was my solution

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main() {
    // Write your main here
    //Declarations
    string FirstName;
    string LastName;
    double Pay;
    double Increase;
    double UpdatedSalery;

    //File object and open txt and dat files per instructions and use user input for    the txt input file
    ifstream FileIn;
    string FileName;
    cout << "enter a file name: ";
    cin >> FileName;
    FileIn.open(FileName);

    ofstream FileOut("Ch3_Ex5Output.dat");
    FileOut << setprecision(8);

    while(FileIn >> LastName >> FirstName >> Pay >> Increase){
        UpdatedSalery = ((Pay*(Increase/100))+Pay);
        FileOut << " " << FirstName << " " << LastName << " " << UpdatedSalery << endl;
    }
    FileIn.close();
    FileOut.close();
    return 0;
}


问:
List files in Glacier with AWS CLI
I need to delete files stored in a Glacier Vault, but  AWS CLI needs the object id and I can't execute the correct command to obtain this id.

Anyone knows the command to see the file id with AWS CLI?

答:
One problem is that how the strings are quoted depending on whether you are using Linux or Mac or Powershell or Windows. See AWS doc on quoting strings

For the Windows command prompt, this works:

```<code>aws glacier initiate-job --account-id 123456789012  --vault-name myvault --job-parameters "{\"Type\": \"inventory-retrieval\"}"
</code>```

For PowerShell use single quotes around the JSON but still escape the double quotes.  With Linux and Mac you shouldn't need to escape the double quotes.

Title: List files in Glacier with AWS CLI

Body:
One problem is that how the strings are quoted depending on whether you are using Linux or Mac or Powershell or Windows. See AWS doc on quoting strings

For the Windows command prompt, this works:

aws glacier initiate-job --account-id 123456789012  --vault-name myvault --job-parameters "{\"Type\": \"inventory-retrieval\"}"

For PowerShell use single quotes around the JSON but still escape the double quotes.  With Linux and Mac you shouldn't need to escape the double quotes.


问:
Why boostrap carousel don't show the images (not even the place holders)?
I'm using Bootstrap. I've paste the code from documention on how to use a carousel.

But images won't show. Not even the gray squares, that are used as placeholders why?

Codepen:

https://codepen.io/ogonzales/pen/VweZYbK

Same happens in localhost:

Code:

```<code><div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img src="..." class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    </div>
    <div class="carousel-item">
      <img src="..." class="d-block w-100" alt="...">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</code>```

答:
You have to include all the bootstrap 4 scripts required to run the carousel.

.carousel-inner img {
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>

<body>

  <div id="demo" class="carousel slide" data-ride="carousel">

    <!-- Indicators -->
    <ul class="carousel-indicators">
      <li data-target="#demo" data-slide-to="0" class="active"></li>
      <li data-target="#demo" data-slide-to="1"></li>
      <li data-target="#demo" data-slide-to="2"></li>
    </ul>

    <!-- The slideshow -->
    <div class="carousel-inner">
      <div class="carousel-item active">
        <img src="la.jpg" alt="Los Angeles" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="chicago.jpg" alt="Chicago" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="ny.jpg" alt="New York" width="1100" height="500">
      </div>
    </div>

    <!-- Left and right controls -->

      <span class="carousel-control-prev-icon"></span>

      <span class="carousel-control-next-icon"></span>

  </div>

</body>

</html></code>```

Note: Please replace the images with your working images to see the effect.

Shamelessly copied from: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_carousel

Body:
I'm using Bootstrap. I've paste the code from documention on how to use a carousel.

But images won't show. Not even the gray squares, that are used as placeholders why?

Codepen:

https://codepen.io/ogonzales/pen/VweZYbK

Same happens in localhost:

Code:

    Previous

    Next

Body:
You have to include all the bootstrap 4 scripts required to run the carousel.

.carousel-inner img {
  width: 100%;
  height: 100%;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>

<body>

  <div id="demo" class="carousel slide" data-ride="carousel">

    <!-- Indicators -->
    <ul class="carousel-indicators">
      <li data-target="#demo" data-slide-to="0" class="active"></li>
      <li data-target="#demo" data-slide-to="1"></li>
      <li data-target="#demo" data-slide-to="2"></li>
    </ul>

    <!-- The slideshow -->
    <div class="carousel-inner">
      <div class="carousel-item active">
        <img src="la.jpg" alt="Los Angeles" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="chicago.jpg" alt="Chicago" width="1100" height="500">
      </div>
      <div class="carousel-item">
        <img src="ny.jpg" alt="New York" width="1100" height="500">
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="carousel-control-prev" href="#demo" data-slide="prev">
      <span class="carousel-control-prev-icon"></span>
    </a>
    <a class="carousel-control-next" href="#demo" data-slide="next">
      <span class="carousel-control-next-icon"></span>
    </a>
  </div>

</body>

</html>

Note: Please replace the images with your working images to see the effect.

Shamelessly copied from: https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_carousel


问:
What does #define macro() <...> do?
What does this line do?
I doubt its a template or expression. (doing those divies and naming a member hpp is a bad idea)

```<code># define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>
</code>```

Full file

```<code># /* **************************************************************************
#  *                                                                          *
#  *     (C) Copyright Paul Mensonides 2005.                                  *
#  *     Distributed under the Boost Software License, Version 1.0. (See      *
#  *     accompanying file LICENSE_1_0.txt or copy at                         *
#  *     http://www.boost.org/LICENSE_1_0.txt)                                *
#  *                                                                          *
#  ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
# define BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
#
# include <boost/preprocessor/slot/detail/def.hpp>
#
# /* BOOST_PP_COUNTER */
#
# define BOOST_PP_COUNTER 0
#
# /* BOOST_PP_UPDATE_COUNTER */
#
# define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>
#
# endif
</code>```

答:
It's just a "shortcut" so you can do

```<code>#include BOOST_PP_UPDATE_COUNTER()
</code>```

in your code rather than know the details of how that feature is implemented.

See this question Incremented define's answers for some usage example.

Title: What does #define macro() <...> do?

Body:
What does this line do?
I doubt its a template or expression. (doing those divies and naming a member hpp is a bad idea)

# define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>

Full file

# /* **************************************************************************
#  *                                                                          *
#  *     (C) Copyright Paul Mensonides 2005.                                  *
#  *     Distributed under the Boost Software License, Version 1.0. (See      *
#  *     accompanying file LICENSE_1_0.txt or copy at                         *
#  *     http://www.boost.org/LICENSE_1_0.txt)                                *
#  *                                                                          *
#  ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
# define BOOST_PREPROCESSOR_SLOT_COUNTER_HPP
#
# include <boost/preprocessor/slot/detail/def.hpp>
#
# /* BOOST_PP_COUNTER */
#
# define BOOST_PP_COUNTER 0
#
# /* BOOST_PP_UPDATE_COUNTER */
#
# define BOOST_PP_UPDATE_COUNTER() <boost/preprocessor/slot/detail/counter.hpp>
#
# endif

Body:
It's just a "shortcut" so you can do

#include BOOST_PP_UPDATE_COUNTER()

in your code rather than know the details of how that feature is implemented.

See this question Incremented define's answers for some usage example.