问:
Problems in displaying redux state changes in react components
Update to the original post: I have realized that the issue is that the updates in the Redux state (props to the WaitingRoom component) somehow set the entire state of the component to its initial state. Thus, "showmatchingwindow" was set to false as well. Initially, after MATCHING_REQUEST was dispatched and "loading" was set to true, the state of WaitingRoom component still remained unchanged. However, after MATCHING_SUCCESS was dispatched and "loading" turned false and "buddy" and "chatid" in the Redux state got updated, all the fields in the state of WaitingRoom were somehow reset to their initial values. This is weird and did not happen with my other Redux actions. I am wondering whether anyone can help me explain what caused this. Really appreciate your patience and any help you can offer!

Link to the Github repo: https://github.com/liu550/salon_project (WaitingRoom component is in src/components/waitingroom.js

///Below is the original post///

I am building a random matching feature for my website. Here is a brief description: I want a chat window to pop up once 2 users are successfully matched up. Inside my Redux state, I have (1) "loading," (2) "buddy" representing the id of the user that our current user is matched with, and (3) "chatid" representing the id of the firestore document that stores the chat history between 2 users. The startMatching Redux action is called in the WaitingRoom component which is a web page that displays other users' profiles in addition to having the matching button. The chat window is the MatchingWindow component, which needs a chatid as its props to render the corresponding chat history between 2 users.

I am sure that my Redux actions work fine but got problems when passing the updated Redux state to my React components. Below are 2 approaches that I tried:

Approach 1: Display the chat window inside a modal returned by the WaitingRoom component. As you can see, what I am doing here is just conditional rendering. However, with this approach, the modal somehow quickly showed up for less than a second and then disappeared along with the previous modal where users select their gender preferences. Checking the props to the WaitingRoom component, I found that "buddy" and "chatid" were indeed updated. Shouldn't MatchingWindow be rendered? I also tried just putting success> instead of the MatchingWindow component and it was the same outcome.

Approach 1 (WaitingRoom)

```<code>class WaitingRoom extends Component {

    state = {
      ......
    }

    showMatching = (e) => {
      e.preventDefault();
      this.setState({
        showmatching: true
      })
    }

    handleMatching = (e) => {
      e.preventDefault();
      this.props.startMatching(this.props.auth.uid, this.props.profile, this.props.profile.gender, this.state.genderpreference);
      this.setState({
        showmatchingwindow: true
      })
    }

    closeMatching = () => {
      this.setState({
        showmatching: false
      })
    }

      render() {

        const { auth, users, profile, loading, sent, buddy, chatid } = this.props;

        return (

            <div>
            <Button variant="success" onClick={this.showMatching} style={{ fontSize: "large", fontFamily: "Comic Sans MS, cursive, sans-serif"}}>Randomly find a study/work buddy instantly!</Button>
            </div>

            <Modal show={this.state.showmatching} onHide={this.closeMatching}>
              <Modal.Header closeButton></Modal.Header>
              <Modal.Body>
                <form onSubmit={this.handleMatching}>
                  Match me with:
                  <div className="form-inline">
                        <div className="radio-container">
                            <label>Male only</label><input type="radio" id="genderpreference" value="Male" onChange={this.handleChange} checked={this.state.genderpreference === "Male"} />
                        </div>

                  ......

                  </div>

                  <button>Start matching</button>
                </form>
              </Modal.Body>
            </Modal>

            <Modal show={this.state.showmatchingwindow} onHide={this.closeMatching}>
              <Modal.Header closeButton></Modal.Header>
              <Modal.Body>
                { loading ?  <div class="loader"></div> : null}
                { buddy !== "" && loading === false ? <MatchingWindow chatid=chatid /> : null }
                { buddy === "" && loading === false ? <span>Sorry we cannot help you find a study/work buddy currently</span> : null }
              </Modal.Body>
            </Modal>

        );
      }
    }

const mapStateToProps = (state) => {
  return {
    users: state.firestore.ordered.users,
    auth: state.firebase.auth,
    profile: state.firebase.profile,
    loading: state.auth.loading,
    sent: state.auth.sent,
    buddy: state.auth.buddy,
    chatid: state.auth.chatid
  }
}

export default compose(
connect(mapStateToProps, {submitTicket, startMatching, groupMessaging}),
firestoreConnect([
{ collection: 'users' }
])
)(WaitingRoom);

</code>```

Approach 2: Create a separate MatchingBox component, which will render different elements/components based on different states. However, when I went with this approach, componentWillReceiveProps() was not fired after the Redux state changes, as the console.log()s I placed inside the method were not executed. It was weird because, as I mentioned in approach 1, the Redux state was indeed changed when I checked the props to the WaitingRoom component, which means that my Redux action and reducer code should be fine and it should work the same for the MatchingBox component as well. As a result of componentWillReceiveProps() not being fired, the chatid I passed to the MatchingWindow component was an empty string, which is problematic. I tried componentDidUpdate() and it did not work either.

Approach 2 (WaitingRoom)

```<code>class WaitingRoom extends Component {

      render() {

        return (

            ......All the same except for replacing the second Modal with:
            { this.state.showmatchingwindow ? <MatchingBox /> : null }

        );
      }
    }
</code>```

Approach 2 (MatchingBox)

```<code>class MatchingBox extends Component {

    state = {
        loading: true,
        chatid: "",
        buddy: []
    }

    componentDidMount() {
        console.log(this.props.loading);
        console.log(this.props.chatid);
        console.log(this.props.buddy);
        this.setState({
            loading: this.props.loading,
            chatid: this.props.chatid,
            buddy: this.props.buddy
        })
    }

    componentWillReceiveProps() {
        console.log(this.props.chatid);
        console.log(this.props.buddy);
        this.setState({
            loading: this.props.loading,
            chatid: this.props.chatid,
            buddy: this.props.buddy
            })
        }

    render() {
        let box;
        if (this.props.loading === true) {
            box = <div class="loader"></div>
        }
        else {
            if (this.props.buddy !== "") {
                box = <div>
                <MatchingWindow chatid={this.state.chatid} />
                </div>
            }
            else {
                box = <span>Sorry</span>
            }
        }
        return (
            <div>
                {box}
            </div>

        );
    }

}

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth,
        loading: state.auth.loading,
        chatid: state.auth.chatid,
        buddy: state.auth.buddy,
        profile: state.firebase.profile
    };
}

export default connect(mapStateToProps)(MatchingBox);
</code>```

As stated above, I am pretty sure my redux actions and reducer are fine but just want to make my description more understandable.

Redux actions

```<code>export const startMatching = (userid, userprofile, usergender, genderpreference) => (dispatch) => {

    dispatch({ type: MATCHING_REQUEST });

    ......

    dispatch(matchingConversation(userspool[number].id, doc.data(), userprofile, {time: "", from: "", content: ""}, number, userspool));
}

export const matchingConversation = (user2id, user2profile, user1profile, message, number, userspool) => (dispatch, getState) => {

      .....
                .then(() => {
                    dispatch({ type: CHAT_SUCCESS, payload: doc.id });
                })
                .then(() => {
                    dispatch({ type: MATCHING_SUCCESS, payload: user2id });
                })
}

</code>```

Redux reducer

```<code>const initialState = {
    loading: false,
    chatid: "",
    buddy: "",
}

const authReducer = (state = initialState, action) => {
    const {type, payload} = action;

    switch(type) {
        ......

        case CHAT_SUCCESS:
            return {
                ...state,
                chatid: action.payload
            }
        case MATCHING_REQUEST:
            return {
                ...state,
                loading: true
            }
        case MATCHING_SUCCESS:
            return {
                ...state,
                buddy: action.payload,
                loading: false
            }
        case MATCHING_FAIL:
            return {
                ...state,
                buddy: action.payload,
                loading: false
            }
        default: return state;
    }
}

</code>```

答:
You seem to be using a function to return the component:

```<code>// main.js
const WaitingRoomPage = () => {
  return <WaitingRoom />;
};

...

<Route path='/waitingroom' component={WaitingRoomPage} />
</code>```

I don't think you should be doing that because every re-render of Main will cause your WaitingRoom to keep remounting (and thus re-initializing). Your WaitingRoom is not a functional component, and even if it was, you should still just use the simpler way of declaring a Route with a component attribute:

```<code><Route path='/waitingroom' component={WaitingRoom} />
</code>```

Body:
Update to the original post: I have realized that the issue is that the updates in the Redux state (props to the WaitingRoom component) somehow set the entire state of the component to its initial state. Thus, "showmatchingwindow" was set to false as well. Initially, after MATCHING_REQUEST was dispatched and "loading" was set to true, the state of WaitingRoom component still remained unchanged. However, after MATCHING_SUCCESS was dispatched and "loading" turned false and "buddy" and "chatid" in the Redux state got updated, all the fields in the state of WaitingRoom were somehow reset to their initial values. This is weird and did not happen with my other Redux actions. I am wondering whether anyone can help me explain what caused this. Really appreciate your patience and any help you can offer!

Link to the Github repo: https://github.com/liu550/salon_project (WaitingRoom component is in src/components/waitingroom.js

///Below is the original post///

