问:
Terraform error - Error: Argument or block definition required
My terraform code is as below:

```<code>terraform {
  backend "remote" {
    hostname     = "hostname.com"
    organization = "companyname"
    workspaces {
      name = "GIT-TIO-DEV"
    }
  }
}

provider "aws" {
  region = "us-east-1"
  version = "~> 2.22"
}

locals {
  aws_region                      = "us-east-1"
  ami_id                          = "ami-000db10762d0c4c05"
  appid_tag                       = "S00012"
  env_tag                         = "dev"
  name_tag                        = "TESTINSTANCE"
  awsaccount_tag                  = "myaccount"
  createdby_tag                   = "testuser"
  keyName                         = "tst-cloudservices-portal-dev"
  securityGroup                   = "sg-wwwwwwwww"
  vpc_id                          = "vpc-aaaaaaaaaaaaa"
  patchgroup_tag                  = "GroupA"
  iam_role                        = "tst-SR-ServiceRole"
  division_tag                    = "TIO"
  application_segment_tag         = "DEV"
  notes_tag                       = "link to notes 2"
  function_tag                    = "portal server"
  os_tag                          = "RHEL76"
  platform_tag                    = "Linux"
  instance_type                   = "t2.micro"
  automation_server_count         = 2
}

variable "health_check" {
  description = "A health check block"
  type        = map(string)
  default = {
  "enabled" = "true",
  "port" = "443",
  "protocol" = "https"
  }

 }

variable listener {
[
    {
        instance_port = "80"
        instance_protocol = "tcp"
    },
    {
        instance_port = "443"
        instance_protocol = "tcp"
    }
]

}
# Adding EC2 afer Security Group

module "tst-security-group-ec2" {
  source                          = "hostname.com/companyname/tst-security-group/aws"
  version                         = "1.0.2"
  group_name                      = "tst-myaccount-portal-dev"
  group_description               = "security group for portal dev"
  vpc_id                          = local.vpc_id
  appid_tag                       = local.appid_tag
  env_tag                         = local.env_tag
  awsaccount_tag                  = local.awsaccount_tag
  createdby_tag                   = local.createdby_tag
  function_tag                    = "Security group for portal dev"
  ingress = [{
    from_port   = 22
    to_port     = 22
    protocol    = "TCP"
    cidr_blocks = ["10.0.0.0/8"]
  },{
    from_port   = 3389
    to_port     = 3389
    protocol    = "TCP"
    cidr_blocks = ["10.0.0.0/8"]
    },{
    from_port   = -1
    to_port     = -1
    protocol    = "icmp"
    cidr_blocks = ["10.0.0.0/8"]
  }]
  egress =[ {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }]
}
module "ec2-rhel-automation-server" {
  source                          = "hostname.com/companyname/tst-ec2-instance-rhel/aws"
  version                         = "1.2.6"
  aws_region                      = local.aws_region
  vpc_id                          = local.vpc_id
  ami_id                          = local.ami_id
  appid_tag                       = local.appid_tag
  application_segment_tag         = local.application_segment_tag
  awsaccount_tag                  = local.awsaccount_tag
  createdby_tag                   = local.createdby_tag
  default_security_group_id       = module.tst-security-group-ec2.id
  division_tag                    = local.division_tag
  env_tag                         = local.env_tag
  function_tag                    = local.function_tag
  keyName                         = local.keyName
  name_tag                        = "RHEL-AS${local.env_tag}"
  notes_tag                       = local.notes_tag
  os_tag                          = local.os_tag
  platform_tag                    = local.platform_tag
  ec2_server_count                = local.automation_server_count
  instance_type                   = local.instance_type
  hostname_tag                    = "ERNST${local.env_tag}WEB"
  iam_role                        = "tst-SR-ServiceRole"
  bootstrap_instance              = "false"
    }

// Adding ALB Security Group
module "tst-security-group-alb" {
  source                          = "hostname.com/companyname/tst-security-group/aws"
  version                         = "1.0.2"
  group_name                      = "tst-myaccount-portal-dev"
  group_description               = "security group for ALB"
  vpc_id                          = local.vpc_id
  appid_tag                       = local.appid_tag
  env_tag                         = local.env_tag
  awsaccount_tag                  = local.awsaccount_tag
  createdby_tag                   = local.createdby_tag
  function_tag                    = "Security group for ALB"
  ingress = [{
    from_port   = 443
    to_port     = 443
    protocol    = "TCP"
    cidr_blocks = ["10.0.0.0/8"]

   }]
  egress =[ {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }]
}
// Creating a ALB
module "tst-alb" {
  source                          = "hostname.com/companyname/tst-alb/aws"
  version                         = "1.0.5"
  subnets                         = ["subnet-xxxxxxxxxxxxx","subnet-yyyyyyyyyyy","subnet-zzzzzzzzzzzzz"]
  listener                        = var.listener
  createdby_tag                   = local.createdby_tag
  function_tag                    = "Terraform created ALB"
  vpc_id                          = local.vpc_id
  awsaccount_tag                  = local.awsaccount_tag
  appid_tag                       = local.appid_tag
  security_groups                 = module.tst-security-group-alb.id
  env_tag                         = local.env_tag
  health_check                    = var.health_check
}
</code>```

Unfortunately, I am getting an error like below:

```<code>Error: Argument or block definition required

  on main.tf line 52, in variable "listener":
  52: [

An argument or block definition is required here.
</code>```

I am going to create a separate variable file later. At the moment I want to get basic skeleton working.

答:
variable listener must be variable "listener". You are missing double quotes

a map should look like the below

```<code>variable "amis" {
 type = "map"
 default = {
   "us-east-1" = "ami-b374d5a5"
   "us-west-2" = "ami-4b32be2b"
 }
}
</code>```

Finally, the variable listener is missing its definition. You have an array of key value pairs, but you are not specifying what type or description of the variable.

Body:
My terraform code is as below:

terraform {
  backend "remote" {
    hostname     = "hostname.com"
    organization = "companyname"
    workspaces {
      name = "GIT-TIO-DEV"
    }
  }
}

provider "aws" {
  region = "us-east-1"
  version = "~> 2.22"
}

locals {
  aws_region                      = "us-east-1"
  ami_id                          = "ami-000db10762d0c4c05"
  appid_tag                       = "S00012"
  env_tag                         = "dev"
  name_tag                        = "TESTINSTANCE"
  awsaccount_tag                  = "myaccount"
  createdby_tag                   = "testuser"
  keyName                         = "tst-cloudservices-portal-dev"
  securityGroup                   = "sg-wwwwwwwww"
  vpc_id                          = "vpc-aaaaaaaaaaaaa"
  patchgroup_tag                  = "GroupA"
  iam_role                        = "tst-SR-ServiceRole"
  division_tag                    = "TIO"
  application_segment_tag         = "DEV"
  notes_tag                       = "link to notes 2"
  function_tag                    = "portal server"
  os_tag                          = "RHEL76"
  platform_tag                    = "Linux"
  instance_type                   = "t2.micro"
  automation_server_count         = 2
}

variable "health_check" {
  description = "A health check block"
  type        = map(string)
  default = {
  "enabled" = "true",
  "port" = "443",
  "protocol" = "https"
  }

 }

variable listener {
[
    {
        instance_port = "80"
        instance_protocol = "tcp"
    },
    {
        instance_port = "443"
        instance_protocol = "tcp"
    }
]

}
# Adding EC2 afer Security Group

module "tst-security-group-ec2" {
  source                          = "hostname.com/companyname/tst-security-group/aws"
  version                         = "1.0.2"
  group_name                      = "tst-myaccount-portal-dev"
  group_description               = "security group for portal dev"
  vpc_id                          = local.vpc_id
  appid_tag                       = local.appid_tag
  env_tag                         = local.env_tag
  awsaccount_tag                  = local.awsaccount_tag
  createdby_tag                   = local.createdby_tag
  function_tag                    = "Security group for portal dev"
  ingress = [{
    from_port   = 22
    to_port     = 22
    protocol    = "TCP"
    cidr_blocks = ["10.0.0.0/8"]
  },{
    from_port   = 3389
    to_port     = 3389
    protocol    = "TCP"
    cidr_blocks = ["10.0.0.0/8"]
    },{
    from_port   = -1
    to_port     = -1
    protocol    = "icmp"
    cidr_blocks = ["10.0.0.0/8"]
  }]
  egress =[ {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }]
}
module "ec2-rhel-automation-server" {
  source                          = "hostname.com/companyname/tst-ec2-instance-rhel/aws"
  version                         = "1.2.6"
  aws_region                      = local.aws_region
  vpc_id                          = local.vpc_id
  ami_id                          = local.ami_id
  appid_tag                       = local.appid_tag
  application_segment_tag         = local.application_segment_tag
  awsaccount_tag                  = local.awsaccount_tag
  createdby_tag                   = local.createdby_tag
  default_security_group_id       = module.tst-security-group-ec2.id
  division_tag                    = local.division_tag
  env_tag                         = local.env_tag
  function_tag                    = local.function_tag
  keyName                         = local.keyName
  name_tag                        = "RHEL-AS${local.env_tag}"
  notes_tag                       = local.notes_tag
  os_tag                          = local.os_tag
  platform_tag                    = local.platform_tag
  ec2_server_count                = local.automation_server_count
  instance_type                   = local.instance_type
  hostname_tag                    = "ERNST${local.env_tag}WEB"
  iam_role                        = "tst-SR-ServiceRole"
  bootstrap_instance              = "false"
    }

// Adding ALB Security Group
module "tst-security-group-alb" {
  source                          = "hostname.com/companyname/tst-security-group/aws"
  version                         = "1.0.2"
  group_name                      = "tst-myaccount-portal-dev"
  group_description               = "security group for ALB"
  vpc_id                          = local.vpc_id
  appid_tag                       = local.appid_tag
  env_tag                         = local.env_tag
  awsaccount_tag                  = local.awsaccount_tag
  createdby_tag                   = local.createdby_tag
  function_tag                    = "Security group for ALB"
  ingress = [{
    from_port   = 443
    to_port     = 443
    protocol    = "TCP"
    cidr_blocks = ["10.0.0.0/8"]

   }]
  egress =[ {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }]
}
// Creating a ALB
module "tst-alb" {
  source                          = "hostname.com/companyname/tst-alb/aws"
  version                         = "1.0.5"
  subnets                         = ["subnet-xxxxxxxxxxxxx","subnet-yyyyyyyyyyy","subnet-zzzzzzzzzzzzz"]
  listener                        = var.listener
  createdby_tag                   = local.createdby_tag
  function_tag                    = "Terraform created ALB"
  vpc_id                          = local.vpc_id
  awsaccount_tag                  = local.awsaccount_tag
  appid_tag                       = local.appid_tag
  security_groups                 = module.tst-security-group-alb.id
  env_tag                         = local.env_tag
  health_check                    = var.health_check
}

