问:
react- setState doesn't clear textbox
I want to clear textbox fields on success or error. how can I do that.?

On success or error, calling a function to show the snack bar. Within that, I'm updating the state. but it is not working fine.

any help appreciated.!

function

```<code>openSnackbar = ({ message }) => {
     this.setState({
         open: true,
         cp_currentPassword: '',
         cp_newPassword: '',
         cp_confirmPassword: '',
         message
     });
  };
</code>```

textfield

```<code><TextField
     id="cp_currentPassword"
     label="Current Password"
     type="password"
     fullWidth
     className={classes.textField}
     value={this.state.cp_currentPassword}
     onChange={this.handleChange}
     margin="normal"
     required={true}
/>;

</code>```

component

```<code>import React, { Component } from 'react'
import withStyles from "@material-ui/core/styles/withStyles";
import CircularProgress from '@material-ui/core/CircularProgress';
import TextField from '@material-ui/core/TextField';
import GridItem from "../uiComponents/Grid/GridItem.jsx";
import GridContainer from "../uiComponents/Grid/GridContainer.jsx";
import Button from "../uiComponents/CustomButtons/Button.jsx";
import Card from "../uiComponents/Card/Card.jsx";
import CardHeader from "../uiComponents/Card/CardHeader.jsx";
import CardBody from "../uiComponents/Card/CardBody.jsx";
import CardFooter from "../uiComponents/Card/CardFooter.jsx";
import Snackbar from '@material-ui/core/Snackbar';
import CloseIcon from '@material-ui/icons/Close';
import { Redirect } from 'react-router-dom'
import IconButton from '@material-ui/core/IconButton';
import { connect } from 'react-redux'
import { compose } from 'redux'
import { changePassword } from '../../store/actions/auth'

const styles = {

    textField: {
        fontSize: '5px'
    },

};

class ChangePassword extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            open: false,
            message: '',
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: ''
        }
    }
    componentDidUpdate = (prevProps) => {
        const { authError } = this.props;
        console.log(authError)
        if (authError != prevProps.authError) {
            this.setState(
                {
                    loading: false,
                    message: authError,
                    open: true
                })
        }

    };

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    openSnackbar = ({ message }) => {
        this.setState({
            open: true,
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: '',
            message
        });
    };

    handleSubmit = (e) => {
        e.preventDefault();
        let curpass = this.state.cp_currentPassword
        let newpass = this.state.cp_newPassword
        this.setState({ loading: true });
        this.props.changePassword(curpass, newpass, this.passwordUpdated)
    }

    passwordUpdated = () => {
        this.setState({
            message: 'Password changed Successfully.!',
            open: true,
            loading: false,
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: ''
        });
    };

    render() {
        const { classes, auth, authError } = this.props;

        console.log(authError)
        const { loading } = this.state;
        const message = (
            <span
                id="snackbar-message-id"
                dangerouslySetInnerHTML={{ __html: this.state.message }}
            />
        );
        if (!auth.uid) return <Redirect to='/signin' />
        return (
            <div>
                {/* {authError ? this.openSnackbar({ message: '{authError}' }) : null} */}
                {/* {authError && !this.state.open ? this.openSnackbar({ message: '{authError}' }) : null} */}
                <GridContainer>
                    <GridItem xs={12} sm={12} md={12}>

                        <Card>
                            <CardHeader color="warning">
                                <h4 className={classes.cardTitleWhite}>Change Password</h4>
                            </CardHeader>
                            <form >
                                <GridContainer>
                                    <GridItem xs={12} sm={12} md={6}>
                                        <CardBody>
                                            <GridContainer>
                                                <GridItem xs={12} sm={12} md={12}>

                                                    <TextField
                                                        id="cp_currentPassword"
                                                        label="Current Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_currentPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>

                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_newPassword"
                                                        label="New Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_newPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_confirmPassword"
                                                        label="Confirm Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_confirmPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                            </GridContainer>

                                        </CardBody>
                                        <CardFooter>

                                            <Button color="warning" onClick={(e) => this.handleSubmit(e)} disabled={loading}>
                                                {loading && <CircularProgress style={{ color: 'white', height: '20px', width: '20px', marginRight: '10px' }} />}
                                                Change Password
                      </Button>
                                        </CardFooter>
                                    </GridItem>
                                </GridContainer>
                            </form>
                        </Card>

                    </GridItem>

                </GridContainer>

                <Snackbar
                    open={this.state.open}//{!!this.props.authError}//
                    anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
                    message={message}
                    variant="error"
                    onClose={() => this.setState({ open: false, message: '' })}
                    action={
                        <IconButton
                            key="close"
                            aria-label="Close"
                            color="inherit"
                            className={classes.close}
                            onClick={() =>
                               // clearAuthError
                                this.setState({ open: false, message: '' })

                            }
                        >
                            <CloseIcon className={classes.icon} />
                        </IconButton>
                    }
                    autoHideDuration={3000}
                />
            </div>
        )
    }
}
const mapstateToProps = (state) => {
    return {
        auth: state.firebase.auth,
        authError: state.authroot.autherr
    }
}
const mapDispatchtoProps = (dispatch, getState) => {
    return {
        changePassword: (currentPassword, newPassword, passwordUpdated) => { dispatch(changePassword(currentPassword, newPassword, passwordUpdated)) },
    }
}
export default compose(
    withStyles(styles),
    connect(mapstateToProps, mapDispatchtoProps)
)(ChangePassword);
</code>```

答:
In your handleSubmit function don't pass this.passwordUpdated

```<code>handleSubmit = (e) => {
    e.preventDefault();
    let curpass = this.state.cp_currentPassword
    let newpass = this.state.cp_newPassword
    this.setState({ loading: true });
    this.props.changePassword(curpass, newpass, this.passwordUpdated) //Remove this.passwordUpdated from here
}
</code>```

Instead of ComponentDidUpdate method you should use ComponentWillReceiveProps

```<code>componentWillReceiveProps(nextProps) {
 console.log('componentWillReceiveProps', nextProps);
 if (this.props.authError !== nextProps.authError) {
  // here you can make your textbox empty
  this.setState({
      cp_currentPassword: '',
      cp_newPassword: '',
      cp_confirmPassword: ''
  });
 }
}
</code>```

Note: In new version of react you must use static getDerivedStateFromProps() instead of componentWillReceiveProps.

Title: react- setState doesn't clear textbox

Body:
I want to clear textbox fields on success or error. how can I do that.?

On success or error, calling a function to show the snack bar. Within that, I'm updating the state. but it is not working fine.

any help appreciated.!

function

openSnackbar = ({ message }) => {
     this.setState({
         open: true,
         cp_currentPassword: '',
         cp_newPassword: '',
         cp_confirmPassword: '',
         message
     });
  };

textfield

<TextField
     id="cp_currentPassword"
     label="Current Password"
     type="password"
     fullWidth
     className={classes.textField}
     value={this.state.cp_currentPassword}
     onChange={this.handleChange}
     margin="normal"
     required={true}
/>;

component

import React, { Component } from 'react'
import withStyles from "@material-ui/core/styles/withStyles";
import CircularProgress from '@material-ui/core/CircularProgress';
import TextField from '@material-ui/core/TextField';
import GridItem from "../uiComponents/Grid/GridItem.jsx";
import GridContainer from "../uiComponents/Grid/GridContainer.jsx";
import Button from "../uiComponents/CustomButtons/Button.jsx";
import Card from "../uiComponents/Card/Card.jsx";
import CardHeader from "../uiComponents/Card/CardHeader.jsx";
import CardBody from "../uiComponents/Card/CardBody.jsx";
import CardFooter from "../uiComponents/Card/CardFooter.jsx";
import Snackbar from '@material-ui/core/Snackbar';
import CloseIcon from '@material-ui/icons/Close';
import { Redirect } from 'react-router-dom'
import IconButton from '@material-ui/core/IconButton';
import { connect } from 'react-redux'
import { compose } from 'redux'
import { changePassword } from '../../store/actions/auth'

const styles = {

    textField: {
        fontSize: '5px'
    },

};