I am building a random matching feature for my website. Here is a brief description: I want a chat window to pop up once 2 users are successfully matched up. Inside my Redux state, I have (1) "loading," (2) "buddy" representing the id of the user that our current user is matched with, and (3) "chatid" representing the id of the firestore document that stores the chat history between 2 users. The startMatching Redux action is called in the WaitingRoom component which is a web page that displays other users' profiles in addition to having the matching button. The chat window is the MatchingWindow component, which needs a chatid as its props to render the corresponding chat history between 2 users.

I am sure that my Redux actions work fine but got problems when passing the updated Redux state to my React components. Below are 2 approaches that I tried:

Approach 1: Display the chat window inside a modal returned by the WaitingRoom component. As you can see, what I am doing here is just conditional rendering. However, with this approach, the modal somehow quickly showed up for less than a second and then disappeared along with the previous modal where users select their gender preferences. Checking the props to the WaitingRoom component, I found that "buddy" and "chatid" were indeed updated. Shouldn't MatchingWindow be rendered? I also tried just putting success> instead of the MatchingWindow component and it was the same outcome.

Approach 1 (WaitingRoom)

class WaitingRoom extends Component {

    state = {
      ......
    }

    showMatching = (e) => {
      e.preventDefault();
      this.setState({
        showmatching: true
      })
    }

    handleMatching = (e) => {
      e.preventDefault();
      this.props.startMatching(this.props.auth.uid, this.props.profile, this.props.profile.gender, this.state.genderpreference);
      this.setState({
        showmatchingwindow: true
      })
    }

    closeMatching = () => {
      this.setState({
        showmatching: false
      })
    }

      render() {

        const { auth, users, profile, loading, sent, buddy, chatid } = this.props;

        return (

            <Button variant="success" onClick={this.showMatching} style={{ fontSize: "large", fontFamily: "Comic Sans MS, cursive, sans-serif"}}>Randomly find a study/work buddy instantly!</Button>

            <Modal show={this.state.showmatching} onHide={this.closeMatching}>
              <Modal.Header closeButton></Modal.Header>
              <Modal.Body>
                <form onSubmit={this.handleMatching}>
                  Match me with:

                            Male only<input type="radio" id="genderpreference" value="Male" onChange={this.handleChange} checked={this.state.genderpreference === "Male"} />

                  ......

                  <button>Start matching</button>
                </form>
              </Modal.Body>
            </Modal>

            <Modal show={this.state.showmatchingwindow} onHide={this.closeMatching}>
              <Modal.Header closeButton></Modal.Header>
              <Modal.Body>
                { loading ?

 : null}
                { buddy !== "" && loading === false ? <MatchingWindow chatid=chatid /> : null }
                { buddy === "" && loading === false ? Sorry we cannot help you find a study/work buddy currently : null }
              </Modal.Body>
            </Modal>

        );
      }
    }

const mapStateToProps = (state) => {
  return {
    users: state.firestore.ordered.users,
    auth: state.firebase.auth,
    profile: state.firebase.profile,
    loading: state.auth.loading,
    sent: state.auth.sent,
    buddy: state.auth.buddy,
    chatid: state.auth.chatid
  }
}

export default compose(
connect(mapStateToProps, {submitTicket, startMatching, groupMessaging}),
firestoreConnect([
{ collection: 'users' }
])
)(WaitingRoom);

Approach 2: Create a separate MatchingBox component, which will render different elements/components based on different states. However, when I went with this approach, componentWillReceiveProps() was not fired after the Redux state changes, as the console.log()s I placed inside the method were not executed. It was weird because, as I mentioned in approach 1, the Redux state was indeed changed when I checked the props to the WaitingRoom component, which means that my Redux action and reducer code should be fine and it should work the same for the MatchingBox component as well. As a result of componentWillReceiveProps() not being fired, the chatid I passed to the MatchingWindow component was an empty string, which is problematic. I tried componentDidUpdate() and it did not work either.

Approach 2 (WaitingRoom)

class WaitingRoom extends Component {

      render() {

        return (

            ......All the same except for replacing the second Modal with:
            { this.state.showmatchingwindow ? <MatchingBox /> : null }

        );
      }
    }

Approach 2 (MatchingBox)

class MatchingBox extends Component {

    state = {
        loading: true,
        chatid: "",
        buddy: []
    }

    componentDidMount() {
        console.log(this.props.loading);
        console.log(this.props.chatid);
        console.log(this.props.buddy);
        this.setState({
            loading: this.props.loading,
            chatid: this.props.chatid,
            buddy: this.props.buddy
        })
    }

    componentWillReceiveProps() {
        console.log(this.props.chatid);
        console.log(this.props.buddy);
        this.setState({
            loading: this.props.loading,
            chatid: this.props.chatid,
            buddy: this.props.buddy
            })
        }

    render() {
        let box;
        if (this.props.loading === true) {
            box =

        }
        else {
            if (this.props.buddy !== "") {
                box =

                <MatchingWindow chatid={this.state.chatid} />

            }
            else {
                box = Sorry
            }
        }
        return (

                {box}

        );
    }

}

const mapStateToProps = (state) => {
    return {
        auth: state.firebase.auth,
        loading: state.auth.loading,
        chatid: state.auth.chatid,
        buddy: state.auth.buddy,
        profile: state.firebase.profile
    };
}

export default connect(mapStateToProps)(MatchingBox);

As stated above, I am pretty sure my redux actions and reducer are fine but just want to make my description more understandable.

Redux actions

export const startMatching = (userid, userprofile, usergender, genderpreference) => (dispatch) => {

    dispatch({ type: MATCHING_REQUEST });

    ......

    dispatch(matchingConversation(userspool[number].id, doc.data(), userprofile, {time: "", from: "", content: ""}, number, userspool));
}

export const matchingConversation = (user2id, user2profile, user1profile, message, number, userspool) => (dispatch, getState) => {

      .....
                .then(() => {
                    dispatch({ type: CHAT_SUCCESS, payload: doc.id });
                })
                .then(() => {
                    dispatch({ type: MATCHING_SUCCESS, payload: user2id });
                })
}

Redux reducer

const initialState = {
    loading: false,
    chatid: "",
    buddy: "",
}

const authReducer = (state = initialState, action) => {
    const {type, payload} = action;

    switch(type) {
        ......

        case CHAT_SUCCESS:
            return {
                ...state,
                chatid: action.payload
            }
        case MATCHING_REQUEST:
            return {
                ...state,
                loading: true
            }
        case MATCHING_SUCCESS:
            return {
                ...state,
                buddy: action.payload,
                loading: false
            }
        case MATCHING_FAIL:
            return {
                ...state,
                buddy: action.payload,
                loading: false
            }
        default: return state;
    }
}

Body:
You seem to be using a function to return the component:

// main.js
const WaitingRoomPage = () => {
  return <WaitingRoom />;
};

...

<Route path='/waitingroom' component={WaitingRoomPage} />

I don't think you should be doing that because every re-render of Main will cause your WaitingRoom to keep remounting (and thus re-initializing). Your WaitingRoom is not a functional component, and even if it was, you should still just use the simpler way of declaring a Route with a component attribute:

<Route path='/waitingroom' component={WaitingRoom} />


来源: stackexchange

问:
Chart.js, how to reduce space between labels and bars (horizontal bar chart)

I am trying to find an option within chart.js that allows me to modify the space between bars and labels, but so far have been unsuccessful. I have tried the options under https://www.chartjs.org/docs/latest/charts/bar.html.

答:
You can use ticks.padding to define the offset of the tick labels from the axis. In you case, it needs to be defined inside the options.scales.yAxis as follows:

```<code>options: {
  scales: {
    yAxes: [{
      gridLines: {
        drawTicks: false
      },
      ticks: {
        padding: 5
      }
    }],
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use ticks.padding to define the offset of the tick labels from the axis. In you case, it needs to be defined inside the options.scales.yAxis as follows:

options: {
  scales: {
    yAxes: [{
      gridLines: {
        drawTicks: false
      },
      ticks: {
        padding: 5
      }
    }],


问:
git commit error: pathspec 'xxx' did not match any file(s) known to git
I wrote a bash script to update my files through git automatically, but I keep getting error for the git commit line, if my message contains error.

I have already wrapped my message with quote, what's wrong here?

My bash script:

```<code>##Handle local git update
remote='
cd express-demo-nonbare;
git pull origin master;
';

echo "Process for updating Git begin";
git add . ;
read -p "Message for this commit: " comment;
comment=\"${comment}\";
echo $comment;
git commit --message=$comment;
git push backup master;
</code>```

答:
You don't want to, as you put it:

wrap... my message with quote

(which is indeed what you are doing).  Instead, you want to protect your message from having bash treat it as a list of words.  To do that, you need quotes, but in a different position:

remote='
cd express-demo-nonbare;
git pull origin master;
'

echo "Process for updating Git begin"
git add .
read -p "Message for this commit: " comment
echo "$comment"
git commit --message="$comment"
git push backup master
```

<p>I removed all non-essential semicolons as well (bash treats the end of a line as the end of the command, unless something like an unclosed parenthesis or brace prevents this).</p>

<p>It's not clear to me what your intent is in setting the variable <code>remote</code> to the literal string <kbd>newline</kbd><kbd>c</kbd><kbd>d</kbd><kbd>space</kbd><kbd>e</kbd><kbd>x</kbd>...<kbd>;</kbd><kbd>newline</kbd>, especially since <code>$remote</code> does not occur later in the script.  Note, however, that since this string does include white-space, expanding it <em>outside</em> quotes, as in <code>$remote</code> (vs <code>"$remote"</code> which expands it inside quotes) can trigger further shell actions.  For instance:</p>