Unfortunately, I am getting an error like below:

Error: Argument or block definition required

  on main.tf line 52, in variable "listener":
  52: [

An argument or block definition is required here.

I am going to create a separate variable file later. At the moment I want to get basic skeleton working.

Body:
variable listener must be variable "listener". You are missing double quotes

a map should look like the below

variable "amis" {
 type = "map"
 default = {
   "us-east-1" = "ami-b374d5a5"
   "us-west-2" = "ami-4b32be2b"
 }
}

Finally, the variable listener is missing its definition. You have an array of key value pairs, but you are not specifying what type or description of the variable.


来源: stackexchange

问:
[React-Context]: Form validation error fails to show up the first time
Validation error in my login form shows only upon clicking submit button a 2nd time with incorrect login credentials. Im noticing that even though the state is updating, error message is not being rendered the first time itself. It requires a 2nd submit click to be able to see the error message Snackbar.

I have defined a separate auth-context which has all the logic for making a post request for login and performing error handling, validations as well as setting user data to localStorage. It also has context providers to supply current state value. Login.js is using this auth-context to make a post request and based on the state either logs in or (is supposed to) displays validation errors.

Here's part of my Login.js page Component:

```<code>import { useAuth } from '../../context/auth-context';
export default function Login() {
  const classes = useStyles();
  const { handleChange, handleSubmit, formValues, formErrors } = useForm(submit, validate);
  const [errorAlertMsg, setErrorAlertMsg] = useState('');
  const authState = useAuth();

  function submit() {
    authState.login(formValues);
    if(authState.error){
      setErrorAlertMsg(authState.error);
    }
/*authState initially shows error as null instead of the validation error. After submit is clicked it stays that way upon reaching here. On 2nd submit click it shows*/
    console.log(authState);
  }

  function closeAlertHandler() {
    setErrorAlertMsg('');
  }

  function Alert(props) {
    return <MuiAlert elevation={6} variant="filled" {...props} />;
  }

  return (
    <div>
    <Grid container>
        <Grid
            item xs={4}
            direction='row'
        >
            <UnauthenticatedSidebar/>
        </Grid>
        <Grid
            item xs={8}
            direction='row' >

          <Container className={classes.mainContainer} component="main" maxWidth="xs">
            <CssBaseline />
            <Grid container justify='flex-end'>
                  <Grid item>
                    <Typography classes = {{ body2: classes.body2Style }} component="p" variant="body2">
                      Don't have an account?
                      <Link className={classes.routerLink} to='/signup'>
                      <Button color='primary' classes = {{ root: classes.buttonMarginRight }} variant="outlined" size="large">
                          Create Account
                      </Button>
                      </Link>
                      </Typography>
                  </Grid>
            </Grid>
            <div className={classes.paper}>
              <Typography className={classes.welcomeHeading} component="h2" variant="h4">
                Welcome Back!
              </Typography>
              <form onSubmit= { handleSubmit } className={classes.form} noValidate>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <TextField
                      required
                      fullWidth
                      id="email"
                      label="Email Address"
                      name="email"
                      autoComplete="email"
                      InputProps = {{
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      InputLabelProps = {{
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      value={ formValues.email }
                      onChange = { handleChange }
                      error = { formErrors.email }
                      helperText = { formErrors.email || null }
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <TextField
                      required
                      fullWidth
                      name="password"
                      label="Password"
                      type="password"
                      id="password"
                      autoComplete="current-password"
                      InputProps = {{
                        endAdornment: <InputAdornment position='end'>
                          <Typography className={classes.adornmentStyle}>
                           Forgot?
                           </Typography>
                          </InputAdornment>,
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      InputLabelProps = {{
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      value={formValues.password}
                      onChange= { handleChange }
                      error = { formErrors.password }
                      helperText= { formErrors.password || null}
                    />
                  </Grid>
                </Grid>
                <Button
                  type="submit"
                  variant="contained"
                  color="primary"
                  className={classes.submit}
                >
                  Login
                </Button>
              </form>
              <Snackbar open = {errorAlertMsg.length !== 0} autoHideDuration={5000} onClose = { closeAlertHandler }>
                          <Alert onClose={closeAlertHandler} severity="error">
                            {errorAlertMsg}
                          </Alert>
              </Snackbar>
            </div>
          </Container>
        </Grid>
    </Grid>
</div>
  );
}
</code>```

Here's the auth-context.js file

```<code>import React, { useState } from 'react';
import axios from 'axios';

const AuthContext = React.createContext([{}, () => {}]);
function AuthProvider({children}) {
  const [state, setState] = React.useState({
    status: 'logged out',
    error: null,
    user: null
  });

  const [token, setToken] = useState(localStorage.getItem('authToken') ? localStorage.getItem('authToken') : null);
  const [email, setEmail] = useState(localStorage.getItem('email') ? localStorage.getItem('email'): null);

  //checking for token and email and then accordingly updating the state
  const getUser = () => {
    if(token) {
      setState({status: 'success', error: null, user: email})
    }
  }

  const logout = () => {
    localStorage.removeItem('authToken');
    setToken(null);
    localStorage.removeItem('email');
    setEmail(null);
    setState({status: 'logged out', error: null, user: null})
  }

  const login = async(formValues) => {
    try {
      const res = await axios.post('http://localhost:3001/user/login', formValues);
      if(res.data.token) {
        setState({status:'success', error:null, user: formValues.email});
        localStorage.setItem('authToken', res.data.token);
        setToken(res.data.token);

        localStorage.setItem('email', res.data.email);
        setEmail(res.data.email);
      }
    }
    catch(err) {
      const validationError = err.response.data.validationError || null;
      const missingDataError = err.response.data.missingData || null;
      if(validationError){
        setState({status: 'error', error: validationError, user: null})
      }
      else if(missingDataError) {
        setState({status: 'error', error: missingDataError, user: null})
      }
      else {
        console.error(err);
      }
    }
  }

  React.useEffect(() => {
    getUser();
  }, [token, email]);

  let authState = {...state, logout, login}

  /**
   * Provider component is the place where you'd pass a prop called value to,
   * which you can subsequently consume within the Consumer component
   */
  return (
    <AuthContext.Provider value={authState}>
      {state.status === 'pending' ? (
        'Loading...'
      ) : state.status === 'logged out' ? (
        children
      ) : (
        children
      )}
    </AuthContext.Provider>
  )
}

//this seems simpler method to pass functions from context to consumers
function useAuth() {
  const context = React.useContext(AuthContext)
  if (context === undefined) {
    throw new Error(`useAuth must be used within a AuthProvider`)
  }
  return context;
}
export {AuthProvider, useAuth};
</code>```

答:
There are two issues in here

login is an asynchronous function

State updates are bound by closure in functional component and do not reflect in the same render cycle.

Since you are using authState.error immediately after calling authState.login, you don't see the updated value.

The solution is to make use of useEffect and wait for the authState to change

```<code>function submit() {
   authState.login(formValues);
}

useEffect(() => {
    if(authState.error){
      setErrorAlertMsg(authState.error);
    }
    console.log(authState);
}, [authState]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Validation error in my login form shows only upon clicking submit button a 2nd time with incorrect login credentials. Im noticing that even though the state is updating, error message is not being rendered the first time itself. It requires a 2nd submit click to be able to see the error message Snackbar.

I have defined a separate auth-context which has all the logic for making a post request for login and performing error handling, validations as well as setting user data to localStorage. It also has context providers to supply current state value. Login.js is using this auth-context to make a post request and based on the state either logs in or (is supposed to) displays validation errors.

Here's part of my Login.js page Component:

import { useAuth } from '../../context/auth-context';
export default function Login() {
  const classes = useStyles();
  const { handleChange, handleSubmit, formValues, formErrors } = useForm(submit, validate);
  const [errorAlertMsg, setErrorAlertMsg] = useState('');
  const authState = useAuth();

  function submit() {
    authState.login(formValues);
    if(authState.error){
      setErrorAlertMsg(authState.error);
    }
/*authState initially shows error as null instead of the validation error. After submit is clicked it stays that way upon reaching here. On 2nd submit click it shows*/
    console.log(authState);
  }

  function closeAlertHandler() {
    setErrorAlertMsg('');
  }

  function Alert(props) {
    return <MuiAlert elevation={6} variant="filled" {...props} />;
  }

  return (

    <Grid container>
        <Grid
            item xs={4}
            direction='row'
        >
            <UnauthenticatedSidebar/>
        </Grid>
        <Grid
            item xs={8}
            direction='row' >

          <Container className={classes.mainContainer} component="main" maxWidth="xs">
            <CssBaseline />
            <Grid container justify='flex-end'>
                  <Grid item>
                    <Typography classes = {{ body2: classes.body2Style }} component="p" variant="body2">
                      Don't have an account?
                      <Link className={classes.routerLink} to='/signup'>
                      <Button color='primary' classes = {{ root: classes.buttonMarginRight }} variant="outlined" size="large">
                          Create Account
                      </Button>
                      </Link>
                      </Typography>
                  </Grid>
            </Grid>

              <Typography className={classes.welcomeHeading} component="h2" variant="h4">
                Welcome Back!
              </Typography>
              <form onSubmit= { handleSubmit } className={classes.form} noValidate>
                <Grid container spacing={2}>
                  <Grid item xs={12}>
                    <TextField
                      required
                      fullWidth
                      id="email"
                      label="Email Address"
                      name="email"
                      autoComplete="email"
                      InputProps = {{
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      InputLabelProps = {{
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      value={ formValues.email }
                      onChange = { handleChange }
                      error = { formErrors.email }
                      helperText = { formErrors.email || null }
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <TextField
                      required
                      fullWidth
                      name="password"
                      label="Password"
                      type="password"
                      id="password"
                      autoComplete="current-password"
                      InputProps = {{
                        endAdornment: <InputAdornment position='end'>
                          <Typography className={classes.adornmentStyle}>
                           Forgot?
                           </Typography>
                          </InputAdornment>,
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      InputLabelProps = {{
                        classes: {root: classes.textFieldSelectLabel}
                      }}
                      value={formValues.password}
                      onChange= { handleChange }
                      error = { formErrors.password }
                      helperText= { formErrors.password || null}
                    />
                  </Grid>
                </Grid>
                <Button
                  type="submit"
                  variant="contained"
                  color="primary"
                  className={classes.submit}
                >
                  Login
                </Button>
              </form>
              <Snackbar open = {errorAlertMsg.length !== 0} autoHideDuration={5000} onClose = { closeAlertHandler }>
                          <Alert onClose={closeAlertHandler} severity="error">
                            {errorAlertMsg}
                          </Alert>
              </Snackbar>

          </Container>
        </Grid>
    </Grid>

  );
}

Here's the auth-context.js file

import React, { useState } from 'react';
import axios from 'axios';

const AuthContext = React.createContext([{}, () => {}]);
function AuthProvider({children}) {
  const [state, setState] = React.useState({
    status: 'logged out',
    error: null,
    user: null
  });

  const [token, setToken] = useState(localStorage.getItem('authToken') ? localStorage.getItem('authToken') : null);
  const [email, setEmail] = useState(localStorage.getItem('email') ? localStorage.getItem('email'): null);

  //checking for token and email and then accordingly updating the state
  const getUser = () => {
    if(token) {
      setState({status: 'success', error: null, user: email})
    }
  }

  const logout = () => {
    localStorage.removeItem('authToken');
    setToken(null);
    localStorage.removeItem('email');
    setEmail(null);
    setState({status: 'logged out', error: null, user: null})
  }

  const login = async(formValues) => {
    try {
      const res = await axios.post('http://localhost:3001/user/login', formValues);
      if(res.data.token) {
        setState({status:'success', error:null, user: formValues.email});
        localStorage.setItem('authToken', res.data.token);
        setToken(res.data.token);

        localStorage.setItem('email', res.data.email);
        setEmail(res.data.email);
      }
    }
    catch(err) {
      const validationError = err.response.data.validationError || null;
      const missingDataError = err.response.data.missingData || null;
      if(validationError){
        setState({status: 'error', error: validationError, user: null})
      }
      else if(missingDataError) {
        setState({status: 'error', error: missingDataError, user: null})
      }
      else {
        console.error(err);
      }
    }
  }

  React.useEffect(() => {
    getUser();
  }, [token, email]);

  let authState = {...state, logout, login}

  /**
   * Provider component is the place where you'd pass a prop called value to,
   * which you can subsequently consume within the Consumer component
   */
  return (
    <AuthContext.Provider value={authState}>
      {state.status === 'pending' ? (
        'Loading...'
      ) : state.status === 'logged out' ? (
        children
      ) : (
        children
      )}
    </AuthContext.Provider>
  )
}

//this seems simpler method to pass functions from context to consumers
function useAuth() {
  const context = React.useContext(AuthContext)
  if (context === undefined) {
    throw new Error(`useAuth must be used within a AuthProvider`)
  }
  return context;
}
export {AuthProvider, useAuth};

Body:
There are two issues in here

login is an asynchronous function

State updates are bound by closure in functional component and do not reflect in the same render cycle.

Since you are using authState.error immediately after calling authState.login, you don't see the updated value.

The solution is to make use of useEffect and wait for the authState to change

function submit() {
   authState.login(formValues);
}

useEffect(() => {
    if(authState.error){
      setErrorAlertMsg(authState.error);
    }
    console.log(authState);
}, [authState]);


问:
Centered modal load spinner bootstrap 4
I want a modal load spinner and have based a test on Bootstrap 4's modal dialog box. However, I can't get the modal horizontally centered on the page. If possible, I would also like the modal to be with no borders and transparent (so it appears that only the spinner is hovering over the page)

 function modal(){
       $('.modal').modal('show');
       setTimeout(function () {
        console.log('hejsan');
        $('.modal').modal('hide');
       }, 3000);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>

<button type="button" class="btn btn-primary" onclick="modal();">Open and close in 3 secs</button>

<div class="modal fade bd-example-modal-lg" data-backdrop="static" data-keyboard="false" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content" style="width: 48px">
            <span class="fa fa-spinner fa-spin fa-3x"></span>
        </div>
    </div>
</div>
<p>I would like the <ul><li>spinner horizontally centered on page<li> the modal transparent without borders</ul></p></code>```

答:
Bootstrap 4.x using d-flex and justify-content-center classes.

            Loading...

```

ContentLicense: CC BY-SA 3.0

Title: Centered modal load spinner bootstrap 4

Body:
I want a modal load spinner and have based a test on Bootstrap 4's modal dialog box. However, I can't get the modal horizontally centered on the page. If possible, I would also like the modal to be with no borders and transparent (so it appears that only the spinner is hovering over the page)

 function modal(){
       $('.modal').modal('show');
       setTimeout(function () {
        console.log('hejsan');
        $('.modal').modal('hide');
       }, 3000);
    }

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<button type="button" class="btn btn-primary" onclick="modal();">Open and close in 3 secs</button>

I would like the

spinner horizontally centered on page
 the modal transparent without borders

Body:
Bootstrap 4.x using d-flex and justify-content-center classes.

<div class="modal fade" id="loadingModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered d-flex justify-content-center" role="document">
        <div class="spinner-border" role="status">
            <span class="sr-only">Loading...</span>
        </div>
    </div>
</div>


问:
cURL not working (Error #77) for SSL connections on CentOS for non-root users
Just recently my server has stopped working for curl requests to https:// addresses for my web server.  Having dug around a little it appears that it's a problem with the user the webserver is running.

If I SSH onto the server as root & call

```<code>curl -I -v https://google.com
</code>```

... I get the following response...

```<code>* About to connect() to google.com port 443 (#0)
*   Trying 173.194.67.113... connected
* Connected to google.com (173.194.67.113) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* SSL connection using SSL_RSA_WITH_RC4_128_SHA
* Server certificate:
*       subject: CN=*.google.com,O=Google Inc,L=Mountain View,ST=California,C=US
*       start date: May 22 15:50:20 2013 GMT
*       expire date: Oct 31 23:59:59 2013 GMT
*       common name: *.google.com
*       issuer: CN=Google Internet Authority,O=Google Inc,C=US
> HEAD / HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: google.com
> Accept: */*
</code>```

However, if I log in as any of the cPanel accounts (also used when running via the web server) I get the following...

```<code>* About to connect() to google.com port 443 (#0)
*   Trying 173.194.67.101... connected
* Connected to google.com (173.194.67.101) port 443 (#0)
* Initializing NSS with certpath: none
* NSS error -5978
* Closing connection #0
* Problem with the SSL CA cert (path? access rights?)
curl: (77) Problem with the SSL CA cert (path? access rights?)
</code>```

I've not been able to find a definitive answer to the problem, & my hosting company are refusing to help as it's "Out of support" even though it was working fine last week!

I did find mention on http://curl.haxx.se/docs/sslcerts.html that

"If libcurl was built with NSS support, then depending on the OS distribution,
  it is probably required to take some additional steps to use the system-wide CA
  cert db. RedHat ships with an additional module, libnsspem.so, which enables
  NSS to read the OpenSSL PEM CA bundle. This library is missing in OpenSuSE, and
  without it, NSS can only work with its own internal formats. NSS also has a new
  database format: https://wiki.mozilla.org/NSS_Shared_DB"

... but I can find no information on how I get this working system-wide on my CentOS server.

Info

```<code>curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp
Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz
</code>```

Can anyone shed some light on why this might have suddenly changed, or better still how to fix it?

Thanks

答: Please check the permissions on the the ca certificates installed on server. </p>

Body:
Just recently my server has stopped working for curl requests to https:// addresses for my web server.  Having dug around a little it appears that it's a problem with the user the webserver is running.

If I SSH onto the server as root & call

curl -I -v https://google.com

... I get the following response...

* About to connect() to google.com port 443 (#0)
*   Trying 173.194.67.113... connected
* Connected to google.com (173.194.67.113) port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* SSL connection using SSL_RSA_WITH_RC4_128_SHA
* Server certificate:
*       subject: CN=*.google.com,O=Google Inc,L=Mountain View,ST=California,C=US
*       start date: May 22 15:50:20 2013 GMT
*       expire date: Oct 31 23:59:59 2013 GMT
*       common name: *.google.com
*       issuer: CN=Google Internet Authority,O=Google Inc,C=US
> HEAD / HTTP/1.1
> User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
> Host: google.com
> Accept: */*

However, if I log in as any of the cPanel accounts (also used when running via the web server) I get the following...

* About to connect() to google.com port 443 (#0)
*   Trying 173.194.67.101... connected
* Connected to google.com (173.194.67.101) port 443 (#0)
* Initializing NSS with certpath: none
* NSS error -5978
* Closing connection #0
* Problem with the SSL CA cert (path? access rights?)
curl: (77) Problem with the SSL CA cert (path? access rights?)

I've not been able to find a definitive answer to the problem, & my hosting company are refusing to help as it's "Out of support" even though it was working fine last week!

I did find mention on http://curl.haxx.se/docs/sslcerts.html that

"If libcurl was built with NSS support, then depending on the OS distribution,
  it is probably required to take some additional steps to use the system-wide CA
  cert db. RedHat ships with an additional module, libnsspem.so, which enables
  NSS to read the OpenSSL PEM CA bundle. This library is missing in OpenSuSE, and
  without it, NSS can only work with its own internal formats. NSS also has a new
  database format: https://wiki.mozilla.org/NSS_Shared_DB"

... but I can find no information on how I get this working system-wide on my CentOS server.

Info

curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
Protocols: tftp ftp telnet dict ldap ldaps http file https ftps scp sftp
Features: GSS-Negotiate IDN IPv6 Largefile NTLM SSL libz

Can anyone shed some light on why this might have suddenly changed, or better still how to fix it?

Thanks


问:
SQL where clause with case statement
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

```<code>AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END
</code>```

I'm not sure how to process the -1 to say select all users

Thanks

答:
```<code>usertable.userid = COALESCE(NULLIF(@user, -1), usertable.userid)
</code>```

Title: SQL where clause with case statement

Body:
I have a problem with SQL that I have not yet found a solution to, what im trying to do is a where clause for a procedure where a userID variable can contain either a valid userID or -1 to indicate all users.

However im stuck at this part of the where clause:

AND usertable.userid = CASE WHEN @user = -1
THEN

ELSE
  @user
END

I'm not sure how to process the -1 to say select all users

Thanks


问:
Why doesn't the 'exists' method evaluate to true even though the document does exist in Firebase?
I'm finding a very weird behaviour in my program. At first, businesses can sign up and go to a businessesPendingAdminApproval firestore collection. While they are in that collection, the 2nd if statement below snapshotPending.exists works (evaluates to true).

However, after an admin accepts the business (moves it to the approvedBusinesses collection), snapshotApproved.exists evaluates to false, even though it does exist in that collection. That happens whether I refresh the page or not.

```<code>useEffect(() => {
    async function getOfferedServicesFromDB() {
      const approved = await db.collection('approvedBusinesses').doc(businessId)
      const snapshotApproved = await approved.get()
      //why does the below evaluate to false even though it does exist?
      if (snapshotApproved.exists) { //always evaluates to false
        //...
      } else {
        const pending = await db.collection('businessesPendingAdminApproval').doc(businessId)
        const snapshotPending = await pending.get()
        if (snapshotPending.exists) //evaluates to true while in businessesPendingAdminApproval'
          //...
      }
      return
    }

    getOfferedServicesFromDB()
  }, [])
</code>```

答:
try

```<code>const approved = db.collection('approvedBusinesses').doc(businessId)
</code>```

or

```<code>const snapshotApproved = await db.collection('approvedBusinesses').doc(businessId).get()
</code>```

Body:
I'm finding a very weird behaviour in my program. At first, businesses can sign up and go to a businessesPendingAdminApproval firestore collection. While they are in that collection, the 2nd if statement below snapshotPending.exists works (evaluates to true).

However, after an admin accepts the business (moves it to the approvedBusinesses collection), snapshotApproved.exists evaluates to false, even though it does exist in that collection. That happens whether I refresh the page or not.

useEffect(() => {
    async function getOfferedServicesFromDB() {
      const approved = await db.collection('approvedBusinesses').doc(businessId)
      const snapshotApproved = await approved.get()
      //why does the below evaluate to false even though it does exist?
      if (snapshotApproved.exists) { //always evaluates to false
        //...
      } else {
        const pending = await db.collection('businessesPendingAdminApproval').doc(businessId)
        const snapshotPending = await pending.get()
        if (snapshotPending.exists) //evaluates to true while in businessesPendingAdminApproval'
          //...
      }
      return
    }

    getOfferedServicesFromDB()
  }, [])

Body:
try

const approved = db.collection('approvedBusinesses').doc(businessId)

or

const snapshotApproved = await db.collection('approvedBusinesses').doc(businessId).get()


问:
Parallelize apply after pandas groupby
I have used rosetta.parallel.pandas_easy to parallelize apply after groupby, for example:

```<code>from rosetta.parallel.pandas_easy import groupby_to_series_to_frame
df = pd.DataFrame({'a': [6, 2, 2], 'b': [4, 5, 6]},index= ['g1', 'g1', 'g2'])
groupby_to_series_to_frame(df, np.mean, n_jobs=8, use_apply=True, by=df.index)
</code>```

However, has anyone figured out how to parallelize a function that returns a DataFrame? This code fails for rosetta, as expected.

```<code>def tmpFunc(df):
    df['c'] = df.a + df.b
    return df

df.groupby(df.index).apply(tmpFunc)
groupby_to_series_to_frame(df, tmpFunc, n_jobs=1, use_apply=True, by=df.index)
</code>```

答:
EDIT: To achieve better calculation performance on pandas groupby, you can use numba to compile your code into C code at runtime and run at C speed. If the function you apply after groupby is pure numpy calculation, it will be super fast (much faster than this parallelization).

You can use either multiprocessing or joblib to achieve parallelization. However, if the number of groups is large and each group DataFrame is large, the running time can be worse as you need to transfer those groups into CPUs for many times. To reduce the overhead, we can first divide the data into large chunks, and then parallelize computation on these chunks.

For example, suppose you are processing the stock data, where you need to group the stocks by their code and then calculate some statistics. You can first group by the first character of the code (large chunks), then do the things within this dummy group:

import pandas as pd
from joblib import Parallel, delayed

def group_func(dummy_group):
    # Do something to the group just like doing to the original dataframe.
    #     Example: calculate daily return.
    res = []
    for _, g in dummy_group.groupby('code'):
        g['daily_return']  = g.close / g.close.shift(1)
        res.append(g)
    return pd.concat(res)

stock_data = stock_data.assign(dummy=stock_data['code'].str[0])

Parallel(n_jobs=-1)(delayed(group_func)(group) for _, group in stock_data.groupby('dummy'))
```

Title: Parallelize apply after pandas groupby

Body:
I have used rosetta.parallel.pandas_easy to parallelize apply after groupby, for example:

from rosetta.parallel.pandas_easy import groupby_to_series_to_frame
df = pd.DataFrame({'a': [6, 2, 2], 'b': [4, 5, 6]},index= ['g1', 'g1', 'g2'])
groupby_to_series_to_frame(df, np.mean, n_jobs=8, use_apply=True, by=df.index)

However, has anyone figured out how to parallelize a function that returns a DataFrame? This code fails for rosetta, as expected.

def tmpFunc(df):
    df['c'] = df.a + df.b
    return df

df.groupby(df.index).apply(tmpFunc)
groupby_to_series_to_frame(df, tmpFunc, n_jobs=1, use_apply=True, by=df.index)


问:
Pandas importing from 12 excel documents - FileNotFoundError: [Errno 2] No such file or directory: 'x'
Python novice- I've attempted to trial and error through solutions that came up when I searched the above error. Whenever I've used pandas in the past, I've used while loops to go through each individual file before opening a new file to add information to my dataframe. Here, my goal is simply to get last week's data from different sectors via pdr.over_ride().

It downloads the files properly, but when trying to assign columns as a variable (works when I do them one at a time via while loop), I keep getting the FileNotFoundError: [Errno 2] No such file or directory: 'x' error.

I don't see where I'm asking python to grab a file named 'x', and have searched stackexchange and tried looking through pandas documentation to find a solution. Any help or a point in the direction towards a solution, or an alternative method would be greatly appreciated.

Here is the full error, and then my code:

```<code>Traceback (most recent call last):
  File "c:/Users/jchil/Desktop/python/Finance/MarketWatch.py", line 45, in <module>
    df0 = pd.read_excel(savename[0], 'Sheet1')
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 304, in read_excel
    io = ExcelFile(io, engine=engine)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 824, in __init__
    self._reader = self._engines[engine](self._io)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_xlrd.py", line 21, in __init__
    super().__init__(filepath_or_buffer)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 353, in __init__
    self.book = self.load_workbook(filepath_or_buffer)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_xlrd.py", line 36, in load_workbook
    return open_workbook(filepath_or_buffer)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\xlrd\__init__.py", line 111, in open_workbook
    with open(filename, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'x'
</code>```

```<code>from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
from matplotlib import style
from money import Money
import yfinance as yf
import pandas as pd
import numpy as np
import datetime
import sys
import re
import os

spiders = {
    '^GSPC': 'S&P 500', 'xlp': 'consumer staples select sector', 'xly': 'consumer discretionary select sector',
    'xlk': 'technology select sector', 'xlv': 'health care select sector', 'xli': 'industrials select sector',
    'xlu': 'utilities select sector', 'xlb': 'materials select sector', 'xle': 'energy select sector',
    'xlf': 'financial select sector', 'xlre': 'real estate select sector', 'xlc': 'communication services select sector'}

keys, values = zip(*spiders.items())
print ("keys : ", str(keys))

begin = "2020-05-01"
through = "2020-06-01"

yf.pdr_override()

collecting = True
savelist = []
j = 0

while collecting == True:
    #index = pdr.get_data_yahoo(keys[j], start=begin, end=through)
    #saver = index.to_excel(str(keys[j]) + '.xlsx')
    savename = str(keys[j]) + '.xlsx'
    savelist.append(savename)
    print(savelist)
    j = j + 1

    if j == len(values):
        collecting = False

df0 = pd.read_excel(savename[0], 'Sheet1')
df1 = pd.read_excel(savename[1], 'Sheet1')
df2 = pd.read_excel(savename[2], 'Sheet1')
df3 = pd.read_excel(savename[3], 'Sheet1')
df4 = pd.read_excel(savename[4], 'Sheet1')
df5 = pd.read_excel(savename[5], 'Sheet1')
df6 = pd.read_excel(savename[6], 'Sheet1')
df7 = pd.read_excel(savename[7], 'Sheet1')
df8 = pd.read_excel(savename[8], 'Sheet1')
df9 = pd.read_excel(savename[9], 'Sheet1')
df10 = pd.read_excel(savename[10], 'Sheet1')
df11 = pd.read_excel(savename[11], 'Sheet1')

date = df0['Date']
snp = df0['Adj Close']
xlp = df1['Adj Close']
xly = df2['Adj Close']
xlk = df3['Adj Close']
xlv = df4['Adj Close']
xli = df5['Adj Close']
xlu = df6['Adj Close']
xlb = df7['Adj Close']
xle = df8['Adj Close']
xlf = df9['Adj Close']
xlre = df10['Adj Close']
xlc = df11['Adj Close']'''
</code>```

答: i think you want the accumulator variable savelist for each of the read_excel statements, not savename which is the variable youre using inside the loop. as written, this will take each character of the last value of savename and interpret it as a filename.

Body:
Python novice- I've attempted to trial and error through solutions that came up when I searched the above error. Whenever I've used pandas in the past, I've used while loops to go through each individual file before opening a new file to add information to my dataframe. Here, my goal is simply to get last week's data from different sectors via pdr.over_ride().

It downloads the files properly, but when trying to assign columns as a variable (works when I do them one at a time via while loop), I keep getting the FileNotFoundError: [Errno 2] No such file or directory: 'x' error.

I don't see where I'm asking python to grab a file named 'x', and have searched stackexchange and tried looking through pandas documentation to find a solution. Any help or a point in the direction towards a solution, or an alternative method would be greatly appreciated.

Here is the full error, and then my code:

Traceback (most recent call last):
  File "c:/Users/jchil/Desktop/python/Finance/MarketWatch.py", line 45, in <module>
    df0 = pd.read_excel(savename[0], 'Sheet1')
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 304, in read_excel
    io = ExcelFile(io, engine=engine)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 824, in __init__
    self._reader = self._engines[engine](self._io)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_xlrd.py", line 21, in __init__
    super().__init__(filepath_or_buffer)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_base.py", line 353, in __init__
    self.book = self.load_workbook(filepath_or_buffer)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_xlrd.py", line 36, in load_workbook
    return open_workbook(filepath_or_buffer)
  File "C:\Users\jchil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\xlrd\__init__.py", line 111, in open_workbook
    with open(filename, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'x'

from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
from matplotlib import style
from money import Money
import yfinance as yf
import pandas as pd
import numpy as np
import datetime
import sys
import re
import os

spiders = {
    '^GSPC': 'S&P 500', 'xlp': 'consumer staples select sector', 'xly': 'consumer discretionary select sector',
    'xlk': 'technology select sector', 'xlv': 'health care select sector', 'xli': 'industrials select sector',
    'xlu': 'utilities select sector', 'xlb': 'materials select sector', 'xle': 'energy select sector',
    'xlf': 'financial select sector', 'xlre': 'real estate select sector', 'xlc': 'communication services select sector'}

keys, values = zip(*spiders.items())
print ("keys : ", str(keys))

begin = "2020-05-01"
through = "2020-06-01"

yf.pdr_override()

collecting = True
savelist = []
j = 0

while collecting == True:
    #index = pdr.get_data_yahoo(keys[j], start=begin, end=through)
    #saver = index.to_excel(str(keys[j]) + '.xlsx')
    savename = str(keys[j]) + '.xlsx'
    savelist.append(savename)
    print(savelist)
    j = j + 1

    if j == len(values):
        collecting = False

df0 = pd.read_excel(savename[0], 'Sheet1')
df1 = pd.read_excel(savename[1], 'Sheet1')
df2 = pd.read_excel(savename[2], 'Sheet1')
df3 = pd.read_excel(savename[3], 'Sheet1')
df4 = pd.read_excel(savename[4], 'Sheet1')
df5 = pd.read_excel(savename[5], 'Sheet1')
df6 = pd.read_excel(savename[6], 'Sheet1')
df7 = pd.read_excel(savename[7], 'Sheet1')
df8 = pd.read_excel(savename[8], 'Sheet1')
df9 = pd.read_excel(savename[9], 'Sheet1')
df10 = pd.read_excel(savename[10], 'Sheet1')
df11 = pd.read_excel(savename[11], 'Sheet1')

date = df0['Date']
snp = df0['Adj Close']
xlp = df1['Adj Close']
xly = df2['Adj Close']
xlk = df3['Adj Close']
xlv = df4['Adj Close']
xli = df5['Adj Close']
xlu = df6['Adj Close']
xlb = df7['Adj Close']
xle = df8['Adj Close']
xlf = df9['Adj Close']
xlre = df10['Adj Close']
xlc = df11['Adj Close']'''


问:
Adding x-pack enabled Elasticsearch behind AWS application load balancer causing health check failure due to missing authentication
I was using Application load balancer(ALB) on my elasticsearch node and configured the health check as shown in image and health check was working fine and I was able to reach to my ES using load balancer.

Now I added x-pack security which requires even for health check to pass a user(Elastic super user and its password) in my case and after that health check stopped working as ALB can't pass the basic authentication and due to this issue Health check is not working and as shown in image ALB is continuously de-registering the Elasticsearch which in turn causing my Elasticsearch docker to stop/start.

Note:- I am using ES 7.7 if its relevant to this question.

答:
Based on the comments, the problem is caused by the fact that ALB health checks fail since failed authentication returns 401 HTTP code, not 200.

The solution is to use 401 code as the expected code for the health check. The failure of authentication still means that the ES is up and running, not that it ES failed.


问:
MySql order by specific ID values
Is it possible to sort in MySQL by "order by" using a predefined set of column values (ID) like order by (ID=1,5,4,3) so I would get records 1, 5, 4, 3 in that order out?

UPDATE: Why I need this...

I want my records to change sort randomly every 5 minutes. I have a cron task to update the table to put different, random sort order in it.

There is just one problem! PAGINATION.

I will have visitors who come to my page, and I will give them the first 20 results. They will wait 6 minutes, go to page 2 and have the wrong results as the sort order has already changed.

So I thought that if I put all the IDs into a session on page 2, we get the correct records even if the sorting had already changed.

Is there any other better way to do this?

答:
If you want to order a single id last in the result, use the order by the case. (Eg: you want "other" option in last and all city list show in alphabetical order.)

select id,city
from city
order by case
when id = 2 then city else -1
end, city ASC
```
<p>If i had 5 city for example, i want to show the city in alphabetical order with "other" option display last in the dropdown then we can use this query.
see example other are showing in my table at second id(id:2) so i am using "when id = 2" in above query.</p>
<p>record in DB table:</p>
```Bangalore - id:1
Other     - id:2
Mumbai    - id:3
Pune      - id:4
Ambala    - id:5
```
<p>my output:</p>
```Ambala
Bangalore
Mumbai
Pune
Other
```

Title: MySql order by specific ID values

Body:
If you want to order a single id last in the result, use the order by the case. (Eg: you want "other" option in last and all city list show in alphabetical order.)

select id,city
from city
order by case
when id = 2 then city else -1
end, city ASC

If i had 5 city for example, i want to show the city in alphabetical order with "other" option display last in the dropdown then we can use this query.
see example other are showing in my table at second id(id:2) so i am using "when id = 2" in above query.

record in DB table:

Bangalore - id:1
Other     - id:2
Mumbai    - id:3
Pune      - id:4
Ambala    - id:5

my output:

Ambala
Bangalore
Mumbai
Pune
Other


问:
Why I can't do arithmetic operations in console input "cin"?
I am a beginner to C++. I am having some trouble or doubt;
The thing is, I am giving an arithmetic operation such as 2+2 in user input cin>>. But in return it gives output of 2!

Code:

```<code>#include "iostream"
using namespace std;
int main(){
    int t;
    cin>>t;      // Here I Have Given 2+2
    cout<<t;     // Instead of giving 4; It is giving me 2
    return 0;
}
</code>```

Is There any solution to this?
Please Help Me!

答:
You declare t as an integer.
You give "2+2" in input. That is no int, that's a string and cin reads the first integer from the input.

```<code>cin>>t;
cout<<t+t;
</code>```

This would print 4. But the point here is that you can't assign arithmetic operations to cin. You need to create them in the code.

Body:
I am a beginner to C++. I am having some trouble or doubt;
The thing is, I am giving an arithmetic operation such as 2+2 in user input cin>>. But in return it gives output of 2!

Code:

#include "iostream"
using namespace std;
int main(){
    int t;
    cin>>t;      // Here I Have Given 2+2
    cout<<t;     // Instead of giving 4; It is giving me 2
    return 0;
}

Is There any solution to this?
Please Help Me!

Body:
You declare t as an integer.
You give "2+2" in input. That is no int, that's a string and cin reads the first integer from the input.

cin>>t;
cout<<t+t;

This would print 4. But the point here is that you can't assign arithmetic operations to cin. You need to create them in the code.


问:
How do I 'git diff' on a certain directory?
git diff actually runs a diff on all source code. How do I do this on a certain directory, so that I can view modifications on files underneath it?

答:
If you want to exclude the sub-directories, you can use</p>

```<code>git diff <ref1>..<ref2> -- $(git diff <ref1>..<ref2> --name-only | grep -v /)
</code>```

Body:
If you want to exclude the sub-directories, you can use

git diff <ref1>..<ref2> -- $(git diff <ref1>..<ref2> --name-only | grep -v /)


问:
elasticsearch on docker - snapshot and restore - access_denied_exception
I created elasticsearch cluster flowing by the article: Running the Elastic Stack on Docker

After the elasticsearch runs, I need to create snapshot and restore to backup my data.
I modified my elastic-docker-tls.yml file:

```<code>version: '2.2'

services:
  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:${VERSION}
    container_name: es01
    environment:
      - node.name=es01
      - cluster.name=es-docker-cluster
      - discovery.seed_hosts=es02,es03
      - cluster.initial_master_nodes=es01,es02,es03
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - xpack.license.self_generated.type=basic
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=true
      - xpack.security.http.ssl.key=$CERTS_DIR/es01/es01.key
      - xpack.security.http.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.http.ssl.certificate=$CERTS_DIR/es01/es01.crt
      - xpack.security.transport.ssl.enabled=true
      - xpack.security.transport.ssl.verification_mode=certificate
      - xpack.security.transport.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.transport.ssl.certificate=$CERTS_DIR/es01/es01.crt
      - xpack.security.transport.ssl.key=$CERTS_DIR/es01/es01.key
      - ELASTIC_PASSWORD=$ELASTIC_PASSWORD
      - path.repo=/usr/share/elasticsearch/backup
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data01:/usr/share/elasticsearch/data
      - databak:/usr/share/elasticsearch/backup
      - certs:$CERTS_DIR
    ports:
      - 9200:9200
    networks:
      - elastic

    healthcheck:
      test: curl --cacert $CERTS_DIR/ca/ca.crt -s https://localhost:9200 >/dev/null; if [[ $$? == 52 ]]; then echo 0; else echo 1; fi
      interval: 30s
      timeout: 10s
      retries: 5

  es02:
    image: docker.elastic.co/elasticsearch/elasticsearch:${VERSION}
    container_name: es02
    environment:
      - node.name=es02
      - cluster.name=es-docker-cluster
      - discovery.seed_hosts=es01,es03
      - cluster.initial_master_nodes=es01,es02,es03
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - xpack.license.self_generated.type=basic
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=true
      - xpack.security.http.ssl.key=$CERTS_DIR/es02/es02.key
      - xpack.security.http.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.http.ssl.certificate=$CERTS_DIR/es02/es02.crt
      - xpack.security.transport.ssl.enabled=true
      - xpack.security.transport.ssl.verification_mode=certificate
      - xpack.security.transport.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.transport.ssl.certificate=$CERTS_DIR/es02/es02.crt
      - xpack.security.transport.ssl.key=$CERTS_DIR/es02/es02.key
      - path.repo=/usr/share/elasticsearch/backup
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data02:/usr/share/elasticsearch/data
      - databak:/usr/share/elasticsearch/backup
      - certs:$CERTS_DIR
    networks:
      - elastic

  es03:
    image: docker.elastic.co/elasticsearch/elasticsearch:${VERSION}
    container_name: es03
    environment:
      - node.name=es03
      - cluster.name=es-docker-cluster
      - discovery.seed_hosts=es01,es02
      - cluster.initial_master_nodes=es01,es02,es03
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - xpack.license.self_generated.type=basic
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=true
      - xpack.security.http.ssl.key=$CERTS_DIR/es03/es03.key
      - xpack.security.http.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.http.ssl.certificate=$CERTS_DIR/es02/es02.crt
      - xpack.security.transport.ssl.enabled=true
      - xpack.security.transport.ssl.verification_mode=certificate
      - xpack.security.transport.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.transport.ssl.certificate=$CERTS_DIR/es03/es03.crt
      - xpack.security.transport.ssl.key=$CERTS_DIR/es03/es03.key
      - path.repo=/usr/share/elasticsearch/backup
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data03:/usr/share/elasticsearch/data
      - databak:/usr/share/elasticsearch/backup
      - certs:$CERTS_DIR
    networks:
      - elastic

  kib01:
    image: docker.elastic.co/kibana/kibana:${VERSION}
    container_name: kib01
    depends_on: {"es01": {"condition": "service_healthy"}}
    ports:
      - 5601:5601
    environment:
      SERVERNAME: localhost
      ELASTICSEARCH_URL: https://es01:9200
      ELASTICSEARCH_HOSTS: https://es01:9200
      ELASTICSEARCH_USERNAME: elastic
      ELASTICSEARCH_PASSWORD: $ELASTIC_PASSWORD
      ELASTICSEARCH_SSL_CERTIFICATEAUTHORITIES: $CERTS_DIR/ca/ca.crt
      SERVER_SSL_ENABLED: "true"
      SERVER_SSL_KEY: $CERTS_DIR/kib01/kib01.key
      SERVER_SSL_CERTIFICATE: $CERTS_DIR/kib01/kib01.crt
    volumes:
      - certs:$CERTS_DIR
    networks:
      - elastic
volumes:
  data01:
    driver: local
  data02:
    driver: local
  data03:
    driver: local
  databak:
    driver: local
  certs:
    driver: local

networks:
  elastic:
    driver: bridge
</code>```

After that, I registered a snapshot repository:

```<code>PUT /_snapshot/my_backup
{
  "type": "fs",
  "settings": {
    "location": "/usr/share/elasticsearch/backup/my_backup"
  }
}
</code>```

But, I get the following error message:

```<code>{
  "error" : {
    "root_cause" : [
      {
        "type" : "repository_exception",
        "reason" : "[my_backup] cannot create blob store"
      }
    ],
    "type" : "repository_exception",
    "reason" : "[my_backup] cannot create blob store",
    "caused_by" : {
      "type" : "access_denied_exception",
      "reason" : "/usr/share/elasticsearch/backup/my_backup"
    }
  },
  "status" : 500
}
</code>```

I have searched for solutions on google for 2 days but no solution. Can someone help me? Thank you very much!!!

答:
You can set chown for elasticsearch user in docker volume.

Run
ls -l show all mod of directory in elasticsearch

Run
chown elasticsearch /backup

Body:
I created elasticsearch cluster flowing by the article: Running the Elastic Stack on Docker

After the elasticsearch runs, I need to create snapshot and restore to backup my data.
I modified my elastic-docker-tls.yml file:

version: '2.2'

services:
  es01:
    image: docker.elastic.co/elasticsearch/elasticsearch:${VERSION}
    container_name: es01
    environment:
      - node.name=es01
      - cluster.name=es-docker-cluster
      - discovery.seed_hosts=es02,es03
      - cluster.initial_master_nodes=es01,es02,es03
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - xpack.license.self_generated.type=basic
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=true
      - xpack.security.http.ssl.key=$CERTS_DIR/es01/es01.key
      - xpack.security.http.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.http.ssl.certificate=$CERTS_DIR/es01/es01.crt
      - xpack.security.transport.ssl.enabled=true
      - xpack.security.transport.ssl.verification_mode=certificate
      - xpack.security.transport.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.transport.ssl.certificate=$CERTS_DIR/es01/es01.crt
      - xpack.security.transport.ssl.key=$CERTS_DIR/es01/es01.key
      - ELASTIC_PASSWORD=$ELASTIC_PASSWORD
      - path.repo=/usr/share/elasticsearch/backup
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data01:/usr/share/elasticsearch/data
      - databak:/usr/share/elasticsearch/backup
      - certs:$CERTS_DIR
    ports:
      - 9200:9200
    networks:
      - elastic

    healthcheck:
      test: curl --cacert $CERTS_DIR/ca/ca.crt -s https://localhost:9200 >/dev/null; if [[ $$? == 52 ]]; then echo 0; else echo 1; fi
      interval: 30s
      timeout: 10s
      retries: 5

  es02:
    image: docker.elastic.co/elasticsearch/elasticsearch:${VERSION}
    container_name: es02
    environment:
      - node.name=es02
      - cluster.name=es-docker-cluster
      - discovery.seed_hosts=es01,es03
      - cluster.initial_master_nodes=es01,es02,es03
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - xpack.license.self_generated.type=basic
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=true
      - xpack.security.http.ssl.key=$CERTS_DIR/es02/es02.key
      - xpack.security.http.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.http.ssl.certificate=$CERTS_DIR/es02/es02.crt
      - xpack.security.transport.ssl.enabled=true
      - xpack.security.transport.ssl.verification_mode=certificate
      - xpack.security.transport.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.transport.ssl.certificate=$CERTS_DIR/es02/es02.crt
      - xpack.security.transport.ssl.key=$CERTS_DIR/es02/es02.key
      - path.repo=/usr/share/elasticsearch/backup
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data02:/usr/share/elasticsearch/data
      - databak:/usr/share/elasticsearch/backup
      - certs:$CERTS_DIR
    networks:
      - elastic

  es03:
    image: docker.elastic.co/elasticsearch/elasticsearch:${VERSION}
    container_name: es03
    environment:
      - node.name=es03
      - cluster.name=es-docker-cluster
      - discovery.seed_hosts=es01,es02
      - cluster.initial_master_nodes=es01,es02,es03
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - xpack.license.self_generated.type=basic
      - xpack.security.enabled=true
      - xpack.security.http.ssl.enabled=true
      - xpack.security.http.ssl.key=$CERTS_DIR/es03/es03.key
      - xpack.security.http.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.http.ssl.certificate=$CERTS_DIR/es02/es02.crt
      - xpack.security.transport.ssl.enabled=true
      - xpack.security.transport.ssl.verification_mode=certificate
      - xpack.security.transport.ssl.certificate_authorities=$CERTS_DIR/ca/ca.crt
      - xpack.security.transport.ssl.certificate=$CERTS_DIR/es03/es03.crt
      - xpack.security.transport.ssl.key=$CERTS_DIR/es03/es03.key
      - path.repo=/usr/share/elasticsearch/backup
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - data03:/usr/share/elasticsearch/data
      - databak:/usr/share/elasticsearch/backup
      - certs:$CERTS_DIR
    networks:
      - elastic

  kib01:
    image: docker.elastic.co/kibana/kibana:${VERSION}
    container_name: kib01
    depends_on: {"es01": {"condition": "service_healthy"}}
    ports:
      - 5601:5601
    environment:
      SERVERNAME: localhost
      ELASTICSEARCH_URL: https://es01:9200
      ELASTICSEARCH_HOSTS: https://es01:9200
      ELASTICSEARCH_USERNAME: elastic
      ELASTICSEARCH_PASSWORD: $ELASTIC_PASSWORD
      ELASTICSEARCH_SSL_CERTIFICATEAUTHORITIES: $CERTS_DIR/ca/ca.crt
      SERVER_SSL_ENABLED: "true"
      SERVER_SSL_KEY: $CERTS_DIR/kib01/kib01.key
      SERVER_SSL_CERTIFICATE: $CERTS_DIR/kib01/kib01.crt
    volumes:
      - certs:$CERTS_DIR
    networks:
      - elastic
volumes:
  data01:
    driver: local
  data02:
    driver: local
  data03:
    driver: local
  databak:
    driver: local
  certs:
    driver: local

networks:
  elastic:
    driver: bridge

After that, I registered a snapshot repository:

PUT /_snapshot/my_backup
{
  "type": "fs",
  "settings": {
    "location": "/usr/share/elasticsearch/backup/my_backup"
  }
}

But, I get the following error message:

{
  "error" : {
    "root_cause" : [
      {
        "type" : "repository_exception",
        "reason" : "[my_backup] cannot create blob store"
      }
    ],
    "type" : "repository_exception",
    "reason" : "[my_backup] cannot create blob store",
    "caused_by" : {
      "type" : "access_denied_exception",
      "reason" : "/usr/share/elasticsearch/backup/my_backup"
    }
  },
  "status" : 500
}

I have searched for solutions on google for 2 days but no solution. Can someone help me? Thank you very much!!!


问:
React hook how to avoid infinite update
I need to update a property passed down from parent, it's causing infinite loop because I have to include it in the dependency list of useEffect hook.

Example

```<code>function componentFoo({bar, setBar}) {
    const [baz, setBaz] = useState()
    useEffect(()=>{

        setBar({...bar,baz:baz})
    }, [bar, baz])

    useEffect(()=>{
        setBaz(123)
    }, [])

    return <>{bar}</>
}

</code>```

How to avoid this?

答:
You must not add bar as a dependnecy to useEffect since you are updating it within useEffect itself and it will cause an infinite loop.

Instead use a functional approach to setBar like below

```<code>function componentFoo({bar, setBar}) {
    const [baz, setBaz] = useState()
    useEffect(()=>{

        setBar(prevBar => ({...prevBar,baz:baz}))
    }, [baz])

    useEffect(()=>{
        setBaz(123)
    }, [])

    return <>{bar}</>
}
</code>```

Title: React hook how to avoid infinite update

Body:
I need to update a property passed down from parent, it's causing infinite loop because I have to include it in the dependency list of useEffect hook.

Example

function componentFoo({bar, setBar}) {
    const [baz, setBaz] = useState()
    useEffect(()=>{

        setBar({...bar,baz:baz})
    }, [bar, baz])

    useEffect(()=>{
        setBaz(123)
    }, [])

    return <>{bar}</>
}

How to avoid this?

Body:
You must not add bar as a dependnecy to useEffect since you are updating it within useEffect itself and it will cause an infinite loop.

Instead use a functional approach to setBar like below

function componentFoo({bar, setBar}) {
    const [baz, setBaz] = useState()
    useEffect(()=>{

        setBar(prevBar => ({...prevBar,baz:baz}))
    }, [baz])

    useEffect(()=>{
        setBaz(123)
    }, [])

    return <>{bar}</>
}


问:
How do I setup Swashbuckle v5 with swagger when I have a custom base url?
I am upgrading a .net API to .net Core 3.1 and using Swashbuckle.AspNetcore 5.4.1. The API is running inside a ServiceFabric app. I found this https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1173 and tried to follow that and swagger gets generated but if I try to use the Swagger UI to send requests the request URL is with the wrong IP so the request fail.
In the old Swashbuckle 4.0.1 setup we did not specify host, only the relative basePath. How can I achieve the same?

Startup.cs

```<code>var swaggerBasePath = "/MySfApp/SfApp.ClientApi/";

app.UseSwagger(c =>
{
    c.SerializeAsV2 = serializeAsSwaggerV2;

    c.RouteTemplate = "swagger/{documentName}/swagger.json";
    c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
    {
        swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{swaggerBasePath}" } };
    });
});

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("api/swagger.json", "My API V1");
});
</code>```

The result is that the Swagger UI loads correctly on URL:

```<code>http://145.12.23.1:54000/MySfApp/SfApp.ClientApi/swagger/index.html
</code>```

and it says under name that BaseUrl is:

```<code>[ Base URL: 10.0.0.4:10680/MySfApp/SfApp.ClientApi/ ]
</code>```

The 10.0.0.4:10680 is the node inside the ServiceFabric cluster. Correct IP to reach from outside is 145.12.23.1:54000. In the older version (4.0.1) of Swashbuckle it says baseUrl without IP first: "/MySfApp/SfApp.ClientApi"

Swagger.json is located at:

```<code>http://40.68.213.118:19081/MySfApp/SfApp.ClientApi/swagger/api/swagger.json
</code>```

and it says:

```<code>"swagger": "2.0",
...
"host": "10.0.0.4:10680",
"basePath": "/MySfApp/SfApp.ClientApi/",
"schemes": [
"http"
],
"paths": {
"/activity/{activityId}": {
"get"
...etc
</code>```

If i try to send a GET request from the Swagger UI the request is sent to wrong IP:

```<code>curl -X GET "http://10.0.0.4:10680/MySfApp/MySfApp/activity/3443"
</code>```

EDIT 1:
After some digging I have now changed the setup to this in
startup.cs

```<code>var swaggerBasePath = "/MySfApp/SfApp.ClientApi/";
app.UsePathBase($"/{swaggerBasePath}");
app.UseMvc();
app.UseSwagger(c =>
{
    c.SerializeAsV2 = serializeAsSwaggerV2;

    c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
    {
        if (!httpReq.Headers.ContainsKey("X-Original-Host"))
            return;

        var serverUrl = $"{httpReq.Headers["X-Original-Proto"]}://" +
                        $"{httpReq.Headers["X-Original-Host"]}/" +
                        $"{httpReq.Headers["X-Original-Prefix"]}";

        swaggerDoc.Servers = new List<OpenApiServer>()
        {
            new OpenApiServer { Url = serverUrl }
        };
    });
});
app.UseSwaggerUI(options => {
    options.SwaggerEndpoint("api/swagger.json", "My API V1");
});
</code>```

This now leads to the Swagger UI loading properly with the baseUrl

```<code>http://145.12.23.1:54000/MySfApp/SfApp.ClientApi/swagger/index.html
</code>```

and also swagger.json is served correctly with the correct baseUrl.

```<code>http://145.12.23.1:54000/MySfApp/SfApp.ClientApi/swagger/api/swagger.json
</code>```

So the wrong hostname is resolved. Thanks to idea from this thread.

However when I try to call an endpoint from the Swagger UI page, the curl URL does not include the baseUrl. So closer... but currently not possible to use Swagger UI.

```<code>curl -X GET "http://10.0.0.4:10680/activity/3443"
</code>```

The swagger.json does not have 'host' nor 'basePath' defined.

答:
Try this:
    serverUrl = $"{httpReq.Headers["X-Forwarded-Proto"]}://" +
                $"{httpReq.Headers["X-Forwarded-Host"]}" + _basePath;
where _basePath can be set using the ServiceName property of StatelessServiceContext.
Please be noted that the original value of X-Forwarded-Proto may be overridden by SF.

Body:
I am upgrading a .net API to .net Core 3.1 and using Swashbuckle.AspNetcore 5.4.1. The API is running inside a ServiceFabric app. I found this https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1173 and tried to follow that and swagger gets generated but if I try to use the Swagger UI to send requests the request URL is with the wrong IP so the request fail.
In the old Swashbuckle 4.0.1 setup we did not specify host, only the relative basePath. How can I achieve the same?

Startup.cs

var swaggerBasePath = "/MySfApp/SfApp.ClientApi/";

app.UseSwagger(c =>
{
    c.SerializeAsV2 = serializeAsSwaggerV2;

    c.RouteTemplate = "swagger/{documentName}/swagger.json";
    c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
    {
        swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}{swaggerBasePath}" } };
    });
});

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("api/swagger.json", "My API V1");
});

The result is that the Swagger UI loads correctly on URL:

http://145.12.23.1:54000/MySfApp/SfApp.ClientApi/swagger/index.html

and it says under name that BaseUrl is:

[ Base URL: 10.0.0.4:10680/MySfApp/SfApp.ClientApi/ ]

The 10.0.0.4:10680 is the node inside the ServiceFabric cluster. Correct IP to reach from outside is 145.12.23.1:54000. In the older version (4.0.1) of Swashbuckle it says baseUrl without IP first: "/MySfApp/SfApp.ClientApi"

Swagger.json is located at:

http://40.68.213.118:19081/MySfApp/SfApp.ClientApi/swagger/api/swagger.json

and it says:

"swagger": "2.0",
...
"host": "10.0.0.4:10680",
"basePath": "/MySfApp/SfApp.ClientApi/",
"schemes": [
"http"
],
"paths": {
"/activity/{activityId}": {
"get"
...etc

If i try to send a GET request from the Swagger UI the request is sent to wrong IP:

curl -X GET "http://10.0.0.4:10680/MySfApp/MySfApp/activity/3443"

EDIT 1:
After some digging I have now changed the setup to this in
startup.cs

var swaggerBasePath = "/MySfApp/SfApp.ClientApi/";
app.UsePathBase($"/{swaggerBasePath}");
app.UseMvc();
app.UseSwagger(c =>
{
    c.SerializeAsV2 = serializeAsSwaggerV2;

    c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
    {
        if (!httpReq.Headers.ContainsKey("X-Original-Host"))
            return;

        var serverUrl = $"{httpReq.Headers["X-Original-Proto"]}://" +
                        $"{httpReq.Headers["X-Original-Host"]}/" +
                        $"{httpReq.Headers["X-Original-Prefix"]}";

        swaggerDoc.Servers = new List<OpenApiServer>()
        {
            new OpenApiServer { Url = serverUrl }
        };
    });
});
app.UseSwaggerUI(options => {
    options.SwaggerEndpoint("api/swagger.json", "My API V1");
});

This now leads to the Swagger UI loading properly with the baseUrl

http://145.12.23.1:54000/MySfApp/SfApp.ClientApi/swagger/index.html

and also swagger.json is served correctly with the correct baseUrl.

http://145.12.23.1:54000/MySfApp/SfApp.ClientApi/swagger/api/swagger.json

So the wrong hostname is resolved. Thanks to idea from this thread.

However when I try to call an endpoint from the Swagger UI page, the curl URL does not include the baseUrl. So closer... but currently not possible to use Swagger UI.

curl -X GET "http://10.0.0.4:10680/activity/3443"

The swagger.json does not have 'host' nor 'basePath' defined.


问:
Is an array from resource xml file ordered?
I have two arrays of the same length and I want to get a value from one based on the index of a value from the other. I'm storing the arrays as xml resources in Android. </p>

```<code>val arrayFromRes1 = resources.getStringArray(R.array.my_first_array)
val arrayFromRes2 = resources.getStringArray(R.array.my_second_array)
</code>```

<p>Will the two arrays always be loaded in the order they appear in the string resources? </p>

答:
Yes. Arrays are ordered.

If they weren't, chaos would ensue.

Body:
I have two arrays of the same length and I want to get a value from one based on the index of a value from the other. I'm storing the arrays as xml resources in Android.

val arrayFromRes1 = resources.getStringArray(R.array.my_first_array)
val arrayFromRes2 = resources.getStringArray(R.array.my_second_array)

Will the two arrays always be loaded in the order they appear in the string resources?


问:
Executing function for every key in array w/o loop
I'm looking for the best practice for executing encodeURIComponent (or some other function) for every key in array, before joining it to one string.

This could be done with a loop like this:

```<code>var dynamicArray = ['uri1', 'uri2', 'hax&%hax'];
var max = dynamicArray.length,
i,
url = '';

for (i=0;i<max;(i++))
{
   url += '/' + encodeURIComponent(dynamicArray[i]);
}

alert(url);

/* RESULT: /uri1/uri2/hax%26%25hax */
</code>```

But I'm looking for something like this (without a loop):

```<code>encodeURIComponent(dynamicArray).join('/'); /* This won't work */
encodeURIComponent(dynamicArray.join('/')); /* Can't do this, wrong result */
</code>```

答:
Well in some modern browsers there's a ".map()" method for arrays:

```<code>var encoded = dynamicArray.map(function(str) {
  return encodeURIComponent(str);
});
</code>```

or without your own function wrapper, which in this case isn't really necessary:

```<code>var encoded = dynamicArray.map(encodeURIComponent);
</code>```

The idea is that ".map()" is called for each element of the array.  The function it's passed should return some result, and those results are gathered up into a new array, which is ultimately the returned value.  You can then ".join()" that, or do whatever else you need.

The Mozilla documentation for ".map()" has a "polyfill" block of code you can use to provide ".map()" in browsers that don't natively support it.  Note also that many utility libraries have their own ".map()", and some of those have slightly different semantics. For example, the jQuery ".map()" has (to me, unpleasant) semantics for returned values from the callback function.

Body:
I'm looking for the best practice for executing encodeURIComponent (or some other function) for every key in array, before joining it to one string.

This could be done with a loop like this:

var dynamicArray = ['uri1', 'uri2', 'hax&%hax'];
var max = dynamicArray.length,
i,
url = '';

for (i=0;i<max;(i++))
{
   url += '/' + encodeURIComponent(dynamicArray[i]);
}

alert(url);

/* RESULT: /uri1/uri2/hax%26%25hax */

But I'm looking for something like this (without a loop):

encodeURIComponent(dynamicArray).join('/'); /* This won't work */
encodeURIComponent(dynamicArray.join('/')); /* Can't do this, wrong result */

Body:
Well in some modern browsers there's a ".map()" method for arrays:

var encoded = dynamicArray.map(function(str) {
  return encodeURIComponent(str);
});

or without your own function wrapper, which in this case isn't really necessary:

var encoded = dynamicArray.map(encodeURIComponent);

The idea is that ".map()" is called for each element of the array.  The function it's passed should return some result, and those results are gathered up into a new array, which is ultimately the returned value.  You can then ".join()" that, or do whatever else you need.

The Mozilla documentation for ".map()" has a "polyfill" block of code you can use to provide ".map()" in browsers that don't natively support it.  Note also that many utility libraries have their own ".map()", and some of those have slightly different semantics. For example, the jQuery ".map()" has (to me, unpleasant) semantics for returned values from the callback function.


问:
Strange sytax error with nested keyword parameters
I am currently trying to code some sort of QoS box by utilizing MITM via ARP poisioning.
Now I ran into a syntax error I can not seem to resolve:

```<code>File "/home/pi/qosmitm/networker.py", line 53
self.recv_threads.append(multiprocessing.Process(target=sniff, args=(iface=interface,
                                                                          ^ SyntaxError: invalid syntax
</code>```

The Code:

```<code>    for i in range(0, len(net_map[0])):
            ip = net_map[0][i]
            mac = net_map[1][i]
            self.packet_queues.append(multiprocessing.Queue())
            self.recv_threads.append(multiprocessing.Process(target=sniff, args=(iface=interface, filter='host ' + ip, prn=mitm.recv_packets(self.packet_queues[i]))))
</code>```

interface is a string.

And here is the recv_packets funktion:

```<code>def recv_packets(self, queue): # not too sure bout that
    def recv_packets(self, pkt):
        # flip macs & put into queue
        old_src = pkt[Ether].src
        print(pkt.summary())
        pkt[Ether].src = pkt[Ether].dst
        pkt[Ether].dst = old_src                                                                          queue.put(pkt)
</code>```

I checked the different docs but I could not find out what I am doing wrong. My guess is that it is somehow related to the nested function calls/callbacks(?).

Thanks in advance!

答:
Thanks @jasonharper for clearifying this. Read his comment below my question for an explanation to this corrected code snipped.

```<code>self.recv_threads.append(multiprocessing.Process(target=sniff, args={'iface':interface, filter':'host ' + ip, 'prn':mitm.recv_packets(self.packet_queues[i])})
</code>```

Go drop him an upvote for the quick answer. Much appreciated!

Body:
I am currently trying to code some sort of QoS box by utilizing MITM via ARP poisioning.
Now I ran into a syntax error I can not seem to resolve:

File "/home/pi/qosmitm/networker.py", line 53
self.recv_threads.append(multiprocessing.Process(target=sniff, args=(iface=interface,
                                                                          ^ SyntaxError: invalid syntax

The Code:

    for i in range(0, len(net_map[0])):
            ip = net_map[0][i]
            mac = net_map[1][i]
            self.packet_queues.append(multiprocessing.Queue())
            self.recv_threads.append(multiprocessing.Process(target=sniff, args=(iface=interface, filter='host ' + ip, prn=mitm.recv_packets(self.packet_queues[i]))))

interface is a string.

And here is the recv_packets funktion:

def recv_packets(self, queue): # not too sure bout that
    def recv_packets(self, pkt):
        # flip macs & put into queue
        old_src = pkt[Ether].src
        print(pkt.summary())
        pkt[Ether].src = pkt[Ether].dst
        pkt[Ether].dst = old_src                                                                          queue.put(pkt)

I checked the different docs but I could not find out what I am doing wrong. My guess is that it is somehow related to the nested function calls/callbacks(?).

Thanks in advance!

Body:
Thanks @jasonharper for clearifying this. Read his comment below my question for an explanation to this corrected code snipped.

self.recv_threads.append(multiprocessing.Process(target=sniff, args={'iface':interface, filter':'host ' + ip, 'prn':mitm.recv_packets(self.packet_queues[i])})

Go drop him an upvote for the quick answer. Much appreciated!


问:
List all indexes on ElasticSearch server?
I would like to list all indexes present on an ElasticSearch server. I tried this:

```<code>curl -XGET localhost:9200/
</code>```

but it just gives me this:

{
  "ok" : true,
  "status" : 200,
  "name" : "El Aguila",
  "version" : {
    "number" : "0.19.3",
    "snapshot_build" : false
  },
  "tagline" : "You Know, for Search"
}
```

I want a list of all indexes..

答:
If you have curl installed on your system, then try this simple command :
curl -XGET xx.xx.xx.xx:9200/_cat/indices?v

The above-mentioned command gives you result in this format :
result to fetch all indices

Body:
I would like to list all indexes present on an ElasticSearch server. I tried this:

curl -XGET localhost:9200/

but it just gives me this:

{
  "ok" : true,
  "status" : 200,
  "name" : "El Aguila",
  "version" : {
    "number" : "0.19.3",
    "snapshot_build" : false
  },
  "tagline" : "You Know, for Search"
}

I want a list of all indexes..


问:
How can I avoid overriding a window-wide style in WPF?
I'm using the MaterialDesign nuget package for my WPF application.
According to the tutorial, by applying window-wide properties, every element will inherit the MaterialDesign style.
However, if I apply a custom style to an element, that element loses its MaterialDesign style.
I can get around this by applying inline styles, but that is very repetitive and error prone.

I think the picture shows it better:

And here is my xaml:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestApp"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" x:Class="TestApp.MainWindow"
        mc:Ignorable="d"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        TextElement.FontWeight="Regular"
        TextElement.FontSize="13"
        TextOptions.TextFormattingMode="Ideal"
        TextOptions.TextRenderingMode="Auto"
        Background="{DynamicResource MaterialDesignPaper}"
        FontFamily="{DynamicResource MaterialDesignFont}"
        Title="MainWindow" Height="450" Width="600">

    <StackPanel>
        <StackPanel.Resources>

        </StackPanel.Resources>

        <Button Content="Button #1" HorizontalAlignment="Center" Margin="0 10"/>
        <Button Content="Button #2" Style="{DynamicResource SpacedButton}"/>
        <Button Content="Button #3" Style="{DynamicResource SpacedButton}"/>
        <Button Content="Button #4" HorizontalAlignment="Center" Margin="0 10"/>
    </StackPanel>
</Window>
```

As you can see, only elements with inline properties keep the MaterialDesign style, but by applying a custom style, the MaterialDesign style is lost.

How can I make sure that MaterialDesign is applied to every element, while still being able to override specific properties with custom styles?

Sorry if some of the terminology is wrong, I'm pretty new to WPF.

答:
Use Style.BasedOn to inherit properties from whichever other style is in scope:

```<code><Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
    ...etc....
</code>```

Or a specific one:

```<code><Style x:Key="ThisStyleKey" TargetType="{x:Type Button}" BasedOn="{StaticResource OtherStyleKey}">
    ...etc....
</code>```

Body:
I'm using the MaterialDesign nuget package for my WPF application.
According to the tutorial, by applying window-wide properties, every element will inherit the MaterialDesign style.
However, if I apply a custom style to an element, that element loses its MaterialDesign style.
I can get around this by applying inline styles, but that is very repetitive and error prone.

I think the picture shows it better:

And here is my xaml:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestApp"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" x:Class="TestApp.MainWindow"
        mc:Ignorable="d"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        TextElement.FontWeight="Regular"
        TextElement.FontSize="13"
        TextOptions.TextFormattingMode="Ideal"
        TextOptions.TextRenderingMode="Auto"
        Background="{DynamicResource MaterialDesignPaper}"
        FontFamily="{DynamicResource MaterialDesignFont}"
        Title="MainWindow" Height="450" Width="600">

    <StackPanel>
        <StackPanel.Resources>

        </StackPanel.Resources>

        <Button Content="Button #1" HorizontalAlignment="Center" Margin="0 10"/>
        <Button Content="Button #2" Style="{DynamicResource SpacedButton}"/>
        <Button Content="Button #3" Style="{DynamicResource SpacedButton}"/>
        <Button Content="Button #4" HorizontalAlignment="Center" Margin="0 10"/>
    </StackPanel>
</Window>

As you can see, only elements with inline properties keep the MaterialDesign style, but by applying a custom style, the MaterialDesign style is lost.

How can I make sure that MaterialDesign is applied to every element, while still being able to override specific properties with custom styles?

Sorry if some of the terminology is wrong, I'm pretty new to WPF.

Body:
Use Style.BasedOn to inherit properties from whichever other style is in scope:

<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
    ...etc....

Or a specific one:

<Style x:Key="ThisStyleKey" TargetType="{x:Type Button}" BasedOn="{StaticResource OtherStyleKey}">
    ...etc....


问:
How to detect SSL certificate information using Selenium?
I am using Selenium to collect some data, and one of the requirements is to get SSL Certificate information like the issuer, expiry date, mixed content, etc.

Is there a way in Selenium to get this information?

I am using Selenium with Ruby.

```<code>require 'selenium-webdriver'
options = Selenium::WebDriver::Chrome::Options.new(args: ['headless'])
driver = Selenium::WebDriver.for(:chrome, options: options)
driver.get 'https://stackoverflow.com/'
</code>```

After that, I am clueless as to how to get any information of the SSL certificates.

答:
Just have a look in this it might be helpful.

Adding to it Chrome Performance Logging records Network.responseReceived event from which we can get information about securitydetails in Network.Response.

Ref: https://chromedevtools.github.io/devtools-protocol/tot/Network/#type-Response

Body:
I am using Selenium to collect some data, and one of the requirements is to get SSL Certificate information like the issuer, expiry date, mixed content, etc.

Is there a way in Selenium to get this information?

I am using Selenium with Ruby.

require 'selenium-webdriver'
options = Selenium::WebDriver::Chrome::Options.new(args: ['headless'])
driver = Selenium::WebDriver.for(:chrome, options: options)
driver.get 'https://stackoverflow.com/'

After that, I am clueless as to how to get any information of the SSL certificates.


问:
can I show a specific part of a page using document.getElementById(href)?
if I have a page called "content page":

```<code><body >

<p id="part1">Tread ... inch. </p>

<p id="part2">Tread ... inch. </p>

<p id="part3">Tread ... inch.</p>

</body>
</code>```

and another page with this java script(code in close icon doesn't appear ).

```<code><head>
<script type="text/javascript" src="popupBox.js"></script>
</head>
<body>

show content of part one : <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.
show content of part two : <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.
show content of part three : <a href="TreadDepth.html" onClick="return show_hide_box(this,400,400,'2px solid')">Click Here</a>.

</body>
</code>```

if I want to retrive a specific part of a content page to be shown in the popup box, is that possible?

I mean in this part at popup.js:

```<code>var boxdiv = document.getElementById(href);
</code>```

can I specify an ID of a tag in the href of the page to retrive it? like :

```<code>var href = an.href;
var boxdiv = document.getElementById(href).getElementById("Show The content of this ID tag!");
</code>```

any idea?

答:
No man. Its not possible.

I have checked your code and found the original site where it was posted.

The URL: http://example.nemikor.com/creating-dialogs-on-demand/

If you check on the three links on that site, you can see that each three of those links reference three different uris.

Body:
if I have a page called "content page":

Tread ... inch.

Tread ... inch.

Tread ... inch.

and another page with this java script(code in close icon doesn't appear ).

show content of part one : Click Here.
show content of part two : Click Here.
show content of part three : Click Here.

if I want to retrive a specific part of a content page to be shown in the popup box, is that possible?

I mean in this part at popup.js:

var boxdiv = document.getElementById(href);

can I specify an ID of a tag in the href of the page to retrive it? like :

var href = an.href;
var boxdiv = document.getElementById(href).getElementById("Show The content of this ID tag!");

any idea?