问:
How to patch values in formik?
I'm using formik for form submission in React but, when i want to 'PATCH' something formik pushes entire object instead of the field that is modified
Here is my code:

editProfile.js

import React, { useEffect } from 'react';
import { makeStyles, Grid, Typography, TextField, Button } from '@material-ui/core';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';
import { useDispatch, useSelector } from 'react-redux';
import { updateUser } from '../actions';
import { useHistory } from 'react-router-dom';
import NavBar from './navBar';
const useStyles = makeStyles((theme) => ({

}));

const Validation = Yup.object().shape({
    firstName: Yup
        .string()
        .min(2, 'Name is too short!')
        .max(15, 'Name is too long!')
        .notRequired(),

    secondName: Yup
        .string()
        .min(2, 'Name is too short!')
        .max(15, 'Name is too long!')
        .notRequired(),

    lastName: Yup
        .string()
        .min(2, 'Name is too short!')
        .max(15, 'Name is too long!')
        .notRequired(),

    password: Yup
        .string()
        .min(6, 'Password too short')
        .max(20, 'Password too long')
        .notRequired(),
    age: Yup
        .number()
        .positive('Age must not be negative')
        .notRequired(),
    bloodGroup: Yup
        .string()
        .max(3, 'Blood group can\'t greater than 3')
        .notRequired(),
    weight: Yup
        .number()
        .positive('Weight must be a positive number')
        .notRequired(),
    bmi: Yup
        .number()
        .positive()
        .notRequired(),
    leftEye: Yup
        .number()
        .max(6)
        .positive()
        .notRequired(),
    rightEye: Yup
        .number()
        .max(6)
        .positive()
        .notRequired(),
    doctorName: Yup
        .string()
        .max(15, 'Name is too long!')
        .notRequired(),
    doctorEmail: Yup
        .string()
        .email()
        .notRequired(),
    doctorPhone: Yup
        .number()
        .notRequired(),
    specialist: Yup
        .string()
        .notRequired(),
    address: Yup
        .string()
        .max(100, 'Too long address')
        .notRequired(),
    lastVisit: Yup
        .date()
        .notRequired(),
    nextVisit: Yup
        .date()
        .notRequired(),

})

const EditProfile = () => {
    const classes = useStyles();
    const dispatch = useDispatch();
    const user = useSelector(state => state.auth.user);
    const isSignedIn = useSelector(state => state.auth.isSignedIn);
    const history = useHistory();
    useEffect(() => {
        if (!isSignedIn) {
            history.push('/')
        }
    }, [isSignedIn, history])
    if (!user) {
        return null;
    } else {
        return (
            <React.Fragment>
                <NavBar />
                <Grid
                    container
                    direction='column'
                    justify='flex-start'
                    alignItems='flex-start'
                    className={classes.gridHome}
                >
                    <Grid item xs={12} className={classes.gridContent}>
                        <Typography className={classes.title}>Medico</Typography>
                    </Grid>
                    <Grid item xs={12} className={classes.gridContent}>
                        <Typography className={classes.signUp}>Welcome {user.user.firstName ? user.user.firstName : null}!</Typography>
                    </Grid>

                    <Formik

                        initialValues={{
                            firstName: '',
                            secondName: '',
                            lastName: '',
                            password: '',
                            age: '',
                            bloodGroup: '',
                            weight: '',
                            leftEye: 1,
                            rightEye: 1,
                            bmi: 1,
                            doctorName: '',
                            doctorPhone: 0,
                            doctorEmail: '',
                            address: '',
                            specialist: '',
                            lastVisit: new Date(),
                            nextVisit: new Date(),
                        }}
                        validationSchema={Validation}
                        onSubmit={(values) => {
                            dispatch(updateUser(values))
                        }}
                    >
                        {({ errors, handleChange, touched }) =>
                            <Form style={{ width: '100%' }}>
                                <Grid container direction='row'>
                                    <Grid item xs={12} className={classes.name}>
                                        <Typography className={classes.signUp}>Name</Typography>
                                    </Grid>
                                    <Grid item md={4} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.firstName && touched.firstName}
                                            name='firstName'
                                            autoComplete='on'
                                            shrink='true'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='firstName'
                                            label='First Name'
                                            helperText={
                                                errors.firstName && touched.firstName
                                                    ? errors.firstName : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={4} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.secondName && touched.secondName}
                                            name='secondName'
                                            autoComplete='on'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='secondName'
                                            label='Middle Name'
                                            helperText={
                                                errors.secondName && touched.secondName
                                                    ? errors.secondName : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={4} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.lastName && touched.lastName}
                                            name='lastName'
                                            autoComplete='on'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='lastName'
                                            label='Last Name'
                                            helperText={
                                                errors.lastName && touched.lastName
                                                    ? errors.lastName : null
                                            }
                                        />
                                    </Grid>

                                    <Grid item xs={12} className={classes.name}>
                                        <Typography className={classes.signUp}>Password</Typography>
                                    </Grid>
                                    <Grid item md={6} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.password && touched.password}
                                            name='password'
                                            type='password'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='password'
                                            label='Password'
                                            helperText={
                                                errors.password && touched.password
                                                    ? errors.password : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item xs={12} className={classes.name}>
                                        <Typography className={classes.signUp}>Personal Information</Typography>
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.age && touched.age}
                                            name='age'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='age'
                                            label='Age'
                                            helperText={
                                                errors.age && touched.age
                                                    ? errors.age : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.bloodGroup && touched.bloodGroup}
                                            name='bloodGroup'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='bloodGroup'
                                            label='Blood Group'
                                            helperText={
                                                errors.bloodGroup && touched.bloodGroup
                                                    ? errors.bloodGroup : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.weight && touched.weight}
                                            name='weight'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='weight'
                                            label='Weight(in Kg)'
                                            helperText={
                                                errors.weight && touched.weight
                                                    ? errors.weight : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.bmi && touched.bmi}
                                            name='bmi'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='bmi'
                                            label='BMI'
                                            helperText={
                                                errors.bmi && touched.bmi
                                                    ? errors.bmi : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.leftEye && touched.leftEye}
                                            name='leftEye'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='leftEye'
                                            label='Left Eye'
                                            helperText={
                                                errors.leftEye && touched.leftEye
                                                    ? errors.leftEye : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.rightEye && touched.rightEye}
                                            name='rightEye'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='rightEye'
                                            label='Right Eye'
                                            helperText={
                                                errors.rightEye && touched.rightEye
                                                    ? errors.rightEye : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item xs={6} container justify='center' alignItems='center' className={classes.loginGrid}>
                                        <Button
                                            className={classes.button}
                                            type='submit'
                                            variant='contained'
                                        >Submit</Button>
                                    </Grid>
                                </Grid>
                            </Form>
                        }
                    </Formik>
                </Grid>
            </React.Fragment >
        );
    }

}

export default EditProfile;```

Suppose I just want to push 'secondName' for 'PATCH' instead formik submits all fields that are mentioned in 'initialValues'.How to control that formik submit only that field that was changed.
PS: I've removed some fields to shorten the snippet.

答:
I think its pretty simple...you just need to compare initialValues with values in onSubmit handler. I hope this snippet is enough to understand

```<code>
const getModifiedValues = (values, initialValues) => {
  let modifiedValues = {};

  if (values) {
    Object.entries(values).forEach((entry) => {
      let key = entry[0];
      let value = entry[1];

      if (value !== initialValues[key]) {
        modifiedValues[key] = value;
      }
    });
  }

  return modifiedValues;
};

const initialValues = {
    firstName: '',
    secondName: '',
    lastName: '',
    password: '',
    age: '',
    bloodGroup: '',
    weight: '',
    leftEye: 1,
    rightEye: 1,
    bmi: 1,
    doctorName: '',
    doctorPhone: 0,
    doctorEmail: '',
    address: '',
    specialist: '',
    lastVisit: new Date(),
    nextVisit: new Date(),
};

<Formik
    initialValues={initialValues}
    validationSchema={Validation}
    onSubmit={(values) => {
        // this function should return the only modified values.
        const modifiedValues = getModifiedValues(values, initialValues);
        dispatch(updateUser(modifiedValues))
    }}