```foo='this; that'
wc $foo
```

<p>will have the <code>wc</code> program attempt to open files named <code>this;</code> and <code>that</code>, having split <code>$foo</code> at the white spaces into separate words that are then passed to <code>wc</code>.  This splitting is actually based on <code>$IFS</code>:</p>

```IFS=+
foo='this+that'
wc $foo
```

<p>tries to open files named <code>this</code> and <code>that</code>.  Restoring IFS to its normal setting:</p>

```wc $foo
```

<p>tries to open one file named <code>this+that</code>.</p>

<p>(I sometimes use <code>wc</code> as a program to help show what the actual arguments were, since it tries to open each one as a file name, and spits out the actual file name in any subsequent error message or count.)</p>

<p>Similarly, if the expansion of a variable produces shell glob metacharacters, these will be evaluated after the expansion:</p>

```foo='*'
wc $foo
```

<p>will try to open and read every file and directory in the current directory.  Again, double quotes will protect against this:</p>

```wc "$foo"
```

will only try to open and read one file, named *.

Body:
I wrote a bash script to update my files through git automatically, but I keep getting error for the git commit line, if my message contains error.

I have already wrapped my message with quote, what's wrong here?

My bash script:

##Handle local git update
remote='
cd express-demo-nonbare;
git pull origin master;
';

echo "Process for updating Git begin";
git add . ;
read -p "Message for this commit: " comment;
comment=\"${comment}\";
echo $comment;
git commit --message=$comment;
git push backup master;

Body:
You don't want to, as you put it:

wrap... my message with quote

(which is indeed what you are doing).  Instead, you want to protect your message from having bash treat it as a list of words.  To do that, you need quotes, but in a different position:

remote='
cd express-demo-nonbare;
git pull origin master;
'

echo "Process for updating Git begin"
git add .
read -p "Message for this commit: " comment
echo "$comment"
git commit --message="$comment"
git push backup master

I removed all non-essential semicolons as well (bash treats the end of a line as the end of the command, unless something like an unclosed parenthesis or brace prevents this).

It's not clear to me what your intent is in setting the variable remote to the literal string newlinecdspaceex...;newline, especially since $remote does not occur later in the script.  Note, however, that since this string does include white-space, expanding it outside quotes, as in $remote (vs "$remote" which expands it inside quotes) can trigger further shell actions.  For instance:

foo='this; that'
wc $foo

will have the wc program attempt to open files named this; and that, having split $foo at the white spaces into separate words that are then passed to wc.  This splitting is actually based on $IFS:

IFS=+
foo='this+that'
wc $foo

tries to open files named this and that.  Restoring IFS to its normal setting:

wc $foo

tries to open one file named this+that.

(I sometimes use wc as a program to help show what the actual arguments were, since it tries to open each one as a file name, and spits out the actual file name in any subsequent error message or count.)

Similarly, if the expansion of a variable produces shell glob metacharacters, these will be evaluated after the expansion:

foo='*'
wc $foo

will try to open and read every file and directory in the current directory.  Again, double quotes will protect against this:

wc "$foo"

will only try to open and read one file, named *.


问:
Create Max and Min column values from a single column value pandas
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

```<code>Kg
0.5
0.5
1
1
1
2
2
5
5
5
</code>```

Expected Output

```<code>Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5
</code>```

How can this be done in pandas ?

Body:
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

Kg
0.5
0.5
1
1
1
2
2
5
5
5

Expected Output

Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5

How can this be done in pandas ?

Body:
Assuming your kg column is sorted:

s = df["Kg"].unique()
df["Kg_from"] = df["Kg"].map({k:v for k,v in zip(s[1:], s)}).fillna(0)
print (df)

    Kg  Kg_from
0  0.5      0.0
1  0.5      0.0
2  1.0      0.5
3  1.0      0.5
4  1.0      0.5
5  2.0      1.0
6  2.0      1.0
7  5.0      2.0
8  5.0      2.0
9  5.0      2.0


问:
TSQL to get missing records inside IN operator
I have a table like below in SQL Server:

```<code>create table address (id int, city varchar(10));

insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');
</code>```

I'm writing a query with the IN operator as

```<code>SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')
</code>```

I can get the result, but I want to get the list of missing or not available records in the table like

```<code>|  City  |  Status   |
+--------+-----------+
| Rome   | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing   |
| Delhi  | Missing   |
+--------+-----------+
</code>```

答:
With CTE :</p>

```<code>with CitySearch (city) as (
select 'Rome' union all
select 'Mumbai'  union all
select 'Dallas'  union all
select 'Delhi'  union all
select 'Moscow'
)
select t1.city,
case when t2.city is null then 'Missing' else 'Available' end Status
from CitySearch t1
left outer join address t2 on t1.city=t2.city
order by 2
</code>```

Body:
I have a table like below in SQL Server:

create table address (id int, city varchar(10));

insert into address values (1, 'Rome');
insert into address values (2, 'Dallas');
insert into address values (3, 'Cracow');
insert into address values (4, 'Moscow');
insert into address values (5, 'Liverpool');
insert into address values (6, 'Cracow');
insert into address values (7, 'Seoul');

I'm writing a query with the IN operator as

SELECT City
FROM address
WHERE city IN ('Rome', 'Mumbai', 'Dallas', 'Delhi', 'Moscow')

I can get the result, but I want to get the list of missing or not available records in the table like

|  City  |  Status   |
+--------+-----------+
| Rome   | Available |
| Dallas | Available |
| Moscow | Available |
| Mumbai | Missing   |
| Delhi  | Missing   |
+--------+-----------+

Body:
With CTE :

with CitySearch (city) as (
select 'Rome' union all
select 'Mumbai'  union all
select 'Dallas'  union all
select 'Delhi'  union all
select 'Moscow'
)
select t1.city,
case when t2.city is null then 'Missing' else 'Available' end Status
from CitySearch t1
left outer join address t2 on t1.city=t2.city
order by 2


问:
org.elasticsearch.client.RequestOptions is only dependency not found in elasticsearch client
For some bizarre reason, the following import is not being found by maven. I am not sure if it's removed from the dependency I get from maven or not. Could I please get a look at why it's not being found

```<code>import org.elasticsearch.client.RequestOptions;
</code>```

I am using elastic version 6.3.2 with the high-level JAVA REST client as 6.3.2 also. My POM looks like this below.

```<code>         <dependency>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-high-level-client</artifactId>
                    <version>6.3.2</version>
                </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.3.2</version>
        </dependency>
</code>```

答:
RequestOptions was introduced in version 6.4 of the Rest High-Level client.

So you need to upgrade your client to 6.4.0 at least. That version might work with ES 6.3.2 but there might be some incompatibility issues as only forward compatibility is guaranteed.

The High Level Client is guaranteed to be able to communicate with any Elasticsearch node running on the same major version and greater or equal minor version.

Body:
For some bizarre reason, the following import is not being found by maven. I am not sure if it's removed from the dependency I get from maven or not. Could I please get a look at why it's not being found

import org.elasticsearch.client.RequestOptions;

I am using elastic version 6.3.2 with the high-level JAVA REST client as 6.3.2 also. My POM looks like this below.

         <dependency>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-high-level-client</artifactId>
                    <version>6.3.2</version>
                </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.3.2</version>
        </dependency>


问:
Difficulties documenting enum classes?
I'm trying to document a module I'm maintaining, and I'm finding it very difficult to get my enum classes documented properly. For instance, here's one that I'd like to document properly (source):

```<code>class QOSLevel(Enum):
    '''Quality of service levels'''

    #: 500ms (fastest available)
    EXPRESS = '0'

    #: 750ms
    REAL_TIME = '1'

    #: 1000ms
    FAST = '2'

    #: 1500ms
    MODERATE = '3'

    #: 3000ms
    SLOW = '4'

    #: 5000ms
    DELAYED = '5'
</code>```

My documentation for this is here (source):

```<code>.. autoclass:: tda.streaming.StreamClient.QOSLevel
  :members:
  :undoc-members:
  :member-order: bysource
</code>```

The output looks like this:

Two things are immediately wrong here:

First off, the documentation strings I set are not rendering. I've attempted to follow some advice I've received before that worked for generic attributes, but it seems enums are somehow handled differently?

Secondly, it seems the :member-order: bysource directive is being ignored. I tried setting this both here and in conf.py, and neither place seems to allow the fields to be emitted in the proper order.

I'm using sphinx v3.0.4 for what it's worth. You can try to replicate the error by copy-pasting the following into your terminal:

```<code>git clone https://github.com/alexgolec/tda-api.git
cd tda-api
git checkout remotes/origin/autodoc-bysource-not-working
virtualenv -v virtualenv
source virtualenv/bin/activate
pip install -r requirements.txt
make -f Makefile.sphinx html
open docs-build/html/streaming.html  # Only works on Mac OS
</code>```

答:
The problem is that the QOSLevel class is nested inside the StreamClient class. The following works (note the colons):