class ChangePassword extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            open: false,
            message: '',
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: ''
        }
    }
    componentDidUpdate = (prevProps) => {
        const { authError } = this.props;
        console.log(authError)
        if (authError != prevProps.authError) {
            this.setState(
                {
                    loading: false,
                    message: authError,
                    open: true
                })
        }

    };

    handleChange = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    openSnackbar = ({ message }) => {
        this.setState({
            open: true,
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: '',
            message
        });
    };

    handleSubmit = (e) => {
        e.preventDefault();
        let curpass = this.state.cp_currentPassword
        let newpass = this.state.cp_newPassword
        this.setState({ loading: true });
        this.props.changePassword(curpass, newpass, this.passwordUpdated)
    }

    passwordUpdated = () => {
        this.setState({
            message: 'Password changed Successfully.!',
            open: true,
            loading: false,
            cp_currentPassword: '',
            cp_newPassword: '',
            cp_confirmPassword: ''
        });
    };

    render() {
        const { classes, auth, authError } = this.props;

        console.log(authError)
        const { loading } = this.state;
        const message = (

        );
        if (!auth.uid) return <Redirect to='/signin' />
        return (

                {/* {authError ? this.openSnackbar({ message: '{authError}' }) : null} */}
                {/* {authError && !this.state.open ? this.openSnackbar({ message: '{authError}' }) : null} */}
                <GridContainer>
                    <GridItem xs={12} sm={12} md={12}>

                        <Card>
                            <CardHeader color="warning">

Change Password

                            </CardHeader>
                            <form >
                                <GridContainer>
                                    <GridItem xs={12} sm={12} md={6}>
                                        <CardBody>
                                            <GridContainer>
                                                <GridItem xs={12} sm={12} md={12}>

                                                    <TextField
                                                        id="cp_currentPassword"
                                                        label="Current Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_currentPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>

                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_newPassword"
                                                        label="New Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_newPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                                <GridItem xs={12} sm={12} md={12}>
                                                    <TextField
                                                        id="cp_confirmPassword"
                                                        label="Confirm Password"
                                                        type="password"
                                                        fullWidth
                                                        className={classes.textField}
                                                        value={this.state.cp_confirmPassword}
                                                        onChange={this.handleChange}
                                                        margin="normal"
                                                        required={true}
                                                    />
                                                </GridItem>
                                            </GridContainer>

                                        </CardBody>
                                        <CardFooter>

                                            <Button color="warning" onClick={(e) => this.handleSubmit(e)} disabled={loading}>
                                                {loading && <CircularProgress style={{ color: 'white', height: '20px', width: '20px', marginRight: '10px' }} />}
                                                Change Password
                      </Button>
                                        </CardFooter>
                                    </GridItem>
                                </GridContainer>
                            </form>
                        </Card>

                    </GridItem>

                </GridContainer>

                <Snackbar
                    open={this.state.open}//{!!this.props.authError}//
                    anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
                    message={message}
                    variant="error"
                    onClose={() => this.setState({ open: false, message: '' })}
                    action={
                        <IconButton
                            key="close"
                            aria-label="Close"
                            color="inherit"
                            className={classes.close}
                            onClick={() =>
                               // clearAuthError
                                this.setState({ open: false, message: '' })

                            }
                        >
                            <CloseIcon className={classes.icon} />
                        </IconButton>
                    }
                    autoHideDuration={3000}
                />

        )
    }
}
const mapstateToProps = (state) => {
    return {
        auth: state.firebase.auth,
        authError: state.authroot.autherr
    }
}
const mapDispatchtoProps = (dispatch, getState) => {
    return {
        changePassword: (currentPassword, newPassword, passwordUpdated) => { dispatch(changePassword(currentPassword, newPassword, passwordUpdated)) },
    }
}
export default compose(
    withStyles(styles),
    connect(mapstateToProps, mapDispatchtoProps)
)(ChangePassword);

Body:
In your handleSubmit function don't pass this.passwordUpdated

handleSubmit = (e) => {
    e.preventDefault();
    let curpass = this.state.cp_currentPassword
    let newpass = this.state.cp_newPassword
    this.setState({ loading: true });
    this.props.changePassword(curpass, newpass, this.passwordUpdated) //Remove this.passwordUpdated from here
}

Instead of ComponentDidUpdate method you should use ComponentWillReceiveProps

componentWillReceiveProps(nextProps) {
 console.log('componentWillReceiveProps', nextProps);
 if (this.props.authError !== nextProps.authError) {
  // here you can make your textbox empty
  this.setState({
      cp_currentPassword: '',
      cp_newPassword: '',
      cp_confirmPassword: ''
  });
 }
}

Note: In new version of react you must use static getDerivedStateFromProps() instead of componentWillReceiveProps.


来源: stackexchange

问:
MYSQL Workbench "Incorrect string value" error while migrating database from MS SQL-Server
I am trying to migrate a SQL-Server database to MYSQL. I am getting the error

"Incorrect string value: '\xF0\x9F\x98\x8B\xF0\x9F...'"

I am using the batch file created by MySQL Workbench 8.0 CE to see the error because the UI crashes and freezes.

The source table is in Latin1_General_CI_AS

The destination table has been created as utf8mb4_0900_ai_ci

Source database: Mssql@DRIVER=ODBC Driver 17 for SQL Server;SERVER=localhost\SQLEXPRESS (Microsoft SQL Server)

Target database: Mysql@localhost:3306

Is there anything else I can try?

答:
That hex is not Latin1, nor UTF16; it matches the UTF-8 encoding for .  (That's the first 4 bytes; the next two are probably the beginning of another Emoji.)

The connection parameters need to say that the data is encoded utf8mb4.  It is not sufficient to specify the table to be utf8mb4.

The source table was not Latin1.  Or you did not notice that that Emoji displayed as this Mojibake:  ðŸ˜‹.

ContentLicense: CC BY-SA 4.0


问:
Navbar is not re-rendering on router location change
I want to display userName and changed the button text to 'logout' from 'login' in Navbar(nav component) when user is logged in. I tired to re-render the Nav Component by pushing the router history location to homepage on user logged in.

```<code>this.props.history.push('/')
</code>```

Then User can successfully log in, user data is saved in localStorage and the router location is changed. data is saved in localStorage, but the component is not re-rendering.

Here is what I have tried.

tried to downgrade 'connected-react-router' to 'v6.0.0' but it threw me some errors. so put it back to the latest version '^6.4.0'.

tried to add Navbar code in App.js which is the parents component.
But the app.js itself is not re-rendering either on user logged in.

app.js

```<code>import React from 'react';
import { connect } from 'react-redux';
/* --- Components --- */
import Nav from './src/components/nav';
import Loader from './src/shared/loader';
import './styles/main.scss';

const FlashMessagesContainer = Loader({
  loader: () =>
    import('./src/shared/flassMessagesContainer' /* webpackChunkName: 'FlashMessagesContainer' */),
});

const App = (props, { isOnModal }) => (
  <div id="app">
    <Nav />
    {!isOnModal && (
      <div className="flex justify-center">
        <FlashMessagesContainer />
      </div>
    )}
    {props.children}
  </div>
);

const mapPropsToState = state => ({
  isOnModal: state.modal.show,
});

export default connect(
  mapPropsToState,
  null,
)(App);

</code>```

nav.js

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';

/* --- Components --- */
import {
  isLoggedIn,
  getCompanyName,
  clearLocalStorage,
} from '../../localStorage';

class Nav extends Component {

  handleUserLogout = async ev => {
    ev.preventDefault();
    await clearLocalStorage();
    return this.props.history.push('/login');
  };

  render() {
    return (
      <div className="nav">
          {isLoggedIn() ? (
            <div className="flex">
              <p className="mr3 mt2">
                안녕하세요. <span className="b">{getCompanyName()}</span>
                 님,
              </p>
              <button
                type="button"
                className="login-btn td-none c-text br f-mini"
                onClick={this.handleUserLogout}
              >
                로그아웃
              </button>
            </div>
          ) : (
            <Link className="login-btn td-none c-text br f-mini" to="/login">
              로그인
            </Link>
          )}
      </div>
    );
  }
}

export default withRouter(Nav);

</code>```

localStorage.js

```<code>export const getToken = () => localStorage.token;
export const getCompanyName = () => localStorage.companyName;
export const isLoggedIn = () => !!localStorage.token;
export const saveUserNameAndToken = userData => {
  localStorage.setItem('token', userData.token);
  localStorage.setItem('companyName', userData.companyName);
};
export const clearLocalStorage = () => localStorage.clear();

</code>```

index.js

```<code>import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter as Router } from 'connected-react-router';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import configureStore, { history } from './store';
import Routes from './routes';

const theme = createMuiTheme({
 ...
});

const store = configureStore();
const root = document.createElement('div');
document.body.appendChild(root);

render(
  <Provider store={store}>
    <MuiThemeProvider theme={theme}>
      <Router history={history}>
        <Routes />
      </Router>
    </MuiThemeProvider>
  </Provider>,
  root,
);

</code>```

routes.js

```<code>import React from 'react';
import { Switch, Route } from 'react-router-dom';
import { hot, setConfig } from 'react-hot-loader';
import { withRouter } from 'react-router';
/* --- Components --- */
import App from './app';
import Loader from './src/shared/loader';

const Home = Loader({
  loader: () =>
    import('./src/components/home/homeContainer' /* webpackChunkName: 'Home' */),
});

...

const routes = props => (
  <div>
    <App history={props.history} />
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/login" render={props => <Login {...props} />} />
      <Route path="/users/account" component={Users} />
      <Route component={NoMatch} />
    </Switch>
  </div>
);

const Routes =
  !module.hot || process.env.NODE_ENV === 'production'
    ? routes
    : hot(module)(routes);

export default withRouter(Routes);

</code>```

I am expecting Nav component to be re-rendered when router location changes.

```<code>react: ^16.8.6
react-dom: ^16.8.6
react-loadable: ^5.5.0
react-redux: ^6.0.0
react-router-dom: ^4.3.1
redux: ^4.0.0
connected-react-router: ^6.4.0
</code>```

答:
I fixed it by saving 'isLoggedIn' state in redux store. And to persist the state from redux store on page refresh, I used 'redux-persist'.

Now Nav component is re-rendering on router location change and the userName data is saved even on page refresh.

authReducer.js

```<code>const initialState = {
  isLoggedIn: false,
  userName: '',
};
const auth = (state = initialState, action) => {
  switch (action.type) {
    case types.USER_LOGIN:
      return {
        ...state,
        isLoggedIn: true,
        userName: action.payload,
      };
    case types.USER_LOGOUT:
      return {
        ...state,
        isLoggedIn: false,
        userName: '',
      };
    default:
      return state;
  }
};

</code>```

nav.js

```<code>...
{this.props.isLoggedIn ? (
           ...
          ) : (
           ...
          )}
...

const mapStateToProps = state => ({
  isLoggedIn: state.auth.isLoggedIn,
  userName: state.auth.userName,
});