>
...
</Formik>
</code>```

I found a link, where it has already been answered.

Only send values that have changed in formik onSubmit

Title: How to patch values in formik?

Body:
I'm using formik for form submission in React but, when i want to 'PATCH' something formik pushes entire object instead of the field that is modified
Here is my code:

editProfile.js

import React, { useEffect } from 'react';
import { makeStyles, Grid, Typography, TextField, Button } from '@material-ui/core';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';
import { useDispatch, useSelector } from 'react-redux';
import { updateUser } from '../actions';
import { useHistory } from 'react-router-dom';
import NavBar from './navBar';
const useStyles = makeStyles((theme) => ({

}));

const Validation = Yup.object().shape({
    firstName: Yup
        .string()
        .min(2, 'Name is too short!')
        .max(15, 'Name is too long!')
        .notRequired(),

    secondName: Yup
        .string()
        .min(2, 'Name is too short!')
        .max(15, 'Name is too long!')
        .notRequired(),

    lastName: Yup
        .string()
        .min(2, 'Name is too short!')
        .max(15, 'Name is too long!')
        .notRequired(),

    password: Yup
        .string()
        .min(6, 'Password too short')
        .max(20, 'Password too long')
        .notRequired(),
    age: Yup
        .number()
        .positive('Age must not be negative')
        .notRequired(),
    bloodGroup: Yup
        .string()
        .max(3, 'Blood group can\'t greater than 3')
        .notRequired(),
    weight: Yup
        .number()
        .positive('Weight must be a positive number')
        .notRequired(),
    bmi: Yup
        .number()
        .positive()
        .notRequired(),
    leftEye: Yup
        .number()
        .max(6)
        .positive()
        .notRequired(),
    rightEye: Yup
        .number()
        .max(6)
        .positive()
        .notRequired(),
    doctorName: Yup
        .string()
        .max(15, 'Name is too long!')
        .notRequired(),
    doctorEmail: Yup
        .string()
        .email()
        .notRequired(),
    doctorPhone: Yup
        .number()
        .notRequired(),
    specialist: Yup
        .string()
        .notRequired(),
    address: Yup
        .string()
        .max(100, 'Too long address')
        .notRequired(),
    lastVisit: Yup
        .date()
        .notRequired(),
    nextVisit: Yup
        .date()
        .notRequired(),

})

const EditProfile = () => {
    const classes = useStyles();
    const dispatch = useDispatch();
    const user = useSelector(state => state.auth.user);
    const isSignedIn = useSelector(state => state.auth.isSignedIn);
    const history = useHistory();
    useEffect(() => {
        if (!isSignedIn) {
            history.push('/')
        }
    }, [isSignedIn, history])
    if (!user) {
        return null;
    } else {
        return (
            <React.Fragment>
                <NavBar />
                <Grid
                    container
                    direction='column'
                    justify='flex-start'
                    alignItems='flex-start'
                    className={classes.gridHome}
                >
                    <Grid item xs={12} className={classes.gridContent}>
                        <Typography className={classes.title}>Medico</Typography>
                    </Grid>
                    <Grid item xs={12} className={classes.gridContent}>
                        <Typography className={classes.signUp}>Welcome {user.user.firstName ? user.user.firstName : null}!</Typography>
                    </Grid>

                    <Formik

                        initialValues={{
                            firstName: '',
                            secondName: '',
                            lastName: '',
                            password: '',
                            age: '',
                            bloodGroup: '',
                            weight: '',
                            leftEye: 1,
                            rightEye: 1,
                            bmi: 1,
                            doctorName: '',
                            doctorPhone: 0,
                            doctorEmail: '',
                            address: '',
                            specialist: '',
                            lastVisit: new Date(),
                            nextVisit: new Date(),
                        }}
                        validationSchema={Validation}
                        onSubmit={(values) => {
                            dispatch(updateUser(values))
                        }}
                    >
                        {({ errors, handleChange, touched }) =>
                            <Form style={{ width: '100%' }}>
                                <Grid container direction='row'>
                                    <Grid item xs={12} className={classes.name}>
                                        <Typography className={classes.signUp}>Name</Typography>
                                    </Grid>
                                    <Grid item md={4} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.firstName && touched.firstName}
                                            name='firstName'
                                            autoComplete='on'
                                            shrink='true'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='firstName'
                                            label='First Name'
                                            helperText={
                                                errors.firstName && touched.firstName
                                                    ? errors.firstName : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={4} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.secondName && touched.secondName}
                                            name='secondName'
                                            autoComplete='on'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='secondName'
                                            label='Middle Name'
                                            helperText={
                                                errors.secondName && touched.secondName
                                                    ? errors.secondName : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={4} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.lastName && touched.lastName}
                                            name='lastName'
                                            autoComplete='on'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='lastName'
                                            label='Last Name'
                                            helperText={
                                                errors.lastName && touched.lastName
                                                    ? errors.lastName : null
                                            }
                                        />
                                    </Grid>

                                    <Grid item xs={12} className={classes.name}>
                                        <Typography className={classes.signUp}>Password</Typography>
                                    </Grid>
                                    <Grid item md={6} xs={12} className={classes.inputGrid}>
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.password && touched.password}
                                            name='password'
                                            type='password'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='password'
                                            label='Password'
                                            helperText={
                                                errors.password && touched.password
                                                    ? errors.password : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item xs={12} className={classes.name}>
                                        <Typography className={classes.signUp}>Personal Information</Typography>
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.age && touched.age}
                                            name='age'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='age'
                                            label='Age'
                                            helperText={
                                                errors.age && touched.age
                                                    ? errors.age : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.bloodGroup && touched.bloodGroup}
                                            name='bloodGroup'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='bloodGroup'
                                            label='Blood Group'
                                            helperText={
                                                errors.bloodGroup && touched.bloodGroup
                                                    ? errors.bloodGroup : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.weight && touched.weight}
                                            name='weight'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='weight'
                                            label='Weight(in Kg)'
                                            helperText={
                                                errors.weight && touched.weight
                                                    ? errors.weight : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.bmi && touched.bmi}
                                            name='bmi'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='bmi'
                                            label='BMI'
                                            helperText={
                                                errors.bmi && touched.bmi
                                                    ? errors.bmi : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.leftEye && touched.leftEye}
                                            name='leftEye'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='leftEye'
                                            label='Left Eye'
                                            helperText={
                                                errors.leftEye && touched.leftEye
                                                    ? errors.leftEye : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item md={2} xs={6} className={classes.inputGrid} >
                                        <TextField
                                            className={classes.inputFields}
                                            error={errors.rightEye && touched.rightEye}
                                            name='rightEye'
                                            variant='standard'
                                            onChange={handleChange}
                                            id='rightEye'
                                            label='Right Eye'
                                            helperText={
                                                errors.rightEye && touched.rightEye
                                                    ? errors.rightEye : null
                                            }
                                        />
                                    </Grid>
                                    <Grid item xs={6} container justify='center' alignItems='center' className={classes.loginGrid}>
                                        <Button
                                            className={classes.button}
                                            type='submit'
                                            variant='contained'
                                        >Submit</Button>
                                    </Grid>
                                </Grid>
                            </Form>
                        }
                    </Formik>
                </Grid>
            </React.Fragment >
        );
    }

}

export default EditProfile;

Suppose I just want to push 'secondName' for 'PATCH' instead formik submits all fields that are mentioned in 'initialValues'.How to control that formik submit only that field that was changed.
PS: I've removed some fields to shorten the snippet.

Body:
I think its pretty simple...you just need to compare initialValues with values in onSubmit handler. I hope this snippet is enough to understand

const getModifiedValues = (values, initialValues) => {
  let modifiedValues = {};

  if (values) {
    Object.entries(values).forEach((entry) => {
      let key = entry[0];
      let value = entry[1];

      if (value !== initialValues[key]) {
        modifiedValues[key] = value;
      }
    });
  }

  return modifiedValues;
};

const initialValues = {
    firstName: '',
    secondName: '',
    lastName: '',
    password: '',
    age: '',
    bloodGroup: '',
    weight: '',
    leftEye: 1,
    rightEye: 1,
    bmi: 1,
    doctorName: '',
    doctorPhone: 0,
    doctorEmail: '',
    address: '',
    specialist: '',
    lastVisit: new Date(),
    nextVisit: new Date(),
};

<Formik
    initialValues={initialValues}
    validationSchema={Validation}
    onSubmit={(values) => {
        // this function should return the only modified values.
        const modifiedValues = getModifiedValues(values, initialValues);
        dispatch(updateUser(modifiedValues))
    }}
>
...
</Formik>

I found a link, where it has already been answered.

Only send values that have changed in formik onSubmit


来源: stackexchange

问:
A user can overload the default constructor of the class in java is this true or false?
For the code below I was able to overload the default constructor but according to the book JAVA OCA SE 8 by mala gupta this statement is false it says we cannot overload a default constructor any thoughts ?</p>

```<code>package com.sandy.OCA_prep;