.. autoclass:: tda.streaming::StreamClient.QOSLevel
```

See How to document nested classes with Sphinx's autodoc?.

Title: Difficulties documenting enum classes?

Body:
I'm trying to document a module I'm maintaining, and I'm finding it very difficult to get my enum classes documented properly. For instance, here's one that I'd like to document properly (source):

class QOSLevel(Enum):
    '''Quality of service levels'''

    #: 500ms (fastest available)
    EXPRESS = '0'

    #: 750ms
    REAL_TIME = '1'

    #: 1000ms
    FAST = '2'

    #: 1500ms
    MODERATE = '3'

    #: 3000ms
    SLOW = '4'

    #: 5000ms
    DELAYED = '5'

My documentation for this is here (source):

.. autoclass:: tda.streaming.StreamClient.QOSLevel
  :members:
  :undoc-members:
  :member-order: bysource

The output looks like this:

Two things are immediately wrong here:

First off, the documentation strings I set are not rendering. I've attempted to follow some advice I've received before that worked for generic attributes, but it seems enums are somehow handled differently?

Secondly, it seems the :member-order: bysource directive is being ignored. I tried setting this both here and in conf.py, and neither place seems to allow the fields to be emitted in the proper order.

I'm using sphinx v3.0.4 for what it's worth. You can try to replicate the error by copy-pasting the following into your terminal:

git clone https://github.com/alexgolec/tda-api.git
cd tda-api
git checkout remotes/origin/autodoc-bysource-not-working
virtualenv -v virtualenv
source virtualenv/bin/activate
pip install -r requirements.txt
make -f Makefile.sphinx html
open docs-build/html/streaming.html  # Only works on Mac OS

Body:
The problem is that the QOSLevel class is nested inside the StreamClient class. The following works (note the colons):

.. autoclass:: tda.streaming::StreamClient.QOSLevel

See How to document nested classes with Sphinx's autodoc?.


问:
Is it a way to stop printing AmqpRejectAndDontRequeueException stacktrace logs in spring boot?
I am trying to setup dead-letter-queue in spring boot app but when I am throwing  AmqpRejectAndDontRequeueException, it's print whole stack trace in the console which I don't want.
Is there any better way to do it?

I have tried to catch that exception but after that dead-letter-queue stopped working.

```<code>2019-06-25 17:26:33.221  WARN 19812 --- [ntContainer#0-1] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener method 'public void com.example.consumer.Consumer.process(com.example.consumer.api.PaymentOrder)' threw exception
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:198) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:127) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1552) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1478) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1466) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:1461) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1410) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:870) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:854) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1600(SimpleMessageListenerContainer.java:78) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.mainLoop(SimpleMessageListenerContainer.java:1137) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1043) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
Caused by: com.example.consumer.InsufficientFundsException: insufficient funds on account XK45 0654 5271 7424 1755
    at com.example.consumer.Consumer.process(Consumer.java:28) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:171) ~[spring-messaging-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:120) ~[spring-messaging-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:49) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:190) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    ... 12 common frames omitted
</code>```

It should be on one line with one message of error description and dead-letter-queue should work.

答:
You should look at the logs and see what class is printing the exception. in your logs you can see that  org.springframework.amqp.rabbit.listener.ConditionalRejectingErrorHandler is the source of the exception so like Rajesh mentionned above setin the logs to OFF should work. in my case I had to set org.springframework.integration.handler.LoggingHandler to OFF</p>

```<code>logging.level:
    org.springframework.integration.handler.LoggingHandler: OFF
</code>```

Body:
I am trying to setup dead-letter-queue in spring boot app but when I am throwing  AmqpRejectAndDontRequeueException, it's print whole stack trace in the console which I don't want.
Is there any better way to do it?

I have tried to catch that exception but after that dead-letter-queue stopped working.

2019-06-25 17:26:33.221  WARN 19812 --- [ntContainer#0-1] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener method 'public void com.example.consumer.Consumer.process(com.example.consumer.api.PaymentOrder)' threw exception
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:198) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:127) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1552) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1478) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1466) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:1461) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1410) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:870) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:854) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1600(SimpleMessageListenerContainer.java:78) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.mainLoop(SimpleMessageListenerContainer.java:1137) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1043) [spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
Caused by: com.example.consumer.InsufficientFundsException: insufficient funds on account XK45 0654 5271 7424 1755
    at com.example.consumer.Consumer.process(Consumer.java:28) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:171) ~[spring-messaging-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:120) ~[spring-messaging-5.1.7.RELEASE.jar:5.1.7.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:49) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:190) ~[spring-rabbit-2.1.6.RELEASE.jar:2.1.6.RELEASE]
    ... 12 common frames omitted

It should be on one line with one message of error description and dead-letter-queue should work.

Body:
You should look at the logs and see what class is printing the exception. in your logs you can see that  org.springframework.amqp.rabbit.listener.ConditionalRejectingErrorHandler is the source of the exception so like Rajesh mentionned above setin the logs to OFF should work. in my case I had to set org.springframework.integration.handler.LoggingHandler to OFF

logging.level:
    org.springframework.integration.handler.LoggingHandler: OFF


问:
Python updated political map of India with state boundaries
Can anyone help me with plotting the most recent political map of India which also includes state boundaries?
The default maps in basemap or cartopy does not include the disputed areas and state boundaries.
My present code is </p>

```<code>import cartopy as ccrs
import matplotlib.pyplot as plt
import cartopy.feature as cfeature
fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.crs.PlateCarree()))
ax.set_extent([67.0, 98.0, 5.0, 38.0])
gl = ax.gridlines(crs=ccrs.crs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='gray', alpha=0.5,
                  linestyle='--')
gl.xlabels_top = False
gl.ylabels_right = False
ax.coastlines(color='black', linewidth=1, resolution='10m')
ax.add_feature(cfeature.BORDERS.with_scale('10m'),
               linestyle='-', alpha=.5)
</code>```

答:
you can use

```<code>ax.add_feature(cfeature.STATES.with_scale('10m'),
               linestyle='-', alpha=.5, color='red')
</code>```

to draw states boundaries, but this will draw all countries states.

Note: Strangely enough, when using scale '50m', only US, Brazil and Australia states are draw.

If you need country specific data, the best way is to download a shapefile from GADM. After downloading and unzipping the India file, you can plot like this:

```<code>import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import cartopy.feature as cfeature
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([67.0, 98.0, 5.0, 38.0])
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='gray', alpha=0.5,
                  linestyle='--')
gl.xlabels_top = False
gl.ylabels_right = False
ax.coastlines(color='black', linewidth=1, resolution='10m')
ax.add_feature(cfeature.BORDERS.with_scale('50m'),
               linestyle='-', alpha=.5)

# ax.add_feature(cfeature.STATES.with_scale('10m'),
#                linestyle='-', alpha=.5, color='red')