const mapDispatchToProps = dispatch => ({
  userLogout: () => dispatch(userLogout()),
});

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps,
  )(Nav),
);
</code>```

[ redux-persist SetUp ]

store.js

```<code>import { applyMiddleware, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { composeWithDevTools } from 'redux-devtools-extension';
import { routerMiddleware } from 'connected-react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import createRootReducer from './src/reducers';

export const history = createBrowserHistory();

const persistConfig = {
  key: 'root',
  storage,
};
const persistedReducer = persistReducer(
  persistConfig,
  createRootReducer(history),
);

const store = createStore(
  persistedReducer,
  composeWithDevTools(
    applyMiddleware(
      routerMiddleware(history),
      thunkMiddleware,
      createLogger({
        predicate: () => process.env.NODE_ENV === 'development',
        collapsed: true,
      }),
    ),
  ),
);

export const persistor = persistStore(store);
export default store;

</code>```

index.js

```<code>import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter as Router } from 'connected-react-router';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { PersistGate } from 'redux-persist/lib/integration/react';
import store, { history, persistor } from './store';
import Routes from './routes';
import Loading from './src/shared/loading';

const theme = createMuiTheme({
  palette: {
    primary: { main: '#AE9A65' },
    secondary: { main: '#ee9105' },
    success: { main: '#43A047' },
    warning: { main: '#FFA000' },
    error: { main: '#ed4337' },
    info: { main: '#2196F3' },
  },
});

const root = document.createElement('div');
document.body.appendChild(root);

render(
  <Provider store={store}>
    <PersistGate loading={<Loading />} persistor={persistor}>
      <MuiThemeProvider theme={theme}>
        <Router history={history}>
          <Routes />
        </Router>
      </MuiThemeProvider>
    </PersistGate>
  </Provider>,
  root,
);
</code>```

Body:
I want to display userName and changed the button text to 'logout' from 'login' in Navbar(nav component) when user is logged in. I tired to re-render the Nav Component by pushing the router history location to homepage on user logged in.

this.props.history.push('/')

Then User can successfully log in, user data is saved in localStorage and the router location is changed. data is saved in localStorage, but the component is not re-rendering.

Here is what I have tried.

tried to downgrade 'connected-react-router' to 'v6.0.0' but it threw me some errors. so put it back to the latest version '^6.4.0'.

tried to add Navbar code in App.js which is the parents component.
But the app.js itself is not re-rendering either on user logged in.

app.js

import React from 'react';
import { connect } from 'react-redux';
/* --- Components --- */
import Nav from './src/components/nav';
import Loader from './src/shared/loader';
import './styles/main.scss';

const FlashMessagesContainer = Loader({
  loader: () =>
    import('./src/shared/flassMessagesContainer' /* webpackChunkName: 'FlashMessagesContainer' */),
});

const App = (props, { isOnModal }) => (

    {!isOnModal && (

        <FlashMessagesContainer />

    )}
    {props.children}

);

const mapPropsToState = state => ({
  isOnModal: state.modal.show,
});

export default connect(
  mapPropsToState,
  null,
)(App);

nav.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link, withRouter } from 'react-router-dom';

/* --- Components --- */
import {
  isLoggedIn,
  getCompanyName,
  clearLocalStorage,
} from '../../localStorage';

class Nav extends Component {

  handleUserLogout = async ev => {
    ev.preventDefault();
    await clearLocalStorage();
    return this.props.history.push('/login');
  };

  render() {
    return (

          {isLoggedIn() ? (

                안녕하세요. {getCompanyName()}
                 님,

              <button
                type="button"
                className="login-btn td-none c-text br f-mini"
                onClick={this.handleUserLogout}
              >
                로그아웃
              </button>

          ) : (
            <Link className="login-btn td-none c-text br f-mini" to="/login">
              로그인
            </Link>
          )}

    );
  }
}

export default withRouter(Nav);

localStorage.js

export const getToken = () => localStorage.token;
export const getCompanyName = () => localStorage.companyName;
export const isLoggedIn = () => !!localStorage.token;
export const saveUserNameAndToken = userData => {
  localStorage.setItem('token', userData.token);
  localStorage.setItem('companyName', userData.companyName);
};
export const clearLocalStorage = () => localStorage.clear();

index.js

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter as Router } from 'connected-react-router';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import configureStore, { history } from './store';
import Routes from './routes';

const theme = createMuiTheme({
 ...
});

const store = configureStore();
const root = document.createElement('div');
document.body.appendChild(root);

render(
  <Provider store={store}>
    <MuiThemeProvider theme={theme}>
      <Router history={history}>
        <Routes />
      </Router>
    </MuiThemeProvider>
  </Provider>,
  root,
);

routes.js

import React from 'react';
import { Switch, Route } from 'react-router-dom';
import { hot, setConfig } from 'react-hot-loader';
import { withRouter } from 'react-router';
/* --- Components --- */
import App from './app';
import Loader from './src/shared/loader';

const Home = Loader({
  loader: () =>
    import('./src/components/home/homeContainer' /* webpackChunkName: 'Home' */),
});

...

const routes = props => (

    <App history={props.history} />
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/login" render={props => <Login {...props} />} />
      <Route path="/users/account" component={Users} />
      <Route component={NoMatch} />
    </Switch>

);

const Routes =
  !module.hot || process.env.NODE_ENV === 'production'
    ? routes
    : hot(module)(routes);

export default withRouter(Routes);

I am expecting Nav component to be re-rendered when router location changes.

react: ^16.8.6
react-dom: ^16.8.6
react-loadable: ^5.5.0
react-redux: ^6.0.0
react-router-dom: ^4.3.1
redux: ^4.0.0
connected-react-router: ^6.4.0

Body:
I fixed it by saving 'isLoggedIn' state in redux store. And to persist the state from redux store on page refresh, I used 'redux-persist'.

Now Nav component is re-rendering on router location change and the userName data is saved even on page refresh.

authReducer.js

const initialState = {
  isLoggedIn: false,
  userName: '',
};
const auth = (state = initialState, action) => {
  switch (action.type) {
    case types.USER_LOGIN:
      return {
        ...state,
        isLoggedIn: true,
        userName: action.payload,
      };
    case types.USER_LOGOUT:
      return {
        ...state,
        isLoggedIn: false,
        userName: '',
      };
    default:
      return state;
  }
};

nav.js

...
{this.props.isLoggedIn ? (
           ...
          ) : (
           ...
          )}
...

const mapStateToProps = state => ({
  isLoggedIn: state.auth.isLoggedIn,
  userName: state.auth.userName,
});

const mapDispatchToProps = dispatch => ({
  userLogout: () => dispatch(userLogout()),
});

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps,
  )(Nav),
);

[ redux-persist SetUp ]

store.js

import { applyMiddleware, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { composeWithDevTools } from 'redux-devtools-extension';
import { routerMiddleware } from 'connected-react-router';
import createBrowserHistory from 'history/createBrowserHistory';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import createRootReducer from './src/reducers';

export const history = createBrowserHistory();

const persistConfig = {
  key: 'root',
  storage,
};
const persistedReducer = persistReducer(
  persistConfig,
  createRootReducer(history),
);

const store = createStore(
  persistedReducer,
  composeWithDevTools(
    applyMiddleware(
      routerMiddleware(history),
      thunkMiddleware,
      createLogger({
        predicate: () => process.env.NODE_ENV === 'development',
        collapsed: true,
      }),
    ),
  ),
);

export const persistor = persistStore(store);
export default store;

index.js

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter as Router } from 'connected-react-router';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { PersistGate } from 'redux-persist/lib/integration/react';
import store, { history, persistor } from './store';
import Routes from './routes';
import Loading from './src/shared/loading';

const theme = createMuiTheme({
  palette: {
    primary: { main: '#AE9A65' },
    secondary: { main: '#ee9105' },
    success: { main: '#43A047' },
    warning: { main: '#FFA000' },
    error: { main: '#ed4337' },
    info: { main: '#2196F3' },
  },
});

const root = document.createElement('div');
document.body.appendChild(root);

render(
  <Provider store={store}>
    <PersistGate loading={<Loading />} persistor={persistor}>
      <MuiThemeProvider theme={theme}>
        <Router history={history}>
          <Routes />
        </Router>
      </MuiThemeProvider>
    </PersistGate>
  </Provider>,
  root,
);


问:
WSO2 - currently called api on gatewa and integrator
is it possible somewhere in wso2 gw and integrator to watch the number of current calls?
I found nothing in the wso2 documentation</p>

答:
If you need to watch the number of service calls served by EI (WSO2 Integrator ESB-Profile) during that moment, there is no out of the box approach available. But if you need statistics about number of service calls served (and many more statistics) in a given time range, you can use EI-Analytics [1].

[1] https://docs.wso2.com/display/EI640/Working+with+Analytics

Thanks,
Milinda


问:
How do I replace all occurrences of a string in JavaScript?
Given a string:

```<code>s = "Test abc test test abc test test test abc test test abc";
</code>```

This seems to only remove the first occurrence of abc in the string above:

```<code>s = s.replace('abc', '');
</code>```

How do I replace all occurrences of it?

答:
Check this answer. Maybe it will help, and I used it in my project.</p>
```<code>function replaceAll(searchString, replaceString, str) {
    return str.split(searchString).join(replaceString);
}

replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test  test test  test test test  test test "
</code>```

Body:
Given a string:

s = "Test abc test test abc test test test abc test test abc";

This seems to only remove the first occurrence of abc in the string above:

s = s.replace('abc', '');

How do I replace all occurrences of it?

Body:
Check this answer. Maybe it will help, and I used it in my project.

function replaceAll(searchString, replaceString, str) {
    return str.split(searchString).join(replaceString);
}

replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test  test test  test test test  test test "


问:
How can I filter nested objects and arrays with JavaScript?
My use case is something like this.

I have an array that has an object.

That each object has an array called menu

Again that menu array has objected.

That each object has an array dish_has_categories

In dish_has_categories array, if there is an object with CategoryId is equal to 8 I want to filter out that root object.

My original data object

const data = [{
        menuName: "Hot dogs",
        menu: [
            {
            dishId: '1',
            dish_has_categories: [{
                CategoryId: '8'
            }]
        },
         {
            dishId: '2',
            dish_has_categories: [{
                CategoryId: '9'
            }]
        }]
    },
    {
        menuName: "Burgers",
        menu: [{
            dishId: '3',
            dish_has_categories: [{
                CategoryId: '6'
            }]
        }, {
            dishId: '4',
            dish_has_categories: [{
                CategoryId: '4'
            }]
        }]
    },
    {
        name: "Drinks",
        menu: []
    }
]```
</div>
</div>
</p>

<p><strong>My expect result is</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[{
        menuName: "Hot dogs",
        menu: [
            {
            dishId: '1',
            dish_has_categories: [{
                CategoryId: '8'
            }]
        },
         {
            dishId: '2',
            dish_has_categories: [{
                CategoryId: '9'
            }]
        }]
    }]
    </code>```

what I've done up to now is

```<code>const data2 = data.filter(element => {
    return element.menu.length > 0
})
</code>```

I have no idea how to deep filter inside nested objects and arrays. Hope my question is clear to you all.

答:
You can use filter() with nested some().

The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value

const data = [{ menuName: "Hot dogs", menu: [ { dishId: '1', dish_has_categories: [{ CategoryId: '8' }] }, { dishId: '2', dish_has_categories: [{ CategoryId: '9' }] }] }, { menuName: "Burgers", menu: [{ dishId: '3', dish_has_categories: [{ CategoryId: '6' }] }, { dishId: '4', dish_has_categories: [{ CategoryId: '4' }] }] }, { name: "Drinks", menu: [] } ]

const res = data.filter(x =>
                x.menu.some(y =>
                    y.dish_has_categories.some(z => z.CategoryId === '8')
                )
            );
console.log(res)```

Body:
My use case is something like this.

I have an array that has an object.

That each object has an array called menu

Again that menu array has objected.

That each object has an array dish_has_categories

In dish_has_categories array, if there is an object with CategoryId is equal to 8 I want to filter out that root object.

My original data object

const data = [{
        menuName: "Hot dogs",
        menu: [
            {
            dishId: '1',
            dish_has_categories: [{
                CategoryId: '8'
            }]
        },
         {
            dishId: '2',
            dish_has_categories: [{
                CategoryId: '9'
            }]
        }]
    },
    {
        menuName: "Burgers",
        menu: [{
            dishId: '3',
            dish_has_categories: [{
                CategoryId: '6'
            }]
        }, {
            dishId: '4',
            dish_has_categories: [{
                CategoryId: '4'
            }]
        }]
    },
    {
        name: "Drinks",
        menu: []
    }
]

My expect result is

[{
        menuName: "Hot dogs",
        menu: [
            {
            dishId: '1',
            dish_has_categories: [{
                CategoryId: '8'
            }]
        },
         {
            dishId: '2',
            dish_has_categories: [{
                CategoryId: '9'
            }]
        }]
    }]

what I've done up to now is

const data2 = data.filter(element => {
    return element.menu.length > 0
})

I have no idea how to deep filter inside nested objects and arrays. Hope my question is clear to you all.


问:
C++ ostream and ofstream conversions
My code has an ostream object that is accumulated by various modules and ultimately displayed to the console. I'd like ALSO to write this ostreamobject to a file, but do I have to rewrite all of that code using an ofstream object instead, or is there a way to convert one to the other (perhaps via a stringstream?)

For example, many of my existing functions look like

```<code>ostream& ClassObject::output(ostream& os) const
{
    os << "Details";
    return os;
}
</code>```

Can I call this function with an ofstream object as the argument and have that ofstream object accumulate information instead?

答:
ofstream derived from ostream so

Just add some code in main.cpp