class App
{
    static
    {
        System.out.println("inside static block");
    }
    App(int a)
    {
        System.out.println("inside the integer overloaded constructor");
    }
    public static void main( String[] args )
    {
      System.out.println("hello world");

      App app2=new App(5);

    }
}

</code>```

答:
This is a tricky question. By definition the default constructor is the constructor provided by the compiler when you do not include one.
Let's say you write a class and then compile it. In the .class file that will be produced, you will see that there is a no-args constructor, even if you didn't include one in your code. That's the default constructor.
However, as you write your own constructors, the default one will not be inserted by the compiler. Remember that the no-args constructor you write is not considered the default constructor.
So, technically speaking, the default constructor can never be overloaded.</p>

ContentLicense: CC BY-SA 4.0

Body:
For the code below I was able to overload the default constructor but according to the book JAVA OCA SE 8 by mala gupta this statement is false it says we cannot overload a default constructor any thoughts ?

package com.sandy.OCA_prep;

class App
{
    static
    {
        System.out.println("inside static block");
    }
    App(int a)
    {
        System.out.println("inside the integer overloaded constructor");
    }
    public static void main( String[] args )
    {
      System.out.println("hello world");

      App app2=new App(5);

    }
}


问:
Filter empty object in odata
There is an oData service i want to call. We have an model that has an field Parent. The service tells me that the parent is an object with an iv that is an string inside. So we get the following model from the oData service:

```<code>{
"total": 0,
"items": [
    {
    "id": "string",
    "data": {
        "Title": {
            "en": "string",
            "nl": "string"
        },
        "Parent": {
            "iv": [
                "string"
            ]
        },
    }
]
}
</code>```

Now when we get data back it looks like this:

```<code>{
    "total": 2,
    "items": [
        {
            "id": "6204c07d-1aef-4bd2-9646-e3ca36c63784",
            "data": {
                "Title": {
                    "en": "Test 1",
                    "nl": "Test 1"
                },
                "Parent": {
                    "iv": []
                },
            },
        },
        {
            "id": "bfd1b084-4166-4fec-9032-08047c8313d2",
            "data": {
                "Title": {
                    "en": "Test 2",
                    "nl": "Test 2"
                },
                "Parent": {
                    "iv": [
                        "6204c07d-1aef-4bd2-9646-e3ca36c63784"
                    ]
                },
            },
        },
}
</code>```

Now i want to filter on all the items where parent is [] (so no parent selected). I've tried the following filters but all without success

data/Parent/iv eq [] | Returns 0 results

data/Parent/iv eq null | Returns 0 results

data/Parent eq null | Returns 0 results

length(data/Parent/iv) eq 0 | OData operation is not supported

not data/Parent/any() | Any/All may only be used following a collection.

not data/Parent/any() | Any/All may only be used following a collection.

data/Parent/iv/$count eq 0 | Server error

答:
Found that for this case the following works:

empty(data/Parent/iv)

Title: Filter empty object in odata

Body:
There is an oData service i want to call. We have an model that has an field Parent. The service tells me that the parent is an object with an iv that is an string inside. So we get the following model from the oData service:

{
"total": 0,
"items": [
    {
    "id": "string",
    "data": {
        "Title": {
            "en": "string",
            "nl": "string"
        },
        "Parent": {
            "iv": [
                "string"
            ]
        },
    }
]
}

Now when we get data back it looks like this:

{
    "total": 2,
    "items": [
        {
            "id": "6204c07d-1aef-4bd2-9646-e3ca36c63784",
            "data": {
                "Title": {
                    "en": "Test 1",
                    "nl": "Test 1"
                },
                "Parent": {
                    "iv": []
                },
            },
        },
        {
            "id": "bfd1b084-4166-4fec-9032-08047c8313d2",
            "data": {
                "Title": {
                    "en": "Test 2",
                    "nl": "Test 2"
                },
                "Parent": {
                    "iv": [
                        "6204c07d-1aef-4bd2-9646-e3ca36c63784"
                    ]
                },
            },
        },
}

Now i want to filter on all the items where parent is [] (so no parent selected). I've tried the following filters but all without success

data/Parent/iv eq [] | Returns 0 results

data/Parent/iv eq null | Returns 0 results

data/Parent eq null | Returns 0 results

length(data/Parent/iv) eq 0 | OData operation is not supported

not data/Parent/any() | Any/All may only be used following a collection.

not data/Parent/any() | Any/All may only be used following a collection.

data/Parent/iv/$count eq 0 | Server error


问:
Append text in the end of line if search pattern is found
This is my first question on this forum :).

I have a file something like:

```<code>----File--------
XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06
</code>```

I want to search for "search_pattern" and if found look at one line above and append "append_text!" in end of line if its not present.

So the output file should be:-

------------output file------

```<code>XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN append_text!
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06
</code>```

I know perl a little so can do file operations but not good at all with pattern matching. Any pointer will be helpful.

答:
```<code>while(<Your filehandle name>)
{
if ($string =~ m/search_pattern/g)
{
$_=~ s/append_text/**append_text**/g;
}
close(filehandle name)
</code>```

Body:
This is my first question on this forum :).

I have a file something like:

----File--------
XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06

I want to search for "search_pattern" and if found look at one line above and append "append_text!" in end of line if its not present.

So the output file should be:-

------------output file------

XI39/XM79 XI39/XM79#G XI39/XM79#S XI39/XM79#D XI39/XM79#B XI39/XM79#DN append_text!
+ search_pattern
+ w=5e-07 l=3.85e-07 sa=4.1e-07 sb=4.1e-07 ad=2.05e-13 as=2.05e-13 pd=1.82e-06

XI57/XM0@1 XI57/XM0@1#G XI57/XM0@1#S XI57/XM0@1#D XI57/XM0@1#B XI57/XM0@1#DN append_text!
+ search_pattern
+ w=1e-06 l=3.85e-07 sa=4.1e-07 sb=1.215e-06 ad=2.1e-13 as=4.1e-13 pd=1.42e-06

I know perl a little so can do file operations but not good at all with pattern matching. Any pointer will be helpful.


问:
gcloud app deploy but Setting traffic false current version
I am updating my code on google app engine but

```<code>gcloud app deploy  -v logic-demo
</code>```

By default traffic set on this version but i don't want to do this

How can do this?

答:
To prevent traffic from being automatically routed to the new version, use the --no-promote flag.
https://cloud.google.com/appengine/docs/flexible/nodejs/testing-and-deploying-your-app

Then you will be able to migrate the trafic from the Google Cloud console.

Body:
I am updating my code on google app engine but

gcloud app deploy  -v logic-demo

By default traffic set on this version but i don't want to do this

How can do this?


问:
Select only the first element 'libro' that don't have the attribute 'paginas'
Given the attached xml file:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <biblioteca>
      <libro paginas="100">
        <titulo>Los bandidos de la playa</titulo>
        <autor>Rosario Lopez</autor>
        <isbn>1231-123-123-2233</isbn>
        <precio>123</precio>
        <fechaPublicacion año="1920"/>
      </libro>
      <libro paginas="200">
        <titulo>Indagaciones publicas</titulo>
        <autor sexo="M">Aurora Laspitas</autor>
        <isbn>1231-222-3333-4444</isbn>
        <precio>40</precio>
        <fechaPublicacion año="2000"/>
      </libro>
      <libro>
        <titulo>libro barato</titulo>
        <autor sexo="H">Cipriano Lopez</autor>
        <isbn>1231-2343 32333333</isbn>
        <precio>10</precio>
        <fechaPublicacion año="1978"/>
      </libro>
      <libro>
        <titulo>libro de ayuda</titulo>
        <autor sexo="H">Zacarias Sanchez</autor>
        <isbn>1231-2343 32333333</isbn>
        <precio>10</precio>
        <fechaPublicacion año="1999"/>
      </libro>
   </biblioteca>
</code>```

I want to select only the first element 'libro' that doesn't have the attribute 'paginas'.
Here is my try that doesn't work:

/biblioteca/libro[not(@paginas)]/../libro[1]

Thanks

答:
You can use this XPath-1.0 expression:</p>

```<code>/biblioteca/libro[not(@paginas)][1]
</code>```

Body:
Given the attached xml file:

    <?xml version="1.0" encoding="UTF-8"?>
    <biblioteca>
      <libro paginas="100">
        <titulo>Los bandidos de la playa</titulo>
        <autor>Rosario Lopez</autor>
        <isbn>1231-123-123-2233</isbn>
        <precio>123</precio>
        <fechaPublicacion año="1920"/>
      </libro>
      <libro paginas="200">
        <titulo>Indagaciones publicas</titulo>
        <autor sexo="M">Aurora Laspitas</autor>
        <isbn>1231-222-3333-4444</isbn>
        <precio>40</precio>
        <fechaPublicacion año="2000"/>
      </libro>
      <libro>
        <titulo>libro barato</titulo>
        <autor sexo="H">Cipriano Lopez</autor>
        <isbn>1231-2343 32333333</isbn>
        <precio>10</precio>
        <fechaPublicacion año="1978"/>
      </libro>
      <libro>
        <titulo>libro de ayuda</titulo>
        <autor sexo="H">Zacarias Sanchez</autor>
        <isbn>1231-2343 32333333</isbn>
        <precio>10</precio>
        <fechaPublicacion año="1999"/>
      </libro>
   </biblioteca>

I want to select only the first element 'libro' that doesn't have the attribute 'paginas'.
Here is my try that doesn't work:

/biblioteca/libro[not(@paginas)]/../libro[1]

Thanks

Body:
You can use this XPath-1.0 expression:

/biblioteca/libro[not(@paginas)][1]


问:
Logstash: Custom delimiter for multi-line XML logs
I have XML logs where logs are closed with "=======", e.g.

```<code><log>
  <level>DEBUG</level>
  <message>This is debug level</message>
</log>

=======

<log>
  <level>ERROR</level>
  <message>This is error level</message>
</log>

=======
</code>```

Every log can span across multiple lines.

How to parse those logs using logstash?

答:
This can be done using multiline codec. The delimiter "=======" can be used in pattern like this

```<code>input {
  file {
    type => "xml"
    path => "/path/to/logs/*.log"
    codec => multiline {
      pattern => "^======="
      negate => "true"
      what => "previous"
    }
  }
}

filter {
  mutate {
    gsub => [ "message", "=======", ""]
  }
  xml {
    force_array => false
    source => "message"
    target => "log"
  }
  mutate {
    remove_field => [ "message" ]
  }
}

output {
  elasticsearch {
    codec => json
    hosts => ["http://localhost:9200"]
    index => "logs-%{+YYYY.MM.dd}"
  }
}
</code>```

Here the combination of pattern and negate => true means: if a line does not start with "=======" it belongs to the previous event (thus what => "previous"). When a line with the delimiter is hit, we start a new event. In the filter the delimiter is simply removed with gsub and XML is parsed with xml plugin.

Body:
I have XML logs where logs are closed with "=======", e.g.

<log>
  <level>DEBUG</level>
  <message>This is debug level</message>
</log>

=======

<log>
  <level>ERROR</level>
  <message>This is error level</message>
</log>

=======

Every log can span across multiple lines.

How to parse those logs using logstash?

Body:
This can be done using multiline codec. The delimiter "=======" can be used in pattern like this

input {
  file {
    type => "xml"
    path => "/path/to/logs/*.log"
    codec => multiline {
      pattern => "^======="
      negate => "true"
      what => "previous"
    }
  }
}

filter {
  mutate {
    gsub => [ "message", "=======", ""]
  }
  xml {
    force_array => false
    source => "message"
    target => "log"
  }
  mutate {
    remove_field => [ "message" ]
  }
}

output {
  elasticsearch {
    codec => json
    hosts => ["http://localhost:9200"]
    index => "logs-%{+YYYY.MM.dd}"
  }
}

Here the combination of pattern and negate => true means: if a line does not start with "=======" it belongs to the previous event (thus what => "previous"). When a line with the delimiter is hit, we start a new event. In the filter the delimiter is simply removed with gsub and XML is parsed with xml plugin.


问:
Why when i'm parsing a website i'm getting old data from site and sometimes current data in site
I'm scraping a website and i'm retrieving a table and a line of date.
Everything works fine but when i run my script i'm getting the current data from the site and sometimes i'm getting yesterday values from the site.

When i'm entering the site the data is always updated.

This is part of my code, full code is at:
http://pythonfiddle.com/lme

```<code>url = 'https://www.lme.com/en-gb/metals/non-ferrous/#tabIndex=0'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
dateFromSite = soup.find('div', class_='delayed-date').text.strip()
</code>```

答:
Looking at the HTTP headers obtained from the page, the site is using Cloudflare for caching the requests. So sometimes you get "old" version of the page.

You can try to circumvent this using http 'Cache-Control: no-cache, must-revalidate' header and/or using random parameter added to the url.

For example:

```<code>import time

url = 'https://www.lme.com/en-gb/metals/non-ferrous/?_random_number={rn}#tabIndex=0'
headers = {'Cache-Control': 'no-cache, must-revalidate'}

r = requests.get(url.format(rn=time.time()), headers=headers)
#print(r.headers) # should print 'CF-Cache-Status': 'MISS' in headers
soup = BeautifulSoup(r.text, 'html.parser')
dateFromSite = soup.find('div', class_='delayed-date').text.strip()

print(dateFromSite)
</code>```

Body:
I'm scraping a website and i'm retrieving a table and a line of date.
Everything works fine but when i run my script i'm getting the current data from the site and sometimes i'm getting yesterday values from the site.

When i'm entering the site the data is always updated.

This is part of my code, full code is at:
http://pythonfiddle.com/lme

url = 'https://www.lme.com/en-gb/metals/non-ferrous/#tabIndex=0'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
dateFromSite = soup.find('div', class_='delayed-date').text.strip()

Body:
Looking at the HTTP headers obtained from the page, the site is using Cloudflare for caching the requests. So sometimes you get "old" version of the page.

You can try to circumvent this using http 'Cache-Control: no-cache, must-revalidate' header and/or using random parameter added to the url.

For example:

import time

url = 'https://www.lme.com/en-gb/metals/non-ferrous/?_random_number={rn}#tabIndex=0'
headers = {'Cache-Control': 'no-cache, must-revalidate'}

r = requests.get(url.format(rn=time.time()), headers=headers)
#print(r.headers) # should print 'CF-Cache-Status': 'MISS' in headers
soup = BeautifulSoup(r.text, 'html.parser')
dateFromSite = soup.find('div', class_='delayed-date').text.strip()

print(dateFromSite)


问:
How to find the features names of the coefficients using scikit linear regression?
I use scikit linear regression and if I change the order of the features, the coef are still printed in the same order, hence I would like to know the mapping of the feature with the coeff.</p>
```<code>#training the model
model_1_features = ['sqft_living', 'bathrooms', 'bedrooms', 'lat', 'long']
model_2_features = model_1_features + ['bed_bath_rooms']
model_3_features = model_2_features + ['bedrooms_squared', 'log_sqft_living', 'lat_plus_long']

model_1 = linear_model.LinearRegression()
model_1.fit(train_data[model_1_features], train_data['price'])

model_2 = linear_model.LinearRegression()
model_2.fit(train_data[model_2_features], train_data['price'])

model_3 = linear_model.LinearRegression()
model_3.fit(train_data[model_3_features], train_data['price'])

# extracting the coef
print model_1.coef_
print model_2.coef_
print model_3.coef_
</code>```

答:
```<code>import pandas as pd

import numpy as np

from sklearn.linear_model import LinearRegression

regressor = LinearRegression()
regressor.fit(X_train, y_train)

coef_table = pd.DataFrame(list(X_train.columns)).copy()
coef_table.insert(len(coef_table.columns),"Coefs",regressor.coef_.transpose())
</code>```

Body:
I use scikit linear regression and if I change the order of the features, the coef are still printed in the same order, hence I would like to know the mapping of the feature with the coeff.

#training the model
model_1_features = ['sqft_living', 'bathrooms', 'bedrooms', 'lat', 'long']
model_2_features = model_1_features + ['bed_bath_rooms']
model_3_features = model_2_features + ['bedrooms_squared', 'log_sqft_living', 'lat_plus_long']

model_1 = linear_model.LinearRegression()
model_1.fit(train_data[model_1_features], train_data['price'])

model_2 = linear_model.LinearRegression()
model_2.fit(train_data[model_2_features], train_data['price'])

model_3 = linear_model.LinearRegression()
model_3.fit(train_data[model_3_features], train_data['price'])

# extracting the coef
print model_1.coef_
print model_2.coef_
print model_3.coef_


问:
jQuery chained animation without plugin
Before with jQuery I could do a chained animation with a delay between like so:

```<code>$("#element").delay(45).animate({ }, 45)
             .delay(45).animate({ }, 45)
             .delay(45).animate({ }, 45);
</code>```

Now since the update to v1.6.1 instead of doing what it did previously, it now skips to the last animation. Ignoring the previous statements. I know I can do an oncomplete callback for each animation but that just get's messy:

```<code>$("#element").delay(45).animate({ }, 45, function(){
    $("#element").delay(45).animate({ }, 45, function(){
        $("#element").delay(45).animate({ }, 45);
    })
})
</code>```

Does anyone know how I can accomplish this in a simple clean way?

答:
Edit: added a Fiddle for you to play with

I wrote this piece of code a while ago, perhaps it's useful for you? (sorry for the messy indenting)

```<code>/**
 * Queue.js
 *
 * @author Arend van Waart
 *
 *  This will allow for events to be queued by timestamp
 *
 * @example
 *  queue({
 *  1000: function () {
 *       // element a na 10ms uitfaden, en daar 100ms over doen
 *       $('#menu').fadeOut(2000);
 *  },
 *  500: function () {
 *    // na 50 ms element b en c inzoemen
 *    $('#content').slideUp(2000);
 * }
 * });
 */

var queue = function(queue){
    var self = this;
    // queue
    this.queue = queue;
    // time passed is 0
    this.timePassed = 0;
    // time in ms to sleep between checks.
    this.sleep = 100;

    var time = new Date();
    this.lastTime = time.getTime();
    this.iterate = function(){
        var total = 0;
        var time = new Date();

        // how much time has passed since we slept?
        self.timePassed = self.timePassed + (time.getTime() - self.lastTime);
        self.lastTime = time.getTime();
        for (var t in self.queue){
            if (t <= self.timePassed){
                self.queue[t]();
                delete(self.queue[t]);
            }
            total++;
        }

        if (total == 0){
            return;
        }else{
            setTimeout(self.iterate, self.sleep);
        }
    }
    this.iterate();
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: jQuery chained animation without plugin

Body:
Before with jQuery I could do a chained animation with a delay between like so:

$("#element").delay(45).animate({ }, 45)
             .delay(45).animate({ }, 45)
             .delay(45).animate({ }, 45);

Now since the update to v1.6.1 instead of doing what it did previously, it now skips to the last animation. Ignoring the previous statements. I know I can do an oncomplete callback for each animation but that just get's messy:

$("#element").delay(45).animate({ }, 45, function(){
    $("#element").delay(45).animate({ }, 45, function(){
        $("#element").delay(45).animate({ }, 45);
    })
})

Does anyone know how I can accomplish this in a simple clean way?

Body:
Edit: added a Fiddle for you to play with

I wrote this piece of code a while ago, perhaps it's useful for you? (sorry for the messy indenting)

/**
 * Queue.js
 *
 * @author Arend van Waart
 *
 *  This will allow for events to be queued by timestamp
 *
 * @example
 *  queue({
 *  1000: function () {
 *       // element a na 10ms uitfaden, en daar 100ms over doen
 *       $('#menu').fadeOut(2000);
 *  },
 *  500: function () {
 *    // na 50 ms element b en c inzoemen
 *    $('#content').slideUp(2000);
 * }
 * });
 */

var queue = function(queue){
    var self = this;
    // queue
    this.queue = queue;
    // time passed is 0
    this.timePassed = 0;
    // time in ms to sleep between checks.
    this.sleep = 100;

    var time = new Date();
    this.lastTime = time.getTime();
    this.iterate = function(){
        var total = 0;
        var time = new Date();

        // how much time has passed since we slept?
        self.timePassed = self.timePassed + (time.getTime() - self.lastTime);
        self.lastTime = time.getTime();
        for (var t in self.queue){
            if (t <= self.timePassed){
                self.queue[t]();
                delete(self.queue[t]);
            }
            total++;
        }

        if (total == 0){
            return;
        }else{
            setTimeout(self.iterate, self.sleep);
        }
    }
    this.iterate();
}


问:
Why mouseover and mouseout is not working properly in javascript?
I have a button

```<code><button onmouseover="Lobby()" class="menuBtn"> Lobby </button>
</code>```

then I have a Lobby()

```<code>function Lobby()
    {
        document.getElementById("lobby").style.display = "block";
    }
</code>```

and then I have a style

```<code>#lobby
{
  display: none;
  height: 100%;
  width: 16%;
}
</code>```

I have a div

```<code><div onmouseout="HideLobby()" class="submenupanel" id="lobby">
        <button onclick="" class="l">Lobby</button>
        <button onclick="GoToHelpDesk()" class="l">Information Center</button>
        <button onclick="ProductDisplay()" class="l">Product Display</button>
    </div>
</code>```

Another Function

```<code>function HideLobby()
    {
        document.getElementById("lobby").style.display = "none";
    }
</code>```

So When I hover to Lobby Button its showing div as it should. And when I remove my mouse from div its hiding as it should. But when I hover on Information Center or Product Display div is hiding. Why?

答:
Use onmouseleave instead onmouseout

The mouseout event triggers when the mouse pointer leaves any child
  elements as well the selected element.

The mouseleave event is only triggered when the mouse pointer leaves
  the selected element.

function Lobby() {
  document.getElementById("lobby").style.display = "block";
}

function HideLobby(event) {
  document.getElementById("lobby").style.display = "none";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#lobby {
  display: none;
  height: 100%;
  width: 16%;
}</code>```

<button onmouseover="Lobby()" class="menuBtn"> Lobby </button>

  <button onclick="" class="l">Lobby</button>
  <button onclick="GoToHelpDesk()" class="l">Information Center</button>
  <button onclick="ProductDisplay()" class="l">Product Display</button>

```

Body:
I have a button

<button onmouseover="Lobby()" class="menuBtn"> Lobby </button>

then I have a Lobby()

function Lobby()
    {
        document.getElementById("lobby").style.display = "block";
    }

and then I have a style

#lobby
{
  display: none;
  height: 100%;
  width: 16%;
}

I have a div

        <button onclick="" class="l">Lobby</button>
        <button onclick="GoToHelpDesk()" class="l">Information Center</button>
        <button onclick="ProductDisplay()" class="l">Product Display</button>

Another Function

function HideLobby()
    {
        document.getElementById("lobby").style.display = "none";
    }

So When I hover to Lobby Button its showing div as it should. And when I remove my mouse from div its hiding as it should. But when I hover on Information Center or Product Display div is hiding. Why?

Body:
Use onmouseleave instead onmouseout

The mouseout event triggers when the mouse pointer leaves any child
  elements as well the selected element.

The mouseleave event is only triggered when the mouse pointer leaves
  the selected element.

function Lobby() {
  document.getElementById("lobby").style.display = "block";
}

function HideLobby(event) {
  document.getElementById("lobby").style.display = "none";
}

#lobby {
  display: none;
  height: 100%;
  width: 16%;
}

<button onmouseover="Lobby()" class="menuBtn"> Lobby </button>

<div onmouseleave="HideLobby()" class="submenupanel" id="lobby">
  <button onclick="" class="l">Lobby</button>
  <button onclick="GoToHelpDesk()" class="l">Information Center</button>
  <button onclick="ProductDisplay()" class="l">Product Display</button>
</div>


问:
Java Spark - Multiple value check on Spark dataframe column while using when condition
I have a dataframe where I am creating a column and populating values based on conditions in other columns.

```<code>List<String> new_lst = new ArrayList<String>();
new_lst.add("value 1");
new_lst.add("value_2");

df_new = df.withColumn("new_column",functions.when(functions.col("col_1").equalTo("A")
.and(functions.col("col_2").isin(new_lst.stream().toArray(String[]::new)),functions.col("col_3"))
.otherwise(functions.col("col_1");
</code>```

When i use the above i get a warning that

Confusing argument new_lst.stream().toArray(String[]::new, unclear if
  a varargs or non-varargs call is desired

My requirement is that i am creating a column called new_column by check if col_1 is equal to A and
col_2 has value_1 and value_2 then i have to get values from col_3, else from col_1.

Kindly let me know the best way to implement this in java spark.

答:
THe api is as below-

```<code>def isin(list: Any*): Column = withExpr { In(expr, list.map(lit(_).expr)) }
</code>```

Its basically Array<Object> from java.
Try below approach- use either isInCollection(Iterable<>) or isin(Object[])

 List<String> new_lst = new ArrayList<>();
        new_lst.add("value_1");
        new_lst.add("value_2");

        Dataset<Row> df = spark.range(1).withColumn("col_1", lit("A"))
                .withColumn("col_2", lit("value_2"))
                .withColumn("col_3", lit("C"));
        Dataset<Row> df_new = df.withColumn("new_column",functions.when(functions.col("col_1").equalTo("A")
                .and(functions.col("col_2").isInCollection(new_lst)), functions.col("col_3"))
                .otherwise(functions.col("col_1"))
        );
        df_new.show(false);

        /**
         * +---+-----+-------+-----+----------+
         * |id |col_1|col_2  |col_3|new_column|
         * +---+-----+-------+-----+----------+
         * |0  |A    |value_2|C    |C         |
         * +---+-----+-------+-----+----------+
         */
        df.withColumn("new_column",functions.when(functions.col("col_1").equalTo("A")
                .and(functions.col("col_2").isin((Object[]) new_lst.toArray())),functions.col("col_3"))
                .otherwise(functions.col("col_1"))).show(false);
        /**
         * +---+-----+-------+-----+----------+
         * |id |col_1|col_2  |col_3|new_column|
         * +---+-----+-------+-----+----------+
         * |0  |A    |value_2|C    |C         |
         * +---+-----+-------+-----+----------+
         */
```

Body:
I have a dataframe where I am creating a column and populating values based on conditions in other columns.

List<String> new_lst = new ArrayList<String>();
new_lst.add("value 1");
new_lst.add("value_2");

df_new = df.withColumn("new_column",functions.when(functions.col("col_1").equalTo("A")
.and(functions.col("col_2").isin(new_lst.stream().toArray(String[]::new)),functions.col("col_3"))
.otherwise(functions.col("col_1");

When i use the above i get a warning that

Confusing argument new_lst.stream().toArray(String[]::new, unclear if
  a varargs or non-varargs call is desired

My requirement is that i am creating a column called new_column by check if col_1 is equal to A and
col_2 has value_1 and value_2 then i have to get values from col_3, else from col_1.

Kindly let me know the best way to implement this in java spark.

Body:
THe api is as below-

def isin(list: Any*): Column = withExpr { In(expr, list.map(lit(_).expr)) }

Its basically Array<Object> from java.
Try below approach- use either isInCollection(Iterable<>) or isin(Object[])

 List<String> new_lst = new ArrayList<>();
        new_lst.add("value_1");
        new_lst.add("value_2");

        Dataset<Row> df = spark.range(1).withColumn("col_1", lit("A"))
                .withColumn("col_2", lit("value_2"))
                .withColumn("col_3", lit("C"));
        Dataset<Row> df_new = df.withColumn("new_column",functions.when(functions.col("col_1").equalTo("A")
                .and(functions.col("col_2").isInCollection(new_lst)), functions.col("col_3"))
                .otherwise(functions.col("col_1"))
        );
        df_new.show(false);

        /**
         * +---+-----+-------+-----+----------+
         * |id |col_1|col_2  |col_3|new_column|
         * +---+-----+-------+-----+----------+
         * |0  |A    |value_2|C    |C         |
         * +---+-----+-------+-----+----------+
         */
        df.withColumn("new_column",functions.when(functions.col("col_1").equalTo("A")
                .and(functions.col("col_2").isin((Object[]) new_lst.toArray())),functions.col("col_3"))
                .otherwise(functions.col("col_1"))).show(false);
        /**
         * +---+-----+-------+-----+----------+
         * |id |col_1|col_2  |col_3|new_column|
         * +---+-----+-------+-----+----------+
         * |0  |A    |value_2|C    |C         |
         * +---+-----+-------+-----+----------+
         */


问:
C++: Indicating a function may throw

Possible Duplicate:

  Is there a generally accepted idiom for indicating C++ code can throw exceptions?

How do you indicate in your code when a C++ function is possible to throw something? I don't mean through documentation, but through syntax.

For example I tried placing a throw(std::exception) at the end of the function declaration, but that gave me a warning saying that "C++ exception specification ignored except to indicate a function is not __declspec(nothrow)", which I guess means the compiler ignored the throw and proceeded as if it were not there.

I also tried adding a throw() (without anything in the parenthesis) at the end of the declaration, but — contrary to my expectations — that means the function is expected to never throw anything: "function assumed not to throw an exception but does".

Atm I'm using throw(...) to syntactically indicate the function may throw as this doesn't give me any errors or warnings. Do you have any other suggestions as to how I might indicate this through syntax?

答:
Most of the compilers are non conforming to the standard when it comes to Exception specifications. Exceptions specifications are considered as an experiment that failed.

For example:

If you have a blank  exception specification then what gets called? the unexpected() method or a bad_exception will be thrown and if both in what order?

```<code> #include "stdafx.h"
 #include <stdio.h>
 #include <exception>
 #include <iostream>

using namespace std;

class A
{
    public:
        int i;
};

void myunexpected ()
{
    cerr << "unexpected called\n";
}

void doSomething(void) throw();
void doSomething(void) throw()
{
    A obj;
    obj.i= 100;
    throw obj;
}

int _tmain(int argc, _TCHAR* argv[])
{
    set_unexpected (myunexpected);
    try
    {
        doSomething();
    }
    catch (bad_exception be)
    {
        puts("Caught something");
    }
    catch (A &obj)
    {
        puts("Caught Integer");
    }
    return 0;
}
</code>```

If you run this code on Visual studio, you will see that the exception just gets caught by the appropriate handler.

So to conclude, Exception specifications is a failed experiment and it's best to avoid them.

Title: C++: Indicating a function may throw

Body:
Most of the compilers are non conforming to the standard when it comes to Exception specifications. Exceptions specifications are considered as an experiment that failed.

For example:

If you have a blank  exception specification then what gets called? the unexpected() method or a bad_exception will be thrown and if both in what order?

 #include "stdafx.h"
 #include <stdio.h>
 #include <exception>
 #include <iostream>

using namespace std;

class A
{
    public:
        int i;
};

void myunexpected ()
{
    cerr << "unexpected called\n";
}

void doSomething(void) throw();
void doSomething(void) throw()
{
    A obj;
    obj.i= 100;
    throw obj;
}

int _tmain(int argc, _TCHAR* argv[])
{
    set_unexpected (myunexpected);
    try
    {
        doSomething();
    }
    catch (bad_exception be)
    {
        puts("Caught something");
    }
    catch (A &obj)
    {
        puts("Caught Integer");
    }
    return 0;
}

If you run this code on Visual studio, you will see that the exception just gets caught by the appropriate handler.

So to conclude, Exception specifications is a failed experiment and it's best to avoid them.


答:
You can deploy a new App Engine version without directing traffic to it by using the --no-promote flag, like this:

```<code>gcloud app deploy --no-promote -v logic-demo
</code>```

If you prefer that new versions deployments are never promoted by default, you can also set it as default in gcloud for all deployment by running:

```<code>gcloud config set app/promote_by_default false
</code>```

All subsequent deployment will then never be promoted. You'll need to direct traffic to it manually. For example, to send all traffic to 'v2' of service 's1', you can run:

```<code>gcloud app services set-traffic s1 --splits v2=1
</code>```

Title: gcloud app deploy but Setting traffic false current version

Body:
You can deploy a new App Engine version without directing traffic to it by using the --no-promote flag, like this:

gcloud app deploy --no-promote -v logic-demo

If you prefer that new versions deployments are never promoted by default, you can also set it as default in gcloud for all deployment by running:

gcloud config set app/promote_by_default false

All subsequent deployment will then never be promoted. You'll need to direct traffic to it manually. For example, to send all traffic to 'v2' of service 's1', you can run:

gcloud app services set-traffic s1 --splits v2=1


问:
How to get a flatten dataframe from lists of dictionaries which contain lists?
I'm trying to flat this kind of data structure into a "plain" dataframe.

Raw data is a list of dictionaries, which contain lists.

Data looks like this( reproducible example):

```<code>data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]
</code>```

My desidered output should be the following pandas dataframe:

```<code>Out[01]:
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18
</code>```

How can i achieve this result?
Thanks

答:
For improve performance use collections.defaultdict with extend:

```<code>from collections import defaultdict

d = defaultdict(list)
for x in data:
    for k, v in x.items():
        d[k].extend(v)
df = pd.DataFrame(d)
print (df)
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18
</code>```

Body:
I'm trying to flat this kind of data structure into a "plain" dataframe.

Raw data is a list of dictionaries, which contain lists.

Data looks like this( reproducible example):

data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

My desidered output should be the following pandas dataframe:

Out[01]:
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18

How can i achieve this result?
Thanks

Body:
For improve performance use collections.defaultdict with extend:

from collections import defaultdict

d = defaultdict(list)
for x in data:
    for k, v in x.items():
        d[k].extend(v)
df = pd.DataFrame(d)
print (df)
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18


问:
How to close child/nested dialog using matDialogClose instead of parent dialog
I am having a two dialogs with a sort of parent-child relationship. Parent is a standalone dialog component while child is created from ng-template

Now, the problem is, that if I use matDialogClose inside ng-template parent dialog is closed, and child is intact.

Here is a stackblitz for you
https://stackblitz.com/edit/mat-dialog-example-vbxhc3

Main dialog template

```<code><ng-template #nested>
    hey, i am nested dialog, close me with the button
    <button matDialogClose="someResult">CLOSE ME </button>
</ng-template>
</code>```

opening child template

```<code>  @ViewChild("nested")
  nestedTmplateRef;
  private dialog:MatDialog
  ...
   this.dialog.open(this.nestedTmplateRef);
</code>```

Can I close child dialog using matCloseDialog directive?? I am interested in using this solution as other obvious workarounds like controlling child dialog from component is know to me. However, using just directive would save me some boilerplace code. I am little bit rusty with angular material components and probably I dont see a obvious solution.

答:
That seems to be a bug in material. If you check the code here you can see the comment:

When this directive is included in a dialog via TemplateRef (rather than being in a Component), the DialogRef isn't available via injection because embedded views cannot be given a custom injector. Instead, we look up the DialogRef by ID. This must occur in onInit, as the ID binding for the dialog container won't be resolved at constructor time.

However, when using a nested dialog, the method getClosestDialog does not seem to get the correct dialog.

I've made a sort of workaround for it though, and perhaps you can create a custom directive from this logic to make it reusable:

By adding a reference on the MatDialogClose and querying this in your component you can set the correct dialog reference:

```<code><ng-template #nested>
  hey, i am nested dialog, close me with the button
  <button matDialogClose="someResult" #innerClose="matDialogClose">CLOSE ME </button>
</ng-template>
</code>```

```<code>@ViewChild("nested")
nestedTmplateRef;

@ViewChild('innerClose')
close: MatDialogClose;

ngOnInit(){
  const ref = this.dialog.open(this.nestedTmplateRef);

  // have to wait for the next tick so the `dialogRef` does not get overwritten again
  setTimeout(() => this.close.dialogRef = ref);
}
</code>```

working stackblitz

Body:
I am having a two dialogs with a sort of parent-child relationship. Parent is a standalone dialog component while child is created from ng-template

Now, the problem is, that if I use matDialogClose inside ng-template parent dialog is closed, and child is intact.

Here is a stackblitz for you
https://stackblitz.com/edit/mat-dialog-example-vbxhc3

Main dialog template

<ng-template #nested>
    hey, i am nested dialog, close me with the button
    <button matDialogClose="someResult">CLOSE ME </button>
</ng-template>

opening child template

  @ViewChild("nested")
  nestedTmplateRef;
  private dialog:MatDialog
  ...
   this.dialog.open(this.nestedTmplateRef);

Can I close child dialog using matCloseDialog directive?? I am interested in using this solution as other obvious workarounds like controlling child dialog from component is know to me. However, using just directive would save me some boilerplace code. I am little bit rusty with angular material components and probably I dont see a obvious solution.

Body:
That seems to be a bug in material. If you check the code here you can see the comment:

When this directive is included in a dialog via TemplateRef (rather than being in a Component), the DialogRef isn't available via injection because embedded views cannot be given a custom injector. Instead, we look up the DialogRef by ID. This must occur in onInit, as the ID binding for the dialog container won't be resolved at constructor time.

However, when using a nested dialog, the method getClosestDialog does not seem to get the correct dialog.

I've made a sort of workaround for it though, and perhaps you can create a custom directive from this logic to make it reusable:

By adding a reference on the MatDialogClose and querying this in your component you can set the correct dialog reference:

<ng-template #nested>
  hey, i am nested dialog, close me with the button
  <button matDialogClose="someResult" #innerClose="matDialogClose">CLOSE ME </button>
</ng-template>

@ViewChild("nested")
nestedTmplateRef;

@ViewChild('innerClose')
close: MatDialogClose;

ngOnInit(){
  const ref = this.dialog.open(this.nestedTmplateRef);

  // have to wait for the next tick so the `dialogRef` does not get overwritten again
  setTimeout(() => this.close.dialogRef = ref);
}

working stackblitz


问:
Create new user on Keycloack 10.0.1 from curl command
Currently I try to create a user from curl command via Keycloak's Admin REST API. I can authenticate myself as an admin, I have a good answer, but when I want to create a user then we are getting error like: 548 {"error":"HTTP 401 Unauthorized"}

Here are my curl commands:

```<code>#!/bin/bash
echo "* Request for authorization"
RESULT=`curl --data "username=rahul&password=password&grant_type=password&    client_id=admin-cli" http://localhost:8080/auth/realms/demo/protocol/openid-connect/token`

echo "\n"
echo "* Recovery of the token"
TOKEN=`echo $RESULT | sed 's/.*access_token":"//g' | sed 's/".*//g'`

echo "\n"
echo "* Display token"
echo $TOKEN

echo "\n"
echo " * user creation\n"
curl -v http://localhost:8080/auth/admin/realms/demo/users -H "Content-Type: application/json" -H "Authorization: bearer $TOKEN"   --data '{"firstName":"xyz","lastName":"xyz", "email":"demo2@gmail.com", "enabled":"true"}'
</code>```

Error logs:

```<code> curl -v http://localhost:8080/auth/admin/realms/demo/users -H "Content-Type: application/json" -H "Authorization: bearer $TOKEN"   --data '{"firstName":"xyz","lastName":"xyz", "email":"demo2@gmail.com", "enabled":"true"}'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0*   Trying ::1:8080...
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /auth/admin/realms/demo/users HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.70.0
> Accept: */*
> Content-Type: application/json
> Authorization: bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJuNGhwUUdSeUZDcmhCTzJZbWhwc0FOWG9ZY0Ztak9CMmF3Y0RPdTNNOHhRIn0.eyJleHAiOjE1OTEwMTE0MDEsImlhdCI6MTU5MTAxMTEwMSwianRpIjoiYWMxYTYyZTEtYzUwMi00NzQ0LTgwMDAtMGQ2MWFkMzU2YzIxIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL2RlbW8iLCJzdWIiOiJjYTc0MDk1Ni1jOTQ2LTQ2ZjktODBkZS1jOTFkZDc4MWJjMTIiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiMDdjODFjODQtM2FlOS00NzUyLTkxMzgtMWY4Yzg2Zjg3NWMzIiwiYWNyIjoiMSIsInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwibmFtZSI6IlJhaHVsIEt1bWFyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoicmFodWwiLCJnaXZlbl9uYW1lIjoiUmFodWwiLCJmYW1pbHlfbmFtZSI6Ikt1bWFyIiwiZW1haWwiOiJhYmNAYWJjLmNvbSJ9.BP1krGeTyTVPhKY8zHCmYowNwnGWl-lgMN7XKukUjRgxl6EEJwERwtbiruX0Qv6bZOAx5VMCntcWLPQgCTFzFXJSOnqf_YLKoUEUKrB3Lp8RHgAax0daPFVp2F86cAQ4x_ExADqepcujinvi1qP-wyWidEEVq6_j6aprzLl59y8cN6mWYL2yIZ2Vb6ZnjFHLOsOo-GZBsE1t31nG8rqPscKKhGVj7SLwexnPXCATmqYW1sc6LJgUUh2zcJrI-L8hgfyTyUHrgzi5gB7YE5mRi3M1vyHfmKNSvnca-UXo7O8OHzTzTmrDQcaTrk86xaSCcL4qm-7s9xHLeYGMAqwGEQ
> Content-Length: 81
>
} [81 bytes data]
* upload completely sent off: 81 out of 81 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 401 Unauthorized
< Connection: keep-alive
< X-XSS-Protection: 1; mode=block
< Strict-Transport-Security: max-age=31536000; includeSubDomains
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< 548{"error":"HTTP 401 Unauthorized"}
* Connection #0 to host localhost left intact
</code>```

答:
"HTTP 401 Unauthorized" as the error message correct implies is that the request is unauthorized. This means that the authentication details in your call are incorrect.

In your request, you send the bearer prefix as "bearer";

Content-Type: application/json
  Authorization: bearer <>
  Content-Length: 81

Change this to "Bearer <>" and see if it works.
Good day!

Body:
Currently I try to create a user from curl command via Keycloak's Admin REST API. I can authenticate myself as an admin, I have a good answer, but when I want to create a user then we are getting error like: 548 {"error":"HTTP 401 Unauthorized"}

Here are my curl commands:

#!/bin/bash
echo "* Request for authorization"
RESULT=`curl --data "username=rahul&password=password&grant_type=password&    client_id=admin-cli" http://localhost:8080/auth/realms/demo/protocol/openid-connect/token`

echo "\n"
echo "* Recovery of the token"
TOKEN=`echo $RESULT | sed 's/.*access_token":"//g' | sed 's/".*//g'`

echo "\n"
echo "* Display token"
echo $TOKEN

echo "\n"
echo " * user creation\n"
curl -v http://localhost:8080/auth/admin/realms/demo/users -H "Content-Type: application/json" -H "Authorization: bearer $TOKEN"   --data '{"firstName":"xyz","lastName":"xyz", "email":"demo2@gmail.com", "enabled":"true"}'

Error logs:

 curl -v http://localhost:8080/auth/admin/realms/demo/users -H "Content-Type: application/json" -H "Authorization: bearer $TOKEN"   --data '{"firstName":"xyz","lastName":"xyz", "email":"demo2@gmail.com", "enabled":"true"}'
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0*   Trying ::1:8080...
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /auth/admin/realms/demo/users HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.70.0
> Accept: */*
> Content-Type: application/json
> Authorization: bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJuNGhwUUdSeUZDcmhCTzJZbWhwc0FOWG9ZY0Ztak9CMmF3Y0RPdTNNOHhRIn0.eyJleHAiOjE1OTEwMTE0MDEsImlhdCI6MTU5MTAxMTEwMSwianRpIjoiYWMxYTYyZTEtYzUwMi00NzQ0LTgwMDAtMGQ2MWFkMzU2YzIxIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL2F1dGgvcmVhbG1zL2RlbW8iLCJzdWIiOiJjYTc0MDk1Ni1jOTQ2LTQ2ZjktODBkZS1jOTFkZDc4MWJjMTIiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiMDdjODFjODQtM2FlOS00NzUyLTkxMzgtMWY4Yzg2Zjg3NWMzIiwiYWNyIjoiMSIsInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwibmFtZSI6IlJhaHVsIEt1bWFyIiwicHJlZmVycmVkX3VzZXJuYW1lIjoicmFodWwiLCJnaXZlbl9uYW1lIjoiUmFodWwiLCJmYW1pbHlfbmFtZSI6Ikt1bWFyIiwiZW1haWwiOiJhYmNAYWJjLmNvbSJ9.BP1krGeTyTVPhKY8zHCmYowNwnGWl-lgMN7XKukUjRgxl6EEJwERwtbiruX0Qv6bZOAx5VMCntcWLPQgCTFzFXJSOnqf_YLKoUEUKrB3Lp8RHgAax0daPFVp2F86cAQ4x_ExADqepcujinvi1qP-wyWidEEVq6_j6aprzLl59y8cN6mWYL2yIZ2Vb6ZnjFHLOsOo-GZBsE1t31nG8rqPscKKhGVj7SLwexnPXCATmqYW1sc6LJgUUh2zcJrI-L8hgfyTyUHrgzi5gB7YE5mRi3M1vyHfmKNSvnca-UXo7O8OHzTzTmrDQcaTrk86xaSCcL4qm-7s9xHLeYGMAqwGEQ
> Content-Length: 81
>
} [81 bytes data]
* upload completely sent off: 81 out of 81 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 401 Unauthorized
< Connection: keep-alive
< X-XSS-Protection: 1; mode=block
< Strict-Transport-Security: max-age=31536000; includeSubDomains
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< 548{"error":"HTTP 401 Unauthorized"}
* Connection #0 to host localhost left intact


问:
Understanding "baseUrl" and "paths" in TypeScript with * glob
I have a monorepo created with yarn workspaces and the following folder structure:

```<code>├── foo                   (workspace @project/foo)
│   ├── package.json
│   └── src
│       └── index.ts
├── bar                   (workspace @project/bar)
│   ├── package.json
│   └── src
│       └── index.ts
├── package.json          (monorepo root)
└── tsconfig.json         (base tsconfig)
</code>```

And the following settings in tsconfig.json:

```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "paths": {
      "@project/foo/*": "./packages/foo/src/*",
      "@project/bar/*": "./packages/bar/src/*"
    },
    ...
  }
}
</code>```

In the @project/bar workspace, I want to import modules from @project/foo:

```<code>import foo from "@project/foo";
</code>```

But I'm getting the following error:

Cannot find module '@project/foo' or its corresponding type declarations.ts(2307)

If I remove the * symbols from both the keys and the values of the "paths" object, the code compiles. Why is that? How can I keep the * glob pattern and make non-relative imports to my local modules?

答:
roots should be defined separately because / blocks @project/foo from import, only @project/foo/ and @project/foo/something are allowed.

```<code>"@project/foo": "./packages/foo/src",
"@project/bar": "./packages/foo/bar",
"@project/foo/*": "./packages/foo/src/*",
"@project/bar/*": "./packages/bar/src/*"
</code>```

In case of monorepo you can't use /* because after compilation it won't be accessible in the same way as at runtime in monorepo.

The right way is to point to public_api of the projects

```<code>"@project/foo": "./packages/foo/src/public_api",
"@project/bar": "./packages/foo/bar/public_api",
</code>```

The same for subprojects:

```<code>"@project/foo/sub": "./packages/foo/src/sub/public_api",
</code>```

Body:
I have a monorepo created with yarn workspaces and the following folder structure:

├── foo                   (workspace @project/foo)
│   ├── package.json
│   └── src
│       └── index.ts
├── bar                   (workspace @project/bar)
│   ├── package.json
│   └── src
│       └── index.ts
├── package.json          (monorepo root)
└── tsconfig.json         (base tsconfig)

And the following settings in tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "paths": {
      "@project/foo/*": "./packages/foo/src/*",
      "@project/bar/*": "./packages/bar/src/*"
    },
    ...
  }
}

In the @project/bar workspace, I want to import modules from @project/foo:

import foo from "@project/foo";

But I'm getting the following error:

Cannot find module '@project/foo' or its corresponding type declarations.ts(2307)

If I remove the * symbols from both the keys and the values of the "paths" object, the code compiles. Why is that? How can I keep the * glob pattern and make non-relative imports to my local modules?

Body:
roots should be defined separately because / blocks @project/foo from import, only @project/foo/ and @project/foo/something are allowed.

"@project/foo": "./packages/foo/src",
"@project/bar": "./packages/foo/bar",
"@project/foo/*": "./packages/foo/src/*",
"@project/bar/*": "./packages/bar/src/*"

In case of monorepo you can't use /* because after compilation it won't be accessible in the same way as at runtime in monorepo.

The right way is to point to public_api of the projects

"@project/foo": "./packages/foo/src/public_api",
"@project/bar": "./packages/foo/bar/public_api",

The same for subprojects:

"@project/foo/sub": "./packages/foo/src/sub/public_api",


问:
JavaScript - Use addition on values of multiple dynamically created objects with same name in array
I have an array of objects that's created dynamically (in React, although I don't think it matters), and I'm attempting to use addition on values that have the same name.

for example:

```<code>[{ n1:"1", n2:"2", n3:"3"},
 { n1:"4", n2:"6", n3:"4"},
 { n1:"3", n2:"1", n3:"2"}]
</code>```

the result of which would then be:

```<code>[{ n1:"8", n2:"9", n3:"9"}]
</code>```

Spread Syntax and the .assign method seem like they'd accomplish this, but both examples have predefined arrays, not dynamically created ones.

If it would be easier to parse the data so each name could occupy a new array, that'd be fine too. ie [n1:"8"],[n2:"9"],[n3:"9"]

答:
Maybe a little bit terse, but using flatMap() and reduce():

const data = [
  {n1:"1", n2:"2", n3:"3"},
  {n1:"4", n2:"6", n3:"4"},
  {n1:"3", n2:"1", n3:"2"}
];

const result = data.flatMap(Object.entries)
                   .reduce((a, [k, v]) => (a[k] = (a[k] || 0) + +v, a), {});

console.log(result);```

Body:
I have an array of objects that's created dynamically (in React, although I don't think it matters), and I'm attempting to use addition on values that have the same name.

for example:

[{ n1:"1", n2:"2", n3:"3"},
 { n1:"4", n2:"6", n3:"4"},
 { n1:"3", n2:"1", n3:"2"}]

the result of which would then be:

[{ n1:"8", n2:"9", n3:"9"}]

Spread Syntax and the .assign method seem like they'd accomplish this, but both examples have predefined arrays, not dynamically created ones.

If it would be easier to parse the data so each name could occupy a new array, that'd be fine too. ie [n1:"8"],[n2:"9"],[n3:"9"]