fname = '/tmp/india/gadm36_IND_1.shp'
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                               ccrs.PlateCarree(), edgecolor='red')
ax.add_feature(shape_feature)
</code>```

_0 is country level, _1 is state level and so on. But I have no idea how disputed areas are presented.

Body:
Can anyone help me with plotting the most recent political map of India which also includes state boundaries?
The default maps in basemap or cartopy does not include the disputed areas and state boundaries.
My present code is

import cartopy as ccrs
import matplotlib.pyplot as plt
import cartopy.feature as cfeature
fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.crs.PlateCarree()))
ax.set_extent([67.0, 98.0, 5.0, 38.0])
gl = ax.gridlines(crs=ccrs.crs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='gray', alpha=0.5,
                  linestyle='--')
gl.xlabels_top = False
gl.ylabels_right = False
ax.coastlines(color='black', linewidth=1, resolution='10m')
ax.add_feature(cfeature.BORDERS.with_scale('10m'),
               linestyle='-', alpha=.5)

Body:
you can use

ax.add_feature(cfeature.STATES.with_scale('10m'),
               linestyle='-', alpha=.5, color='red')

to draw states boundaries, but this will draw all countries states.

Note: Strangely enough, when using scale '50m', only US, Brazil and Australia states are draw.

If you need country specific data, the best way is to download a shapefile from GADM. After downloading and unzipping the India file, you can plot like this:

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import cartopy.feature as cfeature
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

fig, ax = plt.subplots(subplot_kw=dict(projection=ccrs.PlateCarree()))
ax.set_extent([67.0, 98.0, 5.0, 38.0])
gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                  linewidth=1, color='gray', alpha=0.5,
                  linestyle='--')
gl.xlabels_top = False
gl.ylabels_right = False
ax.coastlines(color='black', linewidth=1, resolution='10m')
ax.add_feature(cfeature.BORDERS.with_scale('50m'),
               linestyle='-', alpha=.5)

# ax.add_feature(cfeature.STATES.with_scale('10m'),
#                linestyle='-', alpha=.5, color='red')

fname = '/tmp/india/gadm36_IND_1.shp'
shape_feature = ShapelyFeature(Reader(fname).geometries(),
                               ccrs.PlateCarree(), edgecolor='red')
ax.add_feature(shape_feature)

_0 is country level, _1 is state level and so on. But I have no idea how disputed areas are presented.


问:
Does this method cause concurrency problems?
I have a CoreDataUtilities class with a class method that saves a managed object context and takes care of any errors:

```<code>+ (void)saveContext:(NSManagedObjectContext*)moc {
    NSError *error = nil;
    if (moc != nil) {
        if ([moc hasChanges] && ![moc save:&error]) {
            NSLog(@"MOC save error: %@, %@", error, [error userInfo]);
        }
    }
}
</code>```

I call this method from NSOperation subclasses and background threads, and pass in the NSManagedObjectContext instance of the thread / NSOperation.

My concern is this:

If Thread A calls this method, and while this method is executing half-way, Thread B calls it too. With another MOC of course. Woul this interfere in any way? From my point of view it would not, because this method does only communicate with the MOC instance which is "private" or "owned" by the calling Thread anyways. But what irritates me is if even local variables in a method get "mixed up" when multiple threads execute the same piece of code at the same time. Or does every variable have their own "context" in a new thread, with it's own heap (or stack, for that matter) of memory?

Does it make a big difference if I put this saving code directly into the NSOperation subclasses and background threads? Why?

答:
Why don't you put a @synchronize(...) block around the save operation. This will ensure that a managed object context won't be saved if it's already saving.

```<code>+ (void)saveContext:(NSManagedObjectContext*)moc {
    if (moc == nil) return;

    @synchronized(moc)
    {
        NSError *error = nil;
        if ([moc hasChanges] && ![moc save:&error])
            NSLog(@"MOC save error: %@, %@", error, [error userInfo]);
    }
}
</code>```

Read here on synchronization.

ContentLicense: CC BY-SA 3.0

Body:
I have a CoreDataUtilities class with a class method that saves a managed object context and takes care of any errors:

+ (void)saveContext:(NSManagedObjectContext*)moc {
    NSError *error = nil;
    if (moc != nil) {
        if ([moc hasChanges] && ![moc save:&error]) {
            NSLog(@"MOC save error: %@, %@", error, [error userInfo]);
        }
    }
}

I call this method from NSOperation subclasses and background threads, and pass in the NSManagedObjectContext instance of the thread / NSOperation.

My concern is this:

If Thread A calls this method, and while this method is executing half-way, Thread B calls it too. With another MOC of course. Woul this interfere in any way? From my point of view it would not, because this method does only communicate with the MOC instance which is "private" or "owned" by the calling Thread anyways. But what irritates me is if even local variables in a method get "mixed up" when multiple threads execute the same piece of code at the same time. Or does every variable have their own "context" in a new thread, with it's own heap (or stack, for that matter) of memory?

Does it make a big difference if I put this saving code directly into the NSOperation subclasses and background threads? Why?

Body:
Why don't you put a @synchronize(...) block around the save operation. This will ensure that a managed object context won't be saved if it's already saving.

+ (void)saveContext:(NSManagedObjectContext*)moc {
    if (moc == nil) return;

    @synchronized(moc)
    {
        NSError *error = nil;
        if ([moc hasChanges] && ![moc save:&error])
            NSLog(@"MOC save error: %@, %@", error, [error userInfo]);
    }
}

Read here on synchronization.


问:
Docker MySQL connection DBeaver
I just finished following this Docker tutorial on youtube:

https://www.youtube.com/watch?v=SXY0MLHP3hA&lc=Ugzp3vKtSOp0rn2lYyd4AaABAg

I was able to create a couple of Docker containers for PHP and MySQL.  The file structure is as follows:

```<code>>Docker_PHP_MySQL
 >DB
   -Dockerfile
 >src
   -index.php
 >www
   -Dockerfile
 development.env
 docker-compose.yml
</code>```

The DB Dockerfile:

```<code>FROM mysql:8.0
</code>```

index.php:

```<code><?php
$mysqli = new mysqli('tut07-db', getenv('MYSQL_USER'), getenv('MYSQL_PASSWORD'), 'information_schema');
if($mysqli->connect_error)
{
  echo 'Connection Error [', $mysqli->connect_errno, ']: ', $mysqli->connect_error;
}
else
{
  echo 'MySQLi Connected Successfully!';
}
?>
</code>```

The www Dockerfile:

```<code>FROM php:7.2-apache

RUN docker-php-ext-install mysqli
RUN docker-php-ext-enable mysqli
</code>```

Here is the development.env file:

```<code>MYSQL_USER=sys_admin
MYSQL_PASSWORD=sys_password
MYSQL_ROOT_PASSWORD=root_password
</code>```

And then finally, the docker-compose.yml file:

```<code>version: "3"

networks:
  tut07-frontend:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.10.1.0/24
  tut07-backend:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.10.2.0/23

services:
  tut07-db:
    build: ./db
    command: --default-authentication-plugin=mysql_native_password
    ports:
      - 3306:3306
    networks:
      tut07-backend:
        ipv4_address: 172.10.3.2
    env_file:
      - ./development.env
  tut07-www:
    build: ./www
    ports:
      - 8080:80
    volumes:
      - ./src:/var/www/html/
    networks:
      tut07-backend:
        ipv4_address: 172.10.2.2
      tut07-frontend:
        ipv4_address: 172.10.1.2
    depends_on:
      - tut07-db
    env_file:
      - ./development.env
</code>```

Now here's where I know I'm going in completely blind...

In dbeaver, I'm trying to establish a connection:

But when I test the connection, I get the following response:

How do I fix this problem?

答:
In my case I was using DBBeaver to connect to MariaDB on port 3306 however my container port was not mapped to my local 3306 port so I just needed to add the ports config into the docker-compose.yml</p>

```<code>ports:
- "3306:3306"
</code>```

Title: Docker MySQL connection DBeaver

Body:
I just finished following this Docker tutorial on youtube:

https://www.youtube.com/watch?v=SXY0MLHP3hA&lc=Ugzp3vKtSOp0rn2lYyd4AaABAg

I was able to create a couple of Docker containers for PHP and MySQL.  The file structure is as follows:

>Docker_PHP_MySQL
 >DB
   -Dockerfile
 >src
   -index.php
 >www
   -Dockerfile
 development.env
 docker-compose.yml

The DB Dockerfile:

FROM mysql:8.0

index.php:

<?php
$mysqli = new mysqli('tut07-db', getenv('MYSQL_USER'), getenv('MYSQL_PASSWORD'), 'information_schema');
if($mysqli->connect_error)
{
  echo 'Connection Error [', $mysqli->connect_errno, ']: ', $mysqli->connect_error;
}
else
{
  echo 'MySQLi Connected Successfully!';
}
?>

The www Dockerfile:

FROM php:7.2-apache

RUN docker-php-ext-install mysqli
RUN docker-php-ext-enable mysqli

Here is the development.env file:

MYSQL_USER=sys_admin
MYSQL_PASSWORD=sys_password
MYSQL_ROOT_PASSWORD=root_password

And then finally, the docker-compose.yml file:

version: "3"

networks:
  tut07-frontend:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.10.1.0/24
  tut07-backend:
    driver: bridge
    ipam:
      driver: default
      config:
        - subnet: 172.10.2.0/23

services:
  tut07-db:
    build: ./db
    command: --default-authentication-plugin=mysql_native_password
    ports:
      - 3306:3306
    networks:
      tut07-backend:
        ipv4_address: 172.10.3.2
    env_file:
      - ./development.env
  tut07-www:
    build: ./www
    ports:
      - 8080:80
    volumes:
      - ./src:/var/www/html/
    networks:
      tut07-backend:
        ipv4_address: 172.10.2.2
      tut07-frontend:
        ipv4_address: 172.10.1.2
    depends_on:
      - tut07-db
    env_file:
      - ./development.env

Now here's where I know I'm going in completely blind...

In dbeaver, I'm trying to establish a connection:

But when I test the connection, I get the following response:

How do I fix this problem?

Body:
In my case I was using DBBeaver to connect to MariaDB on port 3306 however my container port was not mapped to my local 3306 port so I just needed to add the ports config into the docker-compose.yml

ports:
- "3306:3306"


问:
C++ argument of type is incompatible with parameter of type void (__cdecl*)(void), when calling std::atexit()
While using certain C++ libraries, I've often come across functions with parameters requiring pointers to functions. This implies methods won't be accepted.

Such as std's atexit(void (__cdecl*)(void));

In this case, it's very inconvenient to call such function from a class, when you'd like to pass the functionality from a method.

I know of these two workarounds, but they have drawbacks/seem impossible:

Declaring the method as static: Means that method can't call any
other non-static methods from the same class.

Passing an actual function: Is an absolute mess, and may require all
sorts of black magic to get the propper functionality to execute
within the method.

What other workarounds are there for these situations in general? Or at least for calling the atexit() example from a class where a method would be ideal as exit function.

答:
atexit functions are called on program exit, in reverse order. Local static object destructors are also called at this point. So in this example:

```<code>void f()
{
  static X x;
  atexit(f1);
  static Y y;
}
</code>```

On first call x and y destructor would be registered to be called on program exit, and f1() would be called between y.Y::~Y() and x.X::~X().

So if you create a collection of std::function objects to be called on destruction of the collection, that may be a viable workaround.

It still may not work well for multiple functions, as all would be called in a single loop, instead of LIFO order relative to other static destructor / atexit call.

Another option could be to look at at_thread_exit. It has different semantic, but may suit your needs as well.

Thunk, mentioned by @Remy Lebeau, could be the best workaround. But it may be nontrivial to implement, that's why I suggest considering other workarounds as well.

Body:
atexit functions are called on program exit, in reverse order. Local static object destructors are also called at this point. So in this example:

void f()
{
  static X x;
  atexit(f1);
  static Y y;
}

On first call x and y destructor would be registered to be called on program exit, and f1() would be called between y.Y::~Y() and x.X::~X().

So if you create a collection of std::function objects to be called on destruction of the collection, that may be a viable workaround.

It still may not work well for multiple functions, as all would be called in a single loop, instead of LIFO order relative to other static destructor / atexit call.

Another option could be to look at at_thread_exit. It has different semantic, but may suit your needs as well.

Thunk, mentioned by @Remy Lebeau, could be the best workaround. But it may be nontrivial to implement, that's why I suggest considering other workarounds as well.


问:
Segmentation Fault: CS50 recover.c
This program accepts a filename as input and should recover all jpegs on that file. It reads 512 bytes at a time, checking for the start of a new jpeg.

The program compiles when I run it, but it gives a segmentation fault. Please advise me how I can go about fixing this.

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

int main(int argc, char *argv[])
{
    // check for proper usage
    if (argc != 2)
    {
        printf("Usage: 1 command line argument\n");
        return 1;
    }

    // check if file can be opened
    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        printf("Cannot be opened\n");
        return 2;
    }

    // read 512 bytes into buffer until end of card
    int buffer[128];
    int counter;
    counter = 0;
    char filename[8];
    FILE *img = NULL;

    while(fread(buffer, 4, 128, file) == 128)
    {
        //check if start of new JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            //check if first JPEG
            if (counter == 0)
            {
                sprintf(filename, "%03i.jpg", counter);
                img = fopen(filename, "w");
                fwrite(buffer, 4, 128, img);
                counter += 1;
            }
            else if (counter > 0)
            {
                fclose(img);
                sprintf(filename, "%03i.jpg", counter);
                img = fopen(filename, "w");
                fwrite(buffer, 4, 128, img);
                counter += 1;
            }
        }
        else if (counter > 0)
        {
            fwrite(buffer, 4, 128, img);
        }
    }
    fclose(img);
    fclose(file);
    return 0;
}
</code>```