```<code>#include "ClassObject"
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
     ClassObject ob;
     cout << ob; // print info to console window

     // save info to .txt file
     ofstream fileout;
     fileout.open("filename.txt", ios::app);
     fileout << ob;
     fileout.close();

     return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C++ ostream and ofstream conversions

Body:
My code has an ostream object that is accumulated by various modules and ultimately displayed to the console. I'd like ALSO to write this ostreamobject to a file, but do I have to rewrite all of that code using an ofstream object instead, or is there a way to convert one to the other (perhaps via a stringstream?)

For example, many of my existing functions look like

ostream& ClassObject::output(ostream& os) const
{
    os << "Details";
    return os;
}

Can I call this function with an ofstream object as the argument and have that ofstream object accumulate information instead?

Body:
ofstream derived from ostream so

Just add some code in main.cpp

#include "ClassObject"
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
     ClassObject ob;
     cout << ob; // print info to console window

     // save info to .txt file
     ofstream fileout;
     fileout.open("filename.txt", ios::app);
     fileout << ob;
     fileout.close();

     return 0;
}


答:
Here is a solution using preg_match, with the following regex pattern:

```<code>window\.DATA_STORE.*?(?=\(function\(\) \{)
</code>```

Sample script:

```<code>$input = "window.DATA_STORE = {
    isMobile: false,
    data: {\"visitsList\":{\"data\":[{\"userId\":\"NkEQmWDdKzwyXKbGMJZj\",\"userName\":\"GeroChile\"}

  };

  (function() { var run = function()";

preg_match('/window\.DATA_STORE.*?(?=\(function\(\) \{)/s', $input, $matches);
print_r($matches);
</code>```

Note carefully that the regex is run in DOT ALL mode, with /s modifier in the call to preg_match.  Here is an explanation of the regex:

```<code>window\.DATA_STORE     match literal "window.DATA_STORE"
.*?                    followed by any content (across lines) until
(?=\(function\(\) \{)  looking ahead and seeing "(function() {"
</code>```

Title: How to match a script using preg_match?

Body:
Here is a solution using preg_match, with the following regex pattern:

window\.DATA_STORE.*?(?=\(function\(\) \{)

Sample script:

$input = "window.DATA_STORE = {
    isMobile: false,
    data: {\"visitsList\":{\"data\":[{\"userId\":\"NkEQmWDdKzwyXKbGMJZj\",\"userName\":\"GeroChile\"}

  };

  (function() { var run = function()";

preg_match('/window\.DATA_STORE.*?(?=\(function\(\) \{)/s', $input, $matches);
print_r($matches);

Note carefully that the regex is run in DOT ALL mode, with /s modifier in the call to preg_match.  Here is an explanation of the regex:

window\.DATA_STORE     match literal "window.DATA_STORE"
.*?                    followed by any content (across lines) until
(?=\(function\(\) \{)  looking ahead and seeing "(function() {"


问:
Android WebView Has started crashing on Android 9
Hello Expert Android Developers:

We have an android app and our basic workflow is as below

User is sent a link via email or text message

User clicks on the link and a page open on Chrome or Android default browser and have a button named JOIN

User clicks on this JOIN button and our app is launched and a page is displayed in webview asking the User to enter the first name, last name and phone/email and then the user clicks on a button named INITIATE

We validate the information - if the user is new, we create a record, it user is existing, we update it etc and then show a popup informing that his session would be recorded.

As soon as the user clicks on OK on the popup and then the control exists the webview and the user is on a native android page.

Problem
As soon as the OK button is tapped on the webview where our native app page would launch normally until a few weeks ago, the app crashes and we would be taken back to the start of the webview page asking us to enter the details.

Please note the below caveats:

First of all, this is happening only in the case of Android 9. We have tested this on Samsung Galaxy S8 and S9. And it doesn't happen every single time but it happens rather regularly, I would say sometimes even 2 out of 3 times. In the best of the times, it has happened 2 out of 10 times but it happens.

This code has been running successfully for the past 1 year or so and we never had this problem. It has only started happening in the last 3-4 weeks.

We also have an iOS app, where the same problem is not observed.

Here is a code snippet that may help - This is how we are loading the webview.

```<code>webview = findViewById(R.id.webview);
    webview.setVisibility(View.VISIBLE);
    final ProgressDialog pd = ProgressDialog.show(ActivtyName.this, "", "Please wait", true);
    webview.setGeolocationEnabled(true);
    webview.setMixedContentAllowed(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setLoadWithOverviewMode(true);

    webview.setWebChromeClient(new WebChromeClient()
</code>```

=======We override a lot of methods here followed by

```<code>webview.setWebViewClient(new WebViewClient()
</code>```

=======We override methods here.

Any idea what might be going on? We have tried looking at the logs while debugging via USB mode, but we don't see much in logs except what is shown on the Android Console like below:

```<code>*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 0, tid: 0 >>> com.a****d.xyzapp <<<
</code>```

backtrace:

```<code>#00  pc 0000000001b61620  /data/app/com.android.chrome-DpcaMBOCm2oa08upmw1Tug==/base.apk
</code>```

Here is the more detailed log as requested:

```<code>2019-05-18 11:58:01.694 23217-23217/com.a**d.xyzapp.debug A/chromium:

[FATAL:crashpad_client_linux.cc(404)] Render process (28925)'s crash wasn't handled by all associated  webviews, triggering application crash.
Fatal signal 5 (SIGTRAP), code 1 (TRAP_BRKPT), fault addr 0x7ab7b9d620 in tid 23217 (atientapp.debug), pid 23217 (atientapp.debug) (edited)
</code>```

答:
I hope this is the same problem which i faced earlier. There are several changes takes place in Android 9 regards of security. So, basically by default it block all urls and domains to use in app which are not secured or SSL Certified.

Network TLS enabled by default
  If your app targets Android 9 or higher, the isCleartextTrafficPermitted() method returns false by default. If your app needs to enable cleartext for specific domains, you must explicitly set cleartextTrafficPermitted to true for those domains in your app's Network Security Configuration.

Either you need to make that domain SSL certified and add this code in manifest

```<code><applicaton ....>
<uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />
</application>
</code>```

also add the code below in your app build.gradle file dependencies block:

```<code>dependencies {
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}
</code>```

and if you are not comfortable with securing your domain right now, then you can also exclude that domain in network configuration. Detailed procedure is mentioned in this page

Security configuration for android

Body:
Hello Expert Android Developers:

We have an android app and our basic workflow is as below

User is sent a link via email or text message

User clicks on the link and a page open on Chrome or Android default browser and have a button named JOIN

User clicks on this JOIN button and our app is launched and a page is displayed in webview asking the User to enter the first name, last name and phone/email and then the user clicks on a button named INITIATE

We validate the information - if the user is new, we create a record, it user is existing, we update it etc and then show a popup informing that his session would be recorded.

As soon as the user clicks on OK on the popup and then the control exists the webview and the user is on a native android page.

Problem
As soon as the OK button is tapped on the webview where our native app page would launch normally until a few weeks ago, the app crashes and we would be taken back to the start of the webview page asking us to enter the details.

Please note the below caveats:

First of all, this is happening only in the case of Android 9. We have tested this on Samsung Galaxy S8 and S9. And it doesn't happen every single time but it happens rather regularly, I would say sometimes even 2 out of 3 times. In the best of the times, it has happened 2 out of 10 times but it happens.

This code has been running successfully for the past 1 year or so and we never had this problem. It has only started happening in the last 3-4 weeks.

We also have an iOS app, where the same problem is not observed.

Here is a code snippet that may help - This is how we are loading the webview.

webview = findViewById(R.id.webview);
    webview.setVisibility(View.VISIBLE);
    final ProgressDialog pd = ProgressDialog.show(ActivtyName.this, "", "Please wait", true);
    webview.setGeolocationEnabled(true);
    webview.setMixedContentAllowed(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setLoadWithOverviewMode(true);

    webview.setWebChromeClient(new WebChromeClient()

=======We override a lot of methods here followed by

webview.setWebViewClient(new WebViewClient()

=======We override methods here.

Any idea what might be going on? We have tried looking at the logs while debugging via USB mode, but we don't see much in logs except what is shown on the Android Console like below:

*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 0, tid: 0 >>> com.a****d.xyzapp <<<

backtrace:

#00  pc 0000000001b61620  /data/app/com.android.chrome-DpcaMBOCm2oa08upmw1Tug==/base.apk

Here is the more detailed log as requested:

2019-05-18 11:58:01.694 23217-23217/com.a**d.xyzapp.debug A/chromium:

[FATAL:crashpad_client_linux.cc(404)] Render process (28925)'s crash wasn't handled by all associated  webviews, triggering application crash.
Fatal signal 5 (SIGTRAP), code 1 (TRAP_BRKPT), fault addr 0x7ab7b9d620 in tid 23217 (atientapp.debug), pid 23217 (atientapp.debug) (edited)

Body:
I hope this is the same problem which i faced earlier. There are several changes takes place in Android 9 regards of security. So, basically by default it block all urls and domains to use in app which are not secured or SSL Certified.

Network TLS enabled by default
  If your app targets Android 9 or higher, the isCleartextTrafficPermitted() method returns false by default. If your app needs to enable cleartext for specific domains, you must explicitly set cleartextTrafficPermitted to true for those domains in your app's Network Security Configuration.

Either you need to make that domain SSL certified and add this code in manifest

<applicaton ....>
<uses-library
            android:name="org.apache.http.legacy"
            android:required="false" />
</application>

also add the code below in your app build.gradle file dependencies block:

dependencies {
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}

and if you are not comfortable with securing your domain right now, then you can also exclude that domain in network configuration. Detailed procedure is mentioned in this page

Security configuration for android


问:
Kerberos delegation: GSSUtil.createSubject returns subject with principal name only
I am doing kerberos delegation. I noticed that GSSUtil.createSubject(context.getSrcName(), clientCred) returns a Subject without having credentials in it.
Prior to that i've done GSSCredential clientCred = context.getDelegCred(); which returns the credentials.
Edit: When I hit my service from one machine in same domain, it works, while if accessed from other machine in same domain, it doesn't.
Confused what additional settings are needed on AD ?
Any help is highly appreciated.

Following is my code:

```<code>public class KerberosTest {

    public Subject loginImpl(byte[] kerberosTicket, String propertiesFileName) throws Exception {
        System.setProperty("sun.security.krb5.debug", "true");
//        // no effect // System.setProperty("javax.security.auth.useSubjectCredsOnly","false");

        final Krb5LoginModule krb5LoginModule = new Krb5LoginModule();
        Subject serviceUserSubject = new Subject();
        final Map<String,String> optionMap = new HashMap<String,String>();
        HashMap<String, String> shared = new HashMap<>();

            optionMap.put("keyTab", "C:\\kerberos_files\\sapuser.keytab");
            optionMap.put("principal", "HTTP/SAPTEST@EQSECTEST.LOCAL"); // default realm
//            optionMap.put("principal", "kerberosuser"); // default realm
            optionMap.put("useFirstPass", "true");
            optionMap.put("doNotPrompt", "true");
            optionMap.put("refreshKrb5Config", "true");
            optionMap.put("useTicketCache", "false");
            optionMap.put("renewTGT", "false");
            optionMap.put("useKeyTab", "true");
            optionMap.put("storeKey", "true");
            optionMap.put("isInitiator", "true");
            optionMap.put("useSubjectCredsOnly", "false");

            optionMap.put("debug", "true"); // switch on debug of the Java implementation
            krb5LoginModule.initialize(serviceUserSubject, null, shared, optionMap);

            // login using details mentioned inside keytab
            boolean loginOk = krb5LoginModule.login();
            System.out.println("Login success: " + loginOk);

            // This API adds Kerberos Credentials to the the Subject's private credentials set
            boolean commitOk = krb5LoginModule.commit();

        }

        System.out.println("Principal from subject: " + serviceUserSubject.getPrincipals()); // this must display name of user to which the keytab corresponds to

        Subject clientSubject = getClientContext(serviceUserSubject, kerberosTicket);
        System.out.println("Client Subject-> " + clientSubject);
        System.out.println("Client principal-> "+clientSubject.getPrincipals().toArray()[0]);

        return clientSubject;
    }

    // Completes the security context initialisation and returns the client name.
    private Subject getClientContext(Subject subject, final byte[] kerberosTicket) throws PrivilegedActionException {
        Subject clientSubject = Subject.doAs(subject, new KerberosValidateAction(kerberosTicket));
        return clientSubject;
    }

    private class KerberosValidateAction implements PrivilegedExceptionAction<Subject> {
        byte[] kerberosTicket;

        public KerberosValidateAction(byte[] kerberosTicket) {
            this.kerberosTicket = kerberosTicket;
        }

        @Override
        public Subject run() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSContext context = gssManager.createContext((GSSCredential) null);

            Oid kerberosOid = new Oid("1.2.840.113554.1.2.2");

//             context.requestCredDeleg(true); // needed when we are demanding ticket from KDC. In our scenario, we are getting ticket from browser(client)

            // Called by the context acceptor upon receiving a token from the peer. This is our context acceptor
            // This method may return an output token which the application will need to send to the peer for further processing by its initSecContext call.
            // We will only accept the incoming token from Peer (browser) and fwd it to third party system
            while (!context.isEstablished()) {
                byte[] nextToken = context.acceptSecContext(kerberosTicket, 0, kerberosTicket.length);
            }

            boolean established = context.isEstablished();
            String user = context.getSrcName().toString();
            String serviceAccnt = context.getTargName().toString();

            //check if the credentials can be delegated
            if (!context.getCredDelegState()) {
                System.out.println("credentials can not be delegated!");
                return null;
            }

            //get the delegated credentials from the calling peer...
            GSSCredential clientCred = context.getDelegCred();
            //Create a Subject out of the delegated credentials.
            //With this Subject the application server can impersonate the client that sent the request.

            Subject clientSubject = GSSUtil.createSubject(context.getSrcName(), clientCred);
            return clientSubject; // ***this contains only principal name and not credentials !!
        }
    }
</code>```

答:
I figured out one important point, which I didn't find anywhere documented. -

While configuring the kerberos service user in AD, "Trust this user for delegation (Kerberos Only)" will come in effect only for new TGTs which are created after this change is saved.

For example, if the user is logged in on client machine A, say at 10:00 AM.

Administrator enables the delegation to kerberos service user at 10:30 AM.

When the user hits an application URL from browser on machine A, the delegation will not work because his TGT is created before the delegation is turned on (at 10:00 AM).

If user logs out from the machine A and relogins, a new TGT will be generated. Delegation works perfectly for this user now.

Body:
I am doing kerberos delegation. I noticed that GSSUtil.createSubject(context.getSrcName(), clientCred) returns a Subject without having credentials in it.
Prior to that i've done GSSCredential clientCred = context.getDelegCred(); which returns the credentials.
Edit: When I hit my service from one machine in same domain, it works, while if accessed from other machine in same domain, it doesn't.
Confused what additional settings are needed on AD ?
Any help is highly appreciated.

Following is my code:

public class KerberosTest {

    public Subject loginImpl(byte[] kerberosTicket, String propertiesFileName) throws Exception {
        System.setProperty("sun.security.krb5.debug", "true");
//        // no effect // System.setProperty("javax.security.auth.useSubjectCredsOnly","false");

        final Krb5LoginModule krb5LoginModule = new Krb5LoginModule();
        Subject serviceUserSubject = new Subject();
        final Map<String,String> optionMap = new HashMap<String,String>();
        HashMap<String, String> shared = new HashMap<>();

            optionMap.put("keyTab", "C:\\kerberos_files\\sapuser.keytab");
            optionMap.put("principal", "HTTP/SAPTEST@EQSECTEST.LOCAL"); // default realm
//            optionMap.put("principal", "kerberosuser"); // default realm
            optionMap.put("useFirstPass", "true");
            optionMap.put("doNotPrompt", "true");
            optionMap.put("refreshKrb5Config", "true");
            optionMap.put("useTicketCache", "false");
            optionMap.put("renewTGT", "false");
            optionMap.put("useKeyTab", "true");
            optionMap.put("storeKey", "true");
            optionMap.put("isInitiator", "true");
            optionMap.put("useSubjectCredsOnly", "false");

            optionMap.put("debug", "true"); // switch on debug of the Java implementation
            krb5LoginModule.initialize(serviceUserSubject, null, shared, optionMap);

            // login using details mentioned inside keytab
            boolean loginOk = krb5LoginModule.login();
            System.out.println("Login success: " + loginOk);

            // This API adds Kerberos Credentials to the the Subject's private credentials set
            boolean commitOk = krb5LoginModule.commit();

        }

        System.out.println("Principal from subject: " + serviceUserSubject.getPrincipals()); // this must display name of user to which the keytab corresponds to

        Subject clientSubject = getClientContext(serviceUserSubject, kerberosTicket);
        System.out.println("Client Subject-> " + clientSubject);
        System.out.println("Client principal-> "+clientSubject.getPrincipals().toArray()[0]);

        return clientSubject;
    }

    // Completes the security context initialisation and returns the client name.
    private Subject getClientContext(Subject subject, final byte[] kerberosTicket) throws PrivilegedActionException {
        Subject clientSubject = Subject.doAs(subject, new KerberosValidateAction(kerberosTicket));
        return clientSubject;
    }

    private class KerberosValidateAction implements PrivilegedExceptionAction<Subject> {
        byte[] kerberosTicket;

        public KerberosValidateAction(byte[] kerberosTicket) {
            this.kerberosTicket = kerberosTicket;
        }

        @Override
        public Subject run() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSContext context = gssManager.createContext((GSSCredential) null);

            Oid kerberosOid = new Oid("1.2.840.113554.1.2.2");

//             context.requestCredDeleg(true); // needed when we are demanding ticket from KDC. In our scenario, we are getting ticket from browser(client)

            // Called by the context acceptor upon receiving a token from the peer. This is our context acceptor
            // This method may return an output token which the application will need to send to the peer for further processing by its initSecContext call.
            // We will only accept the incoming token from Peer (browser) and fwd it to third party system
            while (!context.isEstablished()) {
                byte[] nextToken = context.acceptSecContext(kerberosTicket, 0, kerberosTicket.length);
            }

            boolean established = context.isEstablished();
            String user = context.getSrcName().toString();
            String serviceAccnt = context.getTargName().toString();

            //check if the credentials can be delegated
            if (!context.getCredDelegState()) {
                System.out.println("credentials can not be delegated!");
                return null;
            }

            //get the delegated credentials from the calling peer...
            GSSCredential clientCred = context.getDelegCred();
            //Create a Subject out of the delegated credentials.
            //With this Subject the application server can impersonate the client that sent the request.

            Subject clientSubject = GSSUtil.createSubject(context.getSrcName(), clientCred);
            return clientSubject; // ***this contains only principal name and not credentials !!
        }
    }


问:
ActiveX Command Button that unhides next to a Cell if a value is entered, and hides if the cell is empty
I have 80 rows where the user can enter a predetermined value under column Ward. This unhides a button next to it. Upon clicking it, it empties the adjacent value and increments (+1) a particular cell in another sheet depending on the original value.

Currently, I have 80 ActiveX buttons next to the Ward cells that hides/unhides depending on the value of the Ward cells. I've noticed that adding more buttons slows down the spreadsheet because of the sheer volume of If Then statements I have.

```<code>If Range("F8").Value = 0 Then
  Sheets("Admissions").EDAdmit1.Visible = False
Else
  Sheets("Admissions").EDAdmit1.Visible = True
End If

If Range("L8").Value = 0 Then
  Sheets("Admissions").ElecAdmit1.Visible = False
Else
  Sheets("Admissions").ElecAdmit1.Visible = True
End If

If Range("F9").Value = 0 Then
  Sheets("Admissions").EDAdmit2.Visible = False
Else
  Sheets("Admissions").EDAdmit2.Visible = True
End If

If Range("L9").Value = 0 Then
  Sheets("Admissions").ElecAdmit2.Visible = False
Else
  Sheets("Admissions").ElecAdmit2.Visible = True
End If
</code>```

.. and so on.

Not to mention the If Then statements I have for every button click.

```<code>Private Sub EDAdmit1_Click()
If Range("F8") = "ICU" Then
    Worksheets("Overview").Range("AD11").Value = Worksheets("Overview").Range("AD11") + 1
ElseIf Range("F8") = "HDU" Then
    Worksheets("Overview").Range("AF11").Value = Worksheets("Overview").Range("AF11") + 1
ElseIf Range("F8") = "DPU" Or Range("F8") = "Other" Then
Else
    Col = WorksheetFunction.VLookup(Range("F8"), Range("U1:V27"), 2)
    Worksheets("Overview").Range(Col).Value = Worksheets("Overview").Range(Col).Value + 1
End If
Range("F8").ClearContents
End Sub
</code>```

Is there a more efficient way of doing this?

Admission List:

答:
You could consider using "admit" hyperlinks in the cells next to the Ward selections: that way you only need one handler (Worksheet_FollowHyperlink in the worksheet module).  Note you need to use Insert >> Hyperlink and not the HYPERLINK() formula-type links here (because formula-based links don't trigger the FollowHyperlink event).

You can ditch the hide/show code and instead use conditional formatting to change the link font color to hide the links when there's no Ward selected.  If a user clicks on one of the hidden links then you can just do nothing.

```<code>Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

    Dim rngSrc As Range, addr, ward

    Set rngSrc = Target.Range        '<< the cell with the link
    ward = rngSrc.Offset(0, 1).Value '<< cell with Ward

    'only do anything if a ward is selected
    If Len(ward) > 0 Then
        'find the cell to update
        Select Case ward
            Case "ICU"
                addr = "AD11"
            Case "HDU"
                addr = "AF11"
            Case "DPU", "Other"
                addr = ""
            Case Else
                addr = Application.VLookup(ward, Me.Range("U1:V27"), 2, False)
        End Select

        'if we have a cell to update then
        If Len(addr) > 0 Then
            With Worksheets("Overview").Range(addr)
                .Value = .Value + 1
            End With
        End If
        rngSrc.Offset(0, 1).ClearContents
    End If

    rngSrc.Select '<< select the clicked-on link cell
                  '   (in case the link points elsewhere)

End Sub
</code>```

Body:
I have 80 rows where the user can enter a predetermined value under column Ward. This unhides a button next to it. Upon clicking it, it empties the adjacent value and increments (+1) a particular cell in another sheet depending on the original value.

Currently, I have 80 ActiveX buttons next to the Ward cells that hides/unhides depending on the value of the Ward cells. I've noticed that adding more buttons slows down the spreadsheet because of the sheer volume of If Then statements I have.

If Range("F8").Value = 0 Then
  Sheets("Admissions").EDAdmit1.Visible = False
Else
  Sheets("Admissions").EDAdmit1.Visible = True
End If

If Range("L8").Value = 0 Then
  Sheets("Admissions").ElecAdmit1.Visible = False
Else
  Sheets("Admissions").ElecAdmit1.Visible = True
End If

If Range("F9").Value = 0 Then
  Sheets("Admissions").EDAdmit2.Visible = False
Else
  Sheets("Admissions").EDAdmit2.Visible = True
End If

If Range("L9").Value = 0 Then
  Sheets("Admissions").ElecAdmit2.Visible = False
Else
  Sheets("Admissions").ElecAdmit2.Visible = True
End If

.. and so on.

Not to mention the If Then statements I have for every button click.

Private Sub EDAdmit1_Click()
If Range("F8") = "ICU" Then
    Worksheets("Overview").Range("AD11").Value = Worksheets("Overview").Range("AD11") + 1
ElseIf Range("F8") = "HDU" Then
    Worksheets("Overview").Range("AF11").Value = Worksheets("Overview").Range("AF11") + 1
ElseIf Range("F8") = "DPU" Or Range("F8") = "Other" Then
Else
    Col = WorksheetFunction.VLookup(Range("F8"), Range("U1:V27"), 2)
    Worksheets("Overview").Range(Col).Value = Worksheets("Overview").Range(Col).Value + 1
End If
Range("F8").ClearContents
End Sub

Is there a more efficient way of doing this?

Admission List:

Body:
You could consider using "admit" hyperlinks in the cells next to the Ward selections: that way you only need one handler (Worksheet_FollowHyperlink in the worksheet module).  Note you need to use Insert >> Hyperlink and not the HYPERLINK() formula-type links here (because formula-based links don't trigger the FollowHyperlink event).

You can ditch the hide/show code and instead use conditional formatting to change the link font color to hide the links when there's no Ward selected.  If a user clicks on one of the hidden links then you can just do nothing.

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)

    Dim rngSrc As Range, addr, ward

    Set rngSrc = Target.Range        '<< the cell with the link
    ward = rngSrc.Offset(0, 1).Value '<< cell with Ward

    'only do anything if a ward is selected
    If Len(ward) > 0 Then
        'find the cell to update
        Select Case ward
            Case "ICU"
                addr = "AD11"
            Case "HDU"
                addr = "AF11"
            Case "DPU", "Other"
                addr = ""
            Case Else
                addr = Application.VLookup(ward, Me.Range("U1:V27"), 2, False)
        End Select

        'if we have a cell to update then
        If Len(addr) > 0 Then
            With Worksheets("Overview").Range(addr)
                .Value = .Value + 1
            End With
        End If
        rngSrc.Offset(0, 1).ClearContents
    End If

    rngSrc.Select '<< select the clicked-on link cell
                  '   (in case the link points elsewhere)

End Sub


问:
php regular expression to get the specific url
I would like to get the urls from a webpage that starts with "../category/" from these tags below:

```<code><a href="../category/product/pc.html" target="_blank">PC</a><br>
<a href="../category/product/carpet.html" target="_blank">Carpet</a><br>
</code>```

Any suggestion would be very much appreciated.

Thanks!

答:
This regex searches for your ../category/ string:

```<code>preg_match_all('#......="(\.\./category/.*?)"#', $test, $matches);
</code>```

All text literals are used for matching. You can replace the ..... to make it more specific. Only the \. need escaping. The .*? looks for a variable length string. And () captures the matched path name, so it appears in $matches. The manual explains the rest of the syntax. http://www.php.net/manual/en/book.pcre.php

Body:
I would like to get the urls from a webpage that starts with "../category/" from these tags below:

PC

Carpet

Any suggestion would be very much appreciated.

Thanks!

Body:
This regex searches for your ../category/ string:

preg_match_all('#......="(\.\./category/.*?)"#', $test, $matches);

All text literals are used for matching. You can replace the ..... to make it more specific. Only the \. need escaping. The .*? looks for a variable length string. And () captures the matched path name, so it appears in $matches. The manual explains the rest of the syntax. http://www.php.net/manual/en/book.pcre.php


问:
Firebase cloud function not running?
I have written the bellow code to detect when a comment has been added to the DB and then to respond by updating a timeline node the issue is that it does not actually update. Why is it not working?

```<code>    export const onCommentAdded = functions.database
.ref('/Comments/{receiverUID}/{postID}/{mediaNum}/{commentID}')
.onCreate((snapshot, context) => {
  const uid = context.params.uid
  const newCommentUID = snapshot.child("UID").val()
  console.log(newCommentUID, " the comment")
  return addNewCommentNotif(uid, newCommentUID)
})

function addNewCommentNotif(uuid: string, newCommentUID: string) {

  //NotifTimeline/uid/NewNotif (someuniqueVal)/commentID
  const randID = Math.floor(100000000 + Math.random() * 900000000);
  const notifTimelineRef = admin.database().ref("NotifTimeline").child(uuid).child(newCommentUID + ":" + randID).child("NewComment")

  notifTimelineRef.set(newCommentUID)//update
  .then(() => {
    console.log("Success updating this uid comment timeline")
  })
  .catch((error: string) => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
  return Promise.resolve();
}
</code>```

答:
Return the promise that was returned by set():</p>

```<code>function addNewCommentNotif(uuid: string, newCommentUID: string) {

  //NotifTimeline/uid/NewNotif (someuniqueVal)/commentID
  const randID = Math.floor(100000000 + Math.random() * 900000000);
  const notifTimelineRef = admin.database().ref("NotifTimeline").child(uuid).child(newCommentUID + ":" + randID).child("NewComment")

  return notifTimelineRef.set(newCommentUID)//update
  .then(() => {
    console.log("Success updating this uid comment timeline")
  })
  .catch((error: string) => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
}
</code>```

Title: Firebase cloud function not running?

Body:
I have written the bellow code to detect when a comment has been added to the DB and then to respond by updating a timeline node the issue is that it does not actually update. Why is it not working?

    export const onCommentAdded = functions.database
.ref('/Comments/{receiverUID}/{postID}/{mediaNum}/{commentID}')
.onCreate((snapshot, context) => {
  const uid = context.params.uid
  const newCommentUID = snapshot.child("UID").val()
  console.log(newCommentUID, " the comment")
  return addNewCommentNotif(uid, newCommentUID)
})

function addNewCommentNotif(uuid: string, newCommentUID: string) {

  //NotifTimeline/uid/NewNotif (someuniqueVal)/commentID
  const randID = Math.floor(100000000 + Math.random() * 900000000);
  const notifTimelineRef = admin.database().ref("NotifTimeline").child(uuid).child(newCommentUID + ":" + randID).child("NewComment")

  notifTimelineRef.set(newCommentUID)//update
  .then(() => {
    console.log("Success updating this uid comment timeline")
  })
  .catch((error: string) => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
  return Promise.resolve();
}

Body:
Return the promise that was returned by set():

function addNewCommentNotif(uuid: string, newCommentUID: string) {

  //NotifTimeline/uid/NewNotif (someuniqueVal)/commentID
  const randID = Math.floor(100000000 + Math.random() * 900000000);
  const notifTimelineRef = admin.database().ref("NotifTimeline").child(uuid).child(newCommentUID + ":" + randID).child("NewComment")

  return notifTimelineRef.set(newCommentUID)//update
  .then(() => {
    console.log("Success updating this uid comment timeline")
  })
  .catch((error: string) => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
}


答:
You can use filter and some

Here nested some is used to check whether any of dish_has_categories has CategoryId equal to '8', if it is true then we include that menu in final output else we don't

const data =[{ menuName: "Hot dogs", menu: [ { dishId: '1', dish_has_categories: [{ CategoryId: '8' }] }, { dishId: '2', dish_has_categories: [{ CategoryId: '9' }] }] }, { menuName: "Burgers", menu: [{ dishId: '3', dish_has_categories: [{ CategoryId: '6' }] }, { dishId: '4', dish_has_categories: [{ CategoryId: '4' }] }] }, { name: "Drinks", menu: [] } ]

let op = data.filter(val => {
  let menu = val.menu.some(({dish_has_categories}) => dish_has_categories.some(({CategoryId}) => CategoryId === '8'))
  return menu
})

console.log('filtered values -->\n',op)

let names = op.map(({menuName})=> menuName)

console.log('Names --> \n', names)```

Title: How can I filter nested objects and arrays with JavaScript?


问:
Why logical OR working differently if change the order contains terinary operator
Why below code is giving different outputs?

var test;

var output = test ? 'Test' : 'No Test' || true;
var output2 = true || test ? 'Test' : 'No Test'

console.log(output); // No Test
console.log(output2); // Test```

答:
Because of operator precedence. The conditional operator has precedence 4, while logical OR has precedence 5, so your code is equivalent to:

var test;

var output = test ? 'Test' : ('No Test' || true);
//      undefined ? 'Test' : 'No Test'
var output2 = (true || test) ? 'Test' : 'No Test'
//                      true ? 'Test' : 'No Test'

console.log(output);
console.log(output2);```

The OR grouping has a higher priority - its surrounding tokens are grouped together first.

Body:
Because of operator precedence. The conditional operator has precedence 4, while logical OR has precedence 5, so your code is equivalent to:

var test;

var output = test ? 'Test' : ('No Test' || true);
//      undefined ? 'Test' : 'No Test'
var output2 = (true || test) ? 'Test' : 'No Test'
//                      true ? 'Test' : 'No Test'

console.log(output);
console.log(output2);

The OR grouping has a higher priority - its surrounding tokens are grouped together first.


答:
```<code>var output2 = true || test ? 'Test' : 'No Test'
</code>```

in this above code you used true thats why it has printed Test your conditional operator here got as true

```<code>var output2 = test ? 'Test' : 'No Test'
</code>```

if you have tried like this it will print No Test

var test;

var output = test ? 'Test' : 'No Test' || true;
var output2 = test ? 'Test' : 'No Test'

console.log(output); // No Test
console.log(output2); // Test```

Title: Why logical OR working differently if change the order contains terinary operator

Body:
Why below code is giving different outputs?

var test;

var output = test ? 'Test' : 'No Test' || true;
var output2 = true || test ? 'Test' : 'No Test'

console.log(output); // No Test
console.log(output2); // Test

Body:
var output2 = true || test ? 'Test' : 'No Test'

in this above code you used true thats why it has printed Test your conditional operator here got as true

var output2 = test ? 'Test' : 'No Test'

if you have tried like this it will print No Test

var test;

var output = test ? 'Test' : 'No Test' || true;
var output2 = test ? 'Test' : 'No Test'

console.log(output); // No Test
console.log(output2); // Test


问:
$text $search on array field in mongoDB with Nodejs
I want to do a $text $search on a mongoDB collection where the documents have a field that is an array of fields.

My query is returning false for some reason. Can't figure it out as I've already put an index on "conditions.description" in the collection.

Example Document in collection

```<code>{
  "_id": "58f9c87b5246af0aac145ew",
  "total": 2,
  "patientId": "xxxxxxx",
  "conditions": [
    {
      "verificationStatus": "confirmed",
      "dateRecorded": "2017-03-14",
      "clinicalStatus": "active",
      "description": "Afib"
    },
    {
      "verificationStatus": "confirmed",
      "dateRecorded": "2017-03-14",
      "clinicalStatus": "active",
      "description": "Arterial hypertension"
    }
  ]
}
</code>```

My MongoDB Query that is returning false

```<code>
.find({
       "$and": [
          { "patientId": { $eq: pID } },
          { "conditions.description": { $text: { $search: "diabetes hypertension" }, $caseSensitive: false } }
        ]
})
</code>```

答:
As per the documentation you do not provide field for the $text search:

```<code>db.getCollection('YourCollection').find({
   "$and": [
      { "patientId": { $eq: pID } },
      { $text: { $search: "diabetes hypertension" } }
    ]
})
</code>```

Body:
I want to do a $text $search on a mongoDB collection where the documents have a field that is an array of fields.

My query is returning false for some reason. Can't figure it out as I've already put an index on "conditions.description" in the collection.

Example Document in collection

{
  "_id": "58f9c87b5246af0aac145ew",
  "total": 2,
  "patientId": "xxxxxxx",
  "conditions": [
    {
      "verificationStatus": "confirmed",
      "dateRecorded": "2017-03-14",
      "clinicalStatus": "active",
      "description": "Afib"
    },
    {
      "verificationStatus": "confirmed",
      "dateRecorded": "2017-03-14",
      "clinicalStatus": "active",
      "description": "Arterial hypertension"
    }
  ]
}

My MongoDB Query that is returning false

.find({
       "$and": [
          { "patientId": { $eq: pID } },
          { "conditions.description": { $text: { $search: "diabetes hypertension" }, $caseSensitive: false } }
        ]
})

Body:
As per the documentation you do not provide field for the $text search:

db.getCollection('YourCollection').find({
   "$and": [
      { "patientId": { $eq: pID } },
      { $text: { $search: "diabetes hypertension" } }
    ]
})


问:
How can I count how many times value X is used in column1, when column2="Y"?
I also need to group that info by Column3.

I could do it almost everything, except for "when column2="y". The code I've tried is this one:

```<code>select column3 ,count(column1) as asd
from maps
group by column3;
</code>```

If my table is, for example,

```<code>Month | Day          |  Column3
1     | Sun                YES
1     | Mon                NO
1     | Tue                NO
1     | Wed                YES
1     | Thu                YES
1     | Fri                NO
1     | Sun                YES
1     | Mon                YES
1     | Tue                YES
2     | Wed                NO
</code>```

I expect for example, looking for the times where Column3= "YES", group by Day, when month=1. Thus, I expect to obtain something like this

```<code>Month | Day          |     asd
1     | Sun                2
1     | Mon                1
1     | Tue                1
1     | Wed                1
1     | Thu                1
1     | Fri                0
</code>```

答:
For this you use a where clause.

```<code>select column3 ,count(column1) as asd
from maps
where column2 = 'y'
group by column3;
</code>```

So maybe, given this: Column3= "YES", group by Day, when month=1.:

```<code>select day ,count(*) as count
from maps
where month = 1 and column3 = 'YES'
group by day;
</code>```

Body:
I also need to group that info by Column3.

I could do it almost everything, except for "when column2="y". The code I've tried is this one:

select column3 ,count(column1) as asd
from maps
group by column3;

If my table is, for example,

Month | Day          |  Column3
1     | Sun                YES
1     | Mon                NO
1     | Tue                NO
1     | Wed                YES
1     | Thu                YES
1     | Fri                NO
1     | Sun                YES
1     | Mon                YES
1     | Tue                YES
2     | Wed                NO

I expect for example, looking for the times where Column3= "YES", group by Day, when month=1. Thus, I expect to obtain something like this

Month | Day          |     asd
1     | Sun                2
1     | Mon                1
1     | Tue                1
1     | Wed                1
1     | Thu                1
1     | Fri                0

Body:
For this you use a where clause.

select column3 ,count(column1) as asd
from maps
where column2 = 'y'
group by column3;

So maybe, given this: Column3= "YES", group by Day, when month=1.:

select day ,count(*) as count
from maps
where month = 1 and column3 = 'YES'
group by day;


问:
slurm: Fatal Error: No front end nodes defined
I was installing SLURM to set up a small cluster at home for Molecular Dynamics Simulations on Ubuntu Server.

I have installed it according to the instructions listed here:
http://54.194.218.233/philipwfowler/2016/04/28/setting-up-a-gromacs-cluster/5/

My configuration file looks like this:

http://txt.do/dppin

When starting slurmctld I get this error message:

http://txt.do/dppib

Has anyone ever experienced this error, I'm kind of helpless as there is not information on the web.

Best regards,

TheCShaprFreak

答: Uninstall the slurmctld-wlm-emulator package. Your slurmctld is pointing to the emulator instead of the real package.


问:
What is preventing me from using $_ in a pipeline?
The command git branch --list | select-string 2362 gives me a list of several branches that fit the pattern 2362.  I want to delete all of those branches on the server.

The command git branch --list | select-string 2362 | git push origin --delete $_ gives me the error fatal: --delete doesn't make sense without any refs, which is the same error I get from the command git push origin --delete.  It is as though $_ is empty, as though there are no branches found which match the pattern.

What am I doing wrong?

答:
I came up with this "one-liner":

```<code>git branch --list | ? { $_ -like "*2362*" } | Select-Object -first 1 | % {
    git push origin --delete ($_ -replace "[:\*]",  " ").Trim()
}
</code>```

Select-Object is used to only delete one branch, of course, it can be removed. Leading star and : gets replaced. Spaces are trimmed.

Hope that helps

Body:
I came up with this "one-liner":

git branch --list | ? { $_ -like "*2362*" } | Select-Object -first 1 | % {
    git push origin --delete ($_ -replace "[:\*]",  " ").Trim()
}

Select-Object is used to only delete one branch, of course, it can be removed. Leading star and : gets replaced. Spaces are trimmed.

Hope that helps


答:
Try Using

```<code>        android:usesCleartextTraffic="true"
</code>```

in application tag -
in Your AndroidManifest

Title: Android WebView Has started crashing on Android 9

Body:
Hello Expert Android Developers:

We have an android app and our basic workflow is as below

User is sent a link via email or text message

User clicks on the link and a page open on Chrome or Android default browser and have a button named JOIN

User clicks on this JOIN button and our app is launched and a page is displayed in webview asking the User to enter the first name, last name and phone/email and then the user clicks on a button named INITIATE

We validate the information - if the user is new, we create a record, it user is existing, we update it etc and then show a popup informing that his session would be recorded.

As soon as the user clicks on OK on the popup and then the control exists the webview and the user is on a native android page.

Problem
As soon as the OK button is tapped on the webview where our native app page would launch normally until a few weeks ago, the app crashes and we would be taken back to the start of the webview page asking us to enter the details.

Please note the below caveats:

First of all, this is happening only in the case of Android 9. We have tested this on Samsung Galaxy S8 and S9. And it doesn't happen every single time but it happens rather regularly, I would say sometimes even 2 out of 3 times. In the best of the times, it has happened 2 out of 10 times but it happens.

This code has been running successfully for the past 1 year or so and we never had this problem. It has only started happening in the last 3-4 weeks.

We also have an iOS app, where the same problem is not observed.

Here is a code snippet that may help - This is how we are loading the webview.

webview = findViewById(R.id.webview);
    webview.setVisibility(View.VISIBLE);
    final ProgressDialog pd = ProgressDialog.show(ActivtyName.this, "", "Please wait", true);
    webview.setGeolocationEnabled(true);
    webview.setMixedContentAllowed(true);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setLoadWithOverviewMode(true);

    webview.setWebChromeClient(new WebChromeClient()

=======We override a lot of methods here followed by

webview.setWebViewClient(new WebViewClient()

=======We override methods here.

Any idea what might be going on? We have tried looking at the logs while debugging via USB mode, but we don't see much in logs except what is shown on the Android Console like below:

*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 0, tid: 0 >>> com.a****d.xyzapp <<<

backtrace:

#00  pc 0000000001b61620  /data/app/com.android.chrome-DpcaMBOCm2oa08upmw1Tug==/base.apk

Here is the more detailed log as requested:

2019-05-18 11:58:01.694 23217-23217/com.a**d.xyzapp.debug A/chromium:

[FATAL:crashpad_client_linux.cc(404)] Render process (28925)'s crash wasn't handled by all associated  webviews, triggering application crash.
Fatal signal 5 (SIGTRAP), code 1 (TRAP_BRKPT), fault addr 0x7ab7b9d620 in tid 23217 (atientapp.debug), pid 23217 (atientapp.debug) (edited)

Body:
Try Using

        android:usesCleartextTraffic="true"

in application tag -
in Your AndroidManifest


问:
How to pass parameters in headers
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

```<code>checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}
</code>```

In Node,

```<code>router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });
</code>```

答:
```<code>const headerOptions = {
     headers : new HttpHeaders({
       'Constent-Type' : 'application/json',
       'Authorization : 'you token here'
     })
   }

http.post('you action', {body Params}, headerOptions, function(res){
console.log('your respose is ', res);
})
</code>```

Title: How to pass parameters in headers

Body:
I need to call an API from my Angular Node application.For that i have to pass username and password along with header request.How to pass parameters?
I tried below code

From Angular service,

checkUserApi(url: string): Observable<any> {
   const headers = new HttpHeaders()
    .set('Authorization', 'my-auth-token')
    .set('Content-Type', 'application/json')
    .set('userName','prismtest')
    .set('password','12345678');
   return this.http.post('/upload/checkUserApi/', { headers })
  .map((response: Response) => {
    console.log(response);
   return response;
   })
}

In Node,

router.post('/checkUserApi',function(req,res,next){
var proxyUrl = 'http://cors-anywhere.herokuapp.com/';

Request.post({
  "headers": { "userName": "prismtest","password":"12345678" },
  "url": proxyUrl+"https://example.com",
  "body": {}
  }, (error, response, body) => {

  if(error) {
   return console.log(error);
  }
   res.send(response);
  });
  });