答:
fclose(img) is the culprit. img is NULL. In order to find out why, you can insert some printf after your fopen.  Here is the link to debug any segfaults in the future.

```<code>$ ./recover card.raw

  Memory access error: invalid parameter; abort execution.
  # fclose's parameter (0x0) is not a valid FILE pointer.
  # Stack trace (most recent call first) of the error.
  # [0]  file:/recover.c::55, 5
  # [1]  [libc-start-main]
</code>```

Title: Segmentation Fault: CS50 recover.c

Body:
This program accepts a filename as input and should recover all jpegs on that file. It reads 512 bytes at a time, checking for the start of a new jpeg.

The program compiles when I run it, but it gives a segmentation fault. Please advise me how I can go about fixing this.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    // check for proper usage
    if (argc != 2)
    {
        printf("Usage: 1 command line argument\n");
        return 1;
    }

    // check if file can be opened
    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        printf("Cannot be opened\n");
        return 2;
    }

    // read 512 bytes into buffer until end of card
    int buffer[128];
    int counter;
    counter = 0;
    char filename[8];
    FILE *img = NULL;

    while(fread(buffer, 4, 128, file) == 128)
    {
        //check if start of new JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            //check if first JPEG
            if (counter == 0)
            {
                sprintf(filename, "%03i.jpg", counter);
                img = fopen(filename, "w");
                fwrite(buffer, 4, 128, img);
                counter += 1;
            }
            else if (counter > 0)
            {
                fclose(img);
                sprintf(filename, "%03i.jpg", counter);
                img = fopen(filename, "w");
                fwrite(buffer, 4, 128, img);
                counter += 1;
            }
        }
        else if (counter > 0)
        {
            fwrite(buffer, 4, 128, img);
        }
    }
    fclose(img);
    fclose(file);
    return 0;
}

Body:
fclose(img) is the culprit. img is NULL. In order to find out why, you can insert some printf after your fopen.  Here is the link to debug any segfaults in the future.

$ ./recover card.raw

  Memory access error: invalid parameter; abort execution.
  # fclose's parameter (0x0) is not a valid FILE pointer.
  # Stack trace (most recent call first) of the error.
  # [0]  file:/recover.c::55, 5
  # [1]  [libc-start-main]


问:
Regex match file path with or without space
I am trying to match a path which may contains space and therefore be entered with quote:

```<code>\-inputfile\s*=\s*'?(.*?)(?=\/|\s|'|\||$)
</code>```

I basically would like to match a string starting with -inputfile= followed by a path between '' or not and stop the match if /,|,or a space or end of line is found.

I ma not sure how to specify hat if the path starts with ' then spaces are allowed and then the match should stop at the next '.

The regex examples are here.

答:
If i understand from your regex examples correctly, you want to detect all occurrences below:

-inputFile=path/without/space

-inputFile='path   with/space'

-inputFile='path/with/single/quotation

You can use:

\-inputfile=(('.*')|([^\s]*))
```

<p><em><strong>More information:</strong></em></p>

<p><em>The <code>('.*')</code> part matches all characters between single quotes(') and the <code>([^\s]*)</code> part will match all characters except space. You need to specify it before <code>([^\s]*)</code> part in order to detect 3. occurrence.</em></p>

<p><em><strong>Much more information:</strong></em></p>

<p><em>If you do not want to regex to be matched against 3. occurrence (I'm writing it because it is a weird thing to detect) you can simply add single quote to excluded section like that:</em></p>

<pre class="lang-sh prettyprint-override"><code>\-inputfile=(('.*')|([^'\s]*))
</code>```

Body:
I am trying to match a path which may contains space and therefore be entered with quote:

\-inputfile\s*=\s*'?(.*?)(?=\/|\s|'|\||$)

I basically would like to match a string starting with -inputfile= followed by a path between '' or not and stop the match if /,|,or a space or end of line is found.

I ma not sure how to specify hat if the path starts with ' then spaces are allowed and then the match should stop at the next '.

The regex examples are here.

Body:
If i understand from your regex examples correctly, you want to detect all occurrences below:

-inputFile=path/without/space

-inputFile='path   with/space'

-inputFile='path/with/single/quotation

You can use:

\-inputfile=(('.*')|([^\s]*))

More information:

The ('.*') part matches all characters between single quotes(') and the ([^\s]*) part will match all characters except space. You need to specify it before ([^\s]*) part in order to detect 3. occurrence.

Much more information:

If you do not want to regex to be matched against 3. occurrence (I'm writing it because it is a weird thing to detect) you can simply add single quote to excluded section like that:

\-inputfile=(('.*')|([^'\s]*))


问:
call a php function from jquery
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:

JQUERY:

```<code>$.ajax({
    type: "POST",
    url: post_url,
    success: function(group) //we're calling the response json array 'tree'
    {
        //WANT TO CALL THE PHP FUNCTION HERE
    } //end success
 }); //end AJAX
</code>```

PHP:

```<code><?php
foreach($groups as $group){
    echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
</code>```

答: In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server. </p>

Title: call a php function from jquery

Body:
I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:

JQUERY:

$.ajax({
    type: "POST",
    url: post_url,
    success: function(group) //we're calling the response json array 'tree'
    {
        //WANT TO CALL THE PHP FUNCTION HERE
    } //end success
 }); //end AJAX

PHP:

<?php
foreach($groups as $group){
    echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>


问:
How to make an Oracle Database connection from an AWS Lambda function (Python)
How does one build the upload package for an AWS Lamba function to connect to an Oracle RDS database? The lambda language is Python 3.6. My development environment is Windows NOT linux.

When I try, I get error:

```<code>DPI-1047: 64-bit Oracle Client library cannot be loaded: "libaio.so.1: cannot open shared object file: No such file or directory
</code>```

This is strange, because as I understand it, libaio.so is part of the amazon linux system, and so the correct version of libaio.so should be found.

What I have tried so far

I did the following steps to build my lambda package:

Deploy Oracle Instant Client, Basic Lite for Linux x64, version 18.3
into package directory /lib

Deploy cx_Oracle.so (from pypi website) into package directory /

Configure and deploy tnsnames.ora into package directory /

Within the lambda, ensure that environment variable LD_LIBRARY_PATH includes /lib and environment variable TNS_ADMIN points to directory /

here is the fragment of the python code, inside the lambda to achieve that:

```<code>oraclePath = os.environ['LAMBDA_TASK_ROOT'] + '/lib'
if oraclePath not in os.environ['LD_LIBRARY_PATH'].split(':'):
  os.environ['LD_LIBRARY_PATH'] = oraclePath + ':' + os.environ['LD_LIBRARY_PATH']
if ('TNS_ADMIN' not in os.environ) or (os.environ['TNS_ADMIN'] != os.environ['LAMBDA_TASK_ROOT']):
  os.environ['TNS_ADMIN'] = os.environ['LAMBDA_TASK_ROOT']
</code>```

In the lib directory, overwrite-copy libclntsh.so.18.1 to libclntsh.so. Similarly for libocci.so, and libclntshcore.so

Solutions from others that don't work for me

Here are two similiar SO questions with answers that didnt work for me, or are not applicable to my situation:

AWS Lambda cannot connect to Oracle Instant Client
Paul's solution is done in step 5 above.

AWS Python Lambda with Oracle
Thomas's solution is not helpful to me in my situation. These are linux commands. I need a windows solution.

An alternative approach

Perhaps I need to ask: How does a windows developer acquire the correct version of libaio.so.1 for the Amazon Linux Lambda environment, and where should this file be placed in the lambda package? Any solution that involves bash commands is not helpful.

答: Download instant client basic lite for windows x64.. that error will get solved! As u have downloaded linux version and using it on windows.. you are getting that error.</p>

Body:
How does one build the upload package for an AWS Lamba function to connect to an Oracle RDS database? The lambda language is Python 3.6. My development environment is Windows NOT linux.

When I try, I get error:

DPI-1047: 64-bit Oracle Client library cannot be loaded: "libaio.so.1: cannot open shared object file: No such file or directory

This is strange, because as I understand it, libaio.so is part of the amazon linux system, and so the correct version of libaio.so should be found.

What I have tried so far

I did the following steps to build my lambda package:

Deploy Oracle Instant Client, Basic Lite for Linux x64, version 18.3
into package directory /lib

Deploy cx_Oracle.so (from pypi website) into package directory /

Configure and deploy tnsnames.ora into package directory /

Within the lambda, ensure that environment variable LD_LIBRARY_PATH includes /lib and environment variable TNS_ADMIN points to directory /

here is the fragment of the python code, inside the lambda to achieve that:

oraclePath = os.environ['LAMBDA_TASK_ROOT'] + '/lib'
if oraclePath not in os.environ['LD_LIBRARY_PATH'].split(':'):
  os.environ['LD_LIBRARY_PATH'] = oraclePath + ':' + os.environ['LD_LIBRARY_PATH']
if ('TNS_ADMIN' not in os.environ) or (os.environ['TNS_ADMIN'] != os.environ['LAMBDA_TASK_ROOT']):
  os.environ['TNS_ADMIN'] = os.environ['LAMBDA_TASK_ROOT']

In the lib directory, overwrite-copy libclntsh.so.18.1 to libclntsh.so. Similarly for libocci.so, and libclntshcore.so

Solutions from others that don't work for me

Here are two similiar SO questions with answers that didnt work for me, or are not applicable to my situation:

AWS Lambda cannot connect to Oracle Instant Client
Paul's solution is done in step 5 above.

AWS Python Lambda with Oracle
Thomas's solution is not helpful to me in my situation. These are linux commands. I need a windows solution.

An alternative approach

Perhaps I need to ask: How does a windows developer acquire the correct version of libaio.so.1 for the Amazon Linux Lambda environment, and where should this file be placed in the lambda package? Any solution that involves bash commands is not helpful.


问:
Sending Sensor Data from Nodemcu ESP32 and Firebase
I'm trying to send sensor data from nodemcu ESP32 to firebase.
When using the basic example shown below it worked fine, and also when viewing the sensor data without sending it to firebase.
https://github.com/mobizt/Firebase-ESP32/tree/master/examples/Basic

However when I tried to edit the code a bit and send my sensor's data, I get an error, I would appreciate any help, code, and error attached.

```<code>#include <WiFi.h>
#include <FirebaseESP32.h>
#include "DHT.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include "WiFi.h"

#define DHTPIN 27     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define FIREBASE_HOST "trial-2c3ea.firebaseio.com"
#define FIREBASE_AUTH "Eu706797Vy2zOEDp3Bc9e4T9GZVAVwTyoxshl9Am"
#define WIFI_SSID "saadon 1"
#define WIFI_PASSWORD "0547258525"

//Define FirebaseESP32 data object
FirebaseData firebaseData;

FirebaseJson json;
DHT dht(DHTPIN, DHTTYPE);
const int oneWireBus = 2;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
const int Analog_channel_pin= 15;
double Soil_Moisture = 0;
double Soil_Moisture_analog = 0;
String path = "/Test";

void printResult(FirebaseData &data);

void setup()
{

  Serial.begin(115200);
  sensors.begin();
  dht.begin();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

}

void loop() {
    float h = dht.readHumidity();
  float t = dht.readTemperature();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  Soil_Moisture_analog = analogRead(Analog_channel_pin);
  Soil_Moisture = (0.00531*exp(0.29*(Soil_Moisture_analog*0.006+1.0265)))*100;

      if (Firebase.setFloat(firebaseData, path + "/Air Temp" + t))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

  if (Firebase.setFloat(firebaseData, path + "/Air Humidity" + h))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Temperature" + temperatureC))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Moisture" + Soil_Moisture))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }
  delay(5000);
}
</code>```

Error:

firebasecode:74:65: error: no matching function for call to 'FirebaseESP32::setFloat(FirebaseData&, StringSumHelper&)'

答:
The setFloat method takes three parameters:

```<code>  bool setFloat(FirebaseData &dataObj, const String &path, float floatValue);
</code>```

From https://github.com/mobizt/Firebase-ESP32/blob/master/src/FirebaseESP32.h#L1084

So the path and value are separate parameters. Change the calls to setFloat to look like:

```<code>      if (Firebase.setFloat(firebaseData, path + "/Air Temp", t))
</code>```

Body:
I'm trying to send sensor data from nodemcu ESP32 to firebase.
When using the basic example shown below it worked fine, and also when viewing the sensor data without sending it to firebase.
https://github.com/mobizt/Firebase-ESP32/tree/master/examples/Basic

However when I tried to edit the code a bit and send my sensor's data, I get an error, I would appreciate any help, code, and error attached.

#include <WiFi.h>
#include <FirebaseESP32.h>
#include "DHT.h"
#include <OneWire.h>
#include <DallasTemperature.h>
#include "WiFi.h"

#define DHTPIN 27     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define FIREBASE_HOST "trial-2c3ea.firebaseio.com"
#define FIREBASE_AUTH "Eu706797Vy2zOEDp3Bc9e4T9GZVAVwTyoxshl9Am"
#define WIFI_SSID "saadon 1"
#define WIFI_PASSWORD "0547258525"

//Define FirebaseESP32 data object
FirebaseData firebaseData;

FirebaseJson json;
DHT dht(DHTPIN, DHTTYPE);
const int oneWireBus = 2;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
const int Analog_channel_pin= 15;
double Soil_Moisture = 0;
double Soil_Moisture_analog = 0;
String path = "/Test";

void printResult(FirebaseData &data);

void setup()
{

  Serial.begin(115200);
  sensors.begin();
  dht.begin();
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");

  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.reconnectWiFi(true);

}

void loop() {
    float h = dht.readHumidity();
  float t = dht.readTemperature();
  sensors.requestTemperatures();
  float temperatureC = sensors.getTempCByIndex(0);
  Soil_Moisture_analog = analogRead(Analog_channel_pin);
  Soil_Moisture = (0.00531*exp(0.29*(Soil_Moisture_analog*0.006+1.0265)))*100;

      if (Firebase.setFloat(firebaseData, path + "/Air Temp" + t))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

  if (Firebase.setFloat(firebaseData, path + "/Air Humidity" + h))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Temperature" + temperatureC))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }

    if (Firebase.setFloat(firebaseData, path + "/Soil Moisture" + Soil_Moisture))
    {
      Serial.println("PASSED");
      printResult(firebaseData);
      Serial.println();
    }
    else
    {
      Serial.println("FAILED");
      Serial.println("REASON: " + firebaseData.errorReason());
      Serial.println();
    }
  delay(5000);
}

Error:

firebasecode:74:65: error: no matching function for call to 'FirebaseESP32::setFloat(FirebaseData&, StringSumHelper&)'

Body:
The setFloat method takes three parameters:

  bool setFloat(FirebaseData &dataObj, const String &path, float floatValue);

From https://github.com/mobizt/Firebase-ESP32/blob/master/src/FirebaseESP32.h#L1084

So the path and value are separate parameters. Change the calls to setFloat to look like:

      if (Firebase.setFloat(firebaseData, path + "/Air Temp", t))


问:
Azure AD account had option to send password to another email address - where is this address in user's Azure AD?
I was just recently created as a new user in Microsoft 365 Admin Center (https://admin.microsoft.com/) and during account creation, when setting up password, there was a field to send the password /setup details to me through another email address (my previous email address, outside O365).

I received my new account notification at this other email address, and now this email address gets notifications etc. but when we look at my Azure AD membership, I can't find where this email address is configured in the settings.  Where is this forwarding address being stored?

We checked Azure Admin portal (portal.azure.com) Authentication contact info for my entry and it's not filled in.

It's not in Manage User Name or contact information in the https://admin.microsoft.com/Adminportal/Home#/users page

It's not in my account profile anywhere in https://portal.office.com/account/#personalinfo

Totally stumped!  Apologies if the answer is obvious.

答:
did you check in the account profile under security and privacy? there is an email field there as well. https://portal.office.com/account/#security
if not there. then there is a different spot,
make sure you're logged into portal.office.com
then go here
https://myaccount.microsoft.com/
then click security info. enter your password again, and there is a authentication email there as well. </p>

<p>hope this is what you're looking for. </p>

Body:
did you check in the account profile under security and privacy? there is an email field there as well. https://portal.office.com/account/#security
if not there. then there is a different spot,
make sure you're logged into portal.office.com
then go here
https://myaccount.microsoft.com/
then click security info. enter your password again, and there is a authentication email there as well.

hope this is what you're looking for.


问:
How to get post values from first page to third page ,as post
i have 3 pages

Page1.php,page2.php,page3.php

In page1.php, i have some hidden values, for example 'name'

After the submission of page1.php, it will go to page2.

Then after some process in page2.php, it should need to automatically submit to page3.php(where page3.php is in another sever)

Finally,when i print the $_POST  variables in page3.php, i need to get the variable 'name'

答:
You will want to look into sessions.

If you need them in POST, try this:

```<code>$display = "";
$saveFields = array('one', 'two'); // whitelist of fields to add to the form hidden
foreach ($_POST as $key => $val) {
    if (!empty($val) && in_array($key, $saveFields))
        $display .= '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}

echo $display;
</code>```

Should get you where you want to go. The whitelist just ensure's that random stuff is not injected that does not need to be.

Body:
You will want to look into sessions.

If you need them in POST, try this:

$display = "";
$saveFields = array('one', 'two'); // whitelist of fields to add to the form hidden
foreach ($_POST as $key => $val) {
    if (!empty($val) && in_array($key, $saveFields))
        $display .= '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}

echo $display;

Should get you where you want to go. The whitelist just ensure's that random stuff is not injected that does not need to be.


问:
Changing the color of a Text item from a FlatList onPress
I have a category list that is being displayed using a FlatList I tried changing the color of a single item OnPress so the user gets a feed back of what item he selected,but all the items in the FlatList change color.

How do I go along about implementing something like this so that the only selected item changes color and gets the original color back when another item is selected

Here is a sample of the code used :

```<code>import colors from "../config/colors";
function Categories() {
  return (
    <View style={styles.Categories}>
      <FlatList
        horizontal
        showsHorizontalScrollIndicator={false}
        style={{}}
        data={category}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => {
          return <Text style={styles.Text}>{item.title}</Text>;
        }}
      />
    </View>
  );
}
</code>```

答:
You will have to maintain the selected item in a local state and have a selected flag for each item and switch the style according to the requirement.

```<code>const styles = StyleSheet.create({
  selectedText: {
    color: 'blue',
  },
  normalText: {
    color: 'black',
  },
});

function Categories(props) {
  const [categroy, updateCategory] = React.useState(props.category);

  const updateOnPress = (index) => {
    const categories = categroy.map((item) => {
      item.selected = false;
      return item;
    });
    categories[index].selected = true;
    updateCategory(categories);
  };

  return (
    <View style={styles.Categories}>
      <FlatList
        horizontal
        showsHorizontalScrollIndicator={false}
        style={{}}
        data={categroy}
        keyExtractor={(item) => item.id}
        renderItem={({ item, index }) => {
          return (
            <TouchableOpacity onPress={() => updateOnPress(index)}>
              <Text
                style={item.selected ? styles.selectedText : styles.normalText}>
                {item.title}
              </Text>
            </TouchableOpacity>
          );
        }}
      />
    </View>
  );
}
</code>```

You can use the component like below

```<code>< Categories
      category={[
        { id: 1, title: 'aa' },
        { id: 2, title: 'bb' },
        { id: 3, title: 'cc' },
      ]}
    />
</code>```

Body:
I have a category list that is being displayed using a FlatList I tried changing the color of a single item OnPress so the user gets a feed back of what item he selected,but all the items in the FlatList change color.

How do I go along about implementing something like this so that the only selected item changes color and gets the original color back when another item is selected

Here is a sample of the code used :

import colors from "../config/colors";
function Categories() {
  return (
    <View style={styles.Categories}>
      <FlatList
        horizontal
        showsHorizontalScrollIndicator={false}
        style={{}}
        data={category}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => {
          return <Text style={styles.Text}>{item.title}</Text>;
        }}
      />
    </View>
  );
}

Body:
You will have to maintain the selected item in a local state and have a selected flag for each item and switch the style according to the requirement.

const styles = StyleSheet.create({
  selectedText: {
    color: 'blue',
  },
  normalText: {
    color: 'black',
  },
});

function Categories(props) {
  const [categroy, updateCategory] = React.useState(props.category);

  const updateOnPress = (index) => {
    const categories = categroy.map((item) => {
      item.selected = false;
      return item;
    });
    categories[index].selected = true;
    updateCategory(categories);
  };

  return (
    <View style={styles.Categories}>
      <FlatList
        horizontal
        showsHorizontalScrollIndicator={false}
        style={{}}
        data={categroy}
        keyExtractor={(item) => item.id}
        renderItem={({ item, index }) => {
          return (
            <TouchableOpacity onPress={() => updateOnPress(index)}>
              <Text
                style={item.selected ? styles.selectedText : styles.normalText}>
                {item.title}
              </Text>
            </TouchableOpacity>
          );
        }}
      />
    </View>
  );
}

You can use the component like below

< Categories
      category={[
        { id: 1, title: 'aa' },
        { id: 2, title: 'bb' },
        { id: 3, title: 'cc' },
      ]}
    />


问:
Loop with runas command prompt (cmd)
How can we use loop command as example below:

```<code>runas /user:nsrv\john "a.bat"
</code>```

If we input wrong password, it will ask input again again and again until we input right password.

答:
Oh I found it hahaha</p>

```<code>:Loop
@echo Type password:
runas /user:john "a.bat"
if errorlevel equ 1 goto :Loop
</code>```

Title: Loop with runas command prompt (cmd)

Body:
How can we use loop command as example below:

runas /user:nsrv\john "a.bat"

If we input wrong password, it will ask input again again and again until we input right password.

Body:
Oh I found it hahaha

:Loop
@echo Type password:
runas /user:john "a.bat"
if errorlevel equ 1 goto :Loop


问:
Is it possible to use React Hooks outside of functional component, or i have to use mobx or redux?
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

```<code>//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

</code>```

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?

答:
Hooks comes as an alternatively to class based components, you should pick up one to your project and stick to it, don't mix it up. there are some motivation for the creation of hooks, as it's better stated at docs: hook motivation.

you can create hook functions apart, but they are meant to be consumed by components. it's something like using HOC (high order component) with class based components.

```<code>const myHook = () => {
  [foo, setFoo] = useState('john')
  // use effect for example if you need to run something at state updates
  useEffect(() => {
    // do something on foo changes
  }, [foo])

  return [foo, setFoo] // returning state and setState you can use them by your component
}
</code>```

now you have a reusable hook and you can consume at your components:

```<code>const myComponent = (props) => {
  [foo, setFoo] = myHook()

  const handleFoo = () => {
    // some logic
    setFoo(someValue)
  }
  return (
    <div>
      <span>{foo}<span>
      <button onClick={handleFoo}>click</button>
    </div>
  )
}
</code>```

obs: you should avoid declare variables as var nowadays, pick const for most, and if it's a value variable (like number) that needs update use let.

Body:
I am new to React, and when I was reading about the docs, I found there were two ways to implement React components, functional-based and class-based. I know before React 16.8 it's not possible to manage state in functional components, but after that there is React Hooks.

The problem is, there seems to be one restriction for React Hooks, they can only be used inside functional components. Take a server-client as an example, which needs to change an isAuthenticated state while 401 received.

//client.js
import { useUserDispatch, signOut } from "auth";

export function request(url, args) {
  var dispatch = useUserDispatch();
  return fetch(url, args).then(response => {
  if (response.status === 401) {
    logout(dispatch);
  }
}
);

//auth.js
import React from "react";

var UserStateContext = React.createContext();
var UserDispatchContext = React.createContext();

function userReducer(state, action) {
  ...
}

function UserProvider({ children }) {
  var [state, dispatch] = React.useReducer(userReducer, {
    isAuthenticated: false,
  });

  return (
    <UserStateContext.Provider value={state}>
      <UserDispatchContext.Provider value={dispatch}>
        {children}
      </UserDispatchContext.Provider>
    </UserStateContext.Provider>
  );
}

function useUserState() {
  return React.useContext(UserStateContext);
}

function useUserDispatch() {
  return React.useContext(UserDispatchContext);
}

function signOut(dispatch) {
  dispatch({});
}

export { UserProvider, useUserState, useUserDispatch, loginUser, signOut };

The client code above will produce error "Hooks can only be called inside of the body of a function component".
So maybe I have to move line var dispatch = useUserDispatch() upward to the component where request is called, and pass dispatch as props to request.
I feel this is not right, no only request is forced to care about some meaningless(to it) dispatch, but also this dispatch will spread everywhere a component needs to request.

For class-based components, this.state doesn't solve this problem either, but at least I can use mobx.

So are there some other ideal ways to solve this problem?

Body:
Hooks comes as an alternatively to class based components, you should pick up one to your project and stick to it, don't mix it up. there are some motivation for the creation of hooks, as it's better stated at docs: hook motivation.

you can create hook functions apart, but they are meant to be consumed by components. it's something like using HOC (high order component) with class based components.

const myHook = () => {
  [foo, setFoo] = useState('john')
  // use effect for example if you need to run something at state updates
  useEffect(() => {
    // do something on foo changes
  }, [foo])

  return [foo, setFoo] // returning state and setState you can use them by your component
}

now you have a reusable hook and you can consume at your components:

const myComponent = (props) => {
  [foo, setFoo] = myHook()

  const handleFoo = () => {
    // some logic
    setFoo(someValue)
  }
  return (
    <div>
      <span>{foo}<span>
      <button onClick={handleFoo}>click</button>
    </div>
  )
}

obs: you should avoid declare variables as var nowadays, pick const for most, and if it's a value variable (like number) that needs update use let.