问:
React not closing dialog box
Im using materialUI to click a menu item that then opens a dialog box(child component) however after the dialogbox opens it wont seem to close and wont update the data for noticeModal. There are not any errors being thrown and i belive it has to do with using useEffect to setNoticeModal(props.open) for the initial state. Ive tried removing the useEffect() and throwing props.open into the default useDate() for the noticeModal however upon doing that then my dialogbox wont open anymore at all. What am i over looking here?

holidaySettings.js

```<code>    ...
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const handleDialogOpen = (dataElement) => {
      setDialogData(dataElement);
      setDialogOpen(true);
      setOpen(false);
    }

    ...
    <ClickAwayListener onClickAway={handleClose}>
       <MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
          <MenuItem onClick={handleDialogOpen}>Add Holiday</MenuItem>
        </MenuList>
     </ClickAwayListener>

    ...

    <div className="card-body">
      <div className="row">
         <div className="text-left col-12">
            <Styles>
               <Table columns={columns} data={data} />
               <HolidayDialog open={dialogOpen} onClose={handleDialogClose} data={dialogData}/>
            </Styles>
         </div>
       </div>
     </div>
    ...
</code>```

holidayDialog.js

```<code>const HolidayDialog = (props) => {
    const [noticeModal, setNoticeModal] = useState(false);
    const [selectedDate, setSelectedDate] = useState(new Date());
    const [holidayData, setHolidayData] = useState(props.data);

    useEffect(() => {
        setNoticeModal(props.open)
    });

    const handleDateChange = (date) => {
        setSelectedDate(date);
    };

    const handleClose = () => {
        setNoticeModal(false);
        console.log(noticeModal);
    };

    const handleChange = (e) => {
        const { name, checked } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
      };

    const updateValues = (e) => {
        const { name, value } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: value }));
    }
    return (
        <Dialog
            open={noticeModal}
            TransitionComponent={Transition}
            keepMounted
            onClose={handleClose}
            aria-labelledby="notice-modal-slide-title"
            aria-describedby="notice-modal-slide-description"
        >
            <DialogTitle id="customized-dialog-title" onClose={handleClose}>
                {holidayData.HolidayName ? holidayData.HolidayName : 'Create New Holiday'}
            </DialogTitle>
            <DialogContent dividers>
                <form noValidate autoComplete="off">
                    <div className="row">
                        <div className="col">
                            <TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''}/>
                        </div>
                        <div className="col">
                            <TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || 'ALL'}/>
                        </div>
                    </div>
                    <div className="row mt-3">
                        <div className="col">
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDatePicker
                                disableToolbar
                                variant="inline"
                                format="MM/dd/yyyy"
                                margin="normal"
                                id="date-picker-inline"
                                label="Date picker inline"
                                value={selectedDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                            />
                        </MuiPickersUtilsProvider>
                        </div>
                        <div className="col">
                            <TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || 'Closed'}/>
                        </div>
                    </div>
                    <div className="row mt-3">
                        <div className="col d-flex flex-column">
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Web || false}
                                    value={holidayData.Web}
                                    onChange={handleChange}
                                    name="Web"
                                    color="primary"
                                />
                                }
                                label="Show on Web?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.CoOp || false}
                                    value={holidayData.CoOp}
                                    onChange={handleChange}
                                    name="CoOp"
                                    color="primary"
                                />
                                }
                                label="CoOp Holiday?"
                            />
                        </div>
                        <div className="col d-flex flex-column">
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Phone || false}
                                    value={holidayData.Phone}
                                    onChange={handleChange}
                                    name="Phone"
                                    color="primary"
                                />
                                }
                                label="Use in IVR?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Active || true}
                                    value={holidayData.Active}
                                    onChange={handleChange}
                                    disabled
                                    name="Active"
                                    color="primary"
                                />
                                }
                                label="Active"
                            />
                        </div>
                    </div>
                </form>
            </DialogContent>
            <DialogActions>
                <Button autoFocus onClick={handleClose} color="default">
                    Cancel
                </Button>
                <Button autoFocus onClick={handleClose} color="primary">
                    Create Holiday
                </Button>
            </DialogActions>
        </Dialog>
    )
}

export default HolidayDialog;
</code>```

答:
Could you try this?

I am assuming props.onClose is making dialogOpen to false on parent(holidaySettings)

```<code> const handleClose = () => {
       props.onClose()
    };
</code>```

If props.onClose is not making dialogOpen to false on parent(holidaySettings).You can add close attribute which sets dialogOpen to false.

```<code>     <HolidayDialog open={dialogOpen} close={()=>setDialogOpen(false);} onClose={handleDialogClose} data={dialogData}/>

      const handleClose = () => {
           props.close()
        };
</code>```

And passing props.open to Dialog

```<code><Dialog
  open={props.open}
/>
</code>```

Title: React not closing dialog box

Body:
Im using materialUI to click a menu item that then opens a dialog box(child component) however after the dialogbox opens it wont seem to close and wont update the data for noticeModal. There are not any errors being thrown and i belive it has to do with using useEffect to setNoticeModal(props.open) for the initial state. Ive tried removing the useEffect() and throwing props.open into the default useDate() for the noticeModal however upon doing that then my dialogbox wont open anymore at all. What am i over looking here?

holidaySettings.js

    ...
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const handleDialogOpen = (dataElement) => {
      setDialogData(dataElement);
      setDialogOpen(true);
      setOpen(false);
    }

    ...
    <ClickAwayListener onClickAway={handleClose}>
       <MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
          <MenuItem onClick={handleDialogOpen}>Add Holiday</MenuItem>
        </MenuList>
     </ClickAwayListener>

    ...

    ...

holidayDialog.js

const HolidayDialog = (props) => {
    const [noticeModal, setNoticeModal] = useState(false);
    const [selectedDate, setSelectedDate] = useState(new Date());
    const [holidayData, setHolidayData] = useState(props.data);

    useEffect(() => {
        setNoticeModal(props.open)
    });

    const handleDateChange = (date) => {
        setSelectedDate(date);
    };

    const handleClose = () => {
        setNoticeModal(false);
        console.log(noticeModal);
    };

    const handleChange = (e) => {
        const { name, checked } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
      };

    const updateValues = (e) => {
        const { name, value } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: value }));
    }
    return (
        <Dialog
            open={noticeModal}
            TransitionComponent={Transition}
            keepMounted
            onClose={handleClose}
            aria-labelledby="notice-modal-slide-title"
            aria-describedby="notice-modal-slide-description"
        >
            <DialogTitle id="customized-dialog-title" onClose={handleClose}>
                {holidayData.HolidayName ? holidayData.HolidayName : 'Create New Holiday'}
            </DialogTitle>
            <DialogContent dividers>
                <form noValidate autoComplete="off">

                            <TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''}/>

                            <TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || 'ALL'}/>

                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDatePicker
                                disableToolbar
                                variant="inline"
                                format="MM/dd/yyyy"
                                margin="normal"
                                id="date-picker-inline"
                                label="Date picker inline"
                                value={selectedDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                            />
                        </MuiPickersUtilsProvider>

                            <TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || 'Closed'}/>

                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Web || false}
                                    value={holidayData.Web}
                                    onChange={handleChange}
                                    name="Web"
                                    color="primary"
                                />
                                }
                                label="Show on Web?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.CoOp || false}
                                    value={holidayData.CoOp}
                                    onChange={handleChange}
                                    name="CoOp"
                                    color="primary"
                                />
                                }
                                label="CoOp Holiday?"
                            />

                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Phone || false}
                                    value={holidayData.Phone}
                                    onChange={handleChange}
                                    name="Phone"
                                    color="primary"
                                />
                                }
                                label="Use in IVR?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Active || true}
                                    value={holidayData.Active}
                                    onChange={handleChange}
                                    disabled
                                    name="Active"
                                    color="primary"
                                />
                                }
                                label="Active"
                            />

                </form>
            </DialogContent>
            <DialogActions>
                <Button autoFocus onClick={handleClose} color="default">
                    Cancel
                </Button>
                <Button autoFocus onClick={handleClose} color="primary">
                    Create Holiday
                </Button>
            </DialogActions>
        </Dialog>
    )
}

export default HolidayDialog;

Body:
Could you try this?

I am assuming props.onClose is making dialogOpen to false on parent(holidaySettings)

 const handleClose = () => {
       props.onClose()
    };

If props.onClose is not making dialogOpen to false on parent(holidaySettings).You can add close attribute which sets dialogOpen to false.

     <HolidayDialog open={dialogOpen} close={()=>setDialogOpen(false);} onClose={handleDialogClose} data={dialogData}/>

      const handleClose = () => {
           props.close()
        };

And passing props.open to Dialog

<Dialog
  open={props.open}
/>


来源: stackexchange

答:
I would pivot the data and use asfreq to sample the data, then stack:

```<code>(df.assign(group=df.groupby('Date').cumcount())
  .set_index(['Date','group'])['Name']
  .unstack()
  .asfreq('D').ffill()
  .unstack()
  .reset_index('group',drop=True)
  .reset_index(name='Name')
)
</code>```

Output:

```<code>          Date     Name
0   2002-07-31     Paul
1   2002-07-31     John
2   2002-07-31   Silvia
3   2002-07-31     Mike
4   2002-07-31    Cindy
..         ...      ...
305 2002-09-30  Francis
306 2002-09-30  Michael
307 2002-09-30  Charlie
308 2002-09-30      Joe
309 2002-09-30   Hilary

[310 rows x 2 columns]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Resampling Dataframe from Monthly to Daily

Body:
Here is my problem:

This is a sample of my DataFrame (it actually goes from 2002 to 2012)

df = pd.DataFrame(
    {'Date':["2002-07-31","2002-07-31","2002-07-31","2002-07-31","2002-07-31","2002-08-31","2002-08-31","2002-08-31","2002-08-31","2002-08-31",'2002-09-30','2002-09-30','2002-09-30','2002-09-30','2002-09-30'],
     'Name': ["Paul", "John", "Silvia", "Mike", "Cindy","Paul", "David", "Harry", "Mike", "Britney","Francis", "Michael", "Charlie", "Joe", "Hilary"]})

Which gives this

       Date     Name
0   2002-07-31  Paul
1   2002-07-31  John
2   2002-07-31  Silvia
3   2002-07-31  Mike
4   2002-07-31  Cindy
5   2002-08-31  Paul
6   2002-08-31  David
7   2002-08-31  Harry
8   2002-08-31  Mike
9   2002-08-31  Britney
10  2002-09-30  Francis
11  2002-09-30  Michael
12  2002-09-30  Charlie
13  2002-09-30  Joe
14  2002-09-30  Hilary

and I would like to resample the serie from Monthly to Daily DataFrame by keeping all the names fix from 2002-07-31 to 2002-08-30 and from 2002-08-31 to 2002-09-30 (the change only occurs at the end of each month so it looks like resampling with the ffill() method).

The result I am looking for is something like that :

   Date     Name
2002-07-31  Paul
2002-07-31  John
2002-07-31  Silvia
2002-07-31  Mike
2002-07-31  Cindy
2002-08-01  Paul
2002-08-01  John
2002-08-01  Silvia
2002-08-01  Mike
2002-08-01  Cindy
2002-08-02  Paul
2002-08-02  John
2002-08-02  Silvia
2002-08-02  Mike
2002-08-02  Cindy
2002-08-03  Paul
2002-08-03  John
2002-08-03  Silvia
2002-08-03  Mike
2002-08-03  Cindy
.....

2002-08-31  Paul
2002-08-31  David
2002-08-31  Harry
2002-08-31  Mike
2002-08-31  Britney
2002-09-01  Paul
2002-09-01  David
2002-09-01  Harry
2002-09-01  Mike
2002-09-01  Britney
....

2002-09-30  Francis
2002-09-30  Michael
2002-09-30  Charlie
2002-09-30  Joe
2002-09-30  Hilary

As you can see, the names only change at the end of each month.
The most difficult step for me is that I have a selection of 5 names, and I don't really know how to resample to a daily Dataframe and still having 5 names for each day.

I already looked at this link

Resampling Error : cannot reindex a non-unique index with a method or limit

But It is not really the same issue and I still don't find any solution to manage mine.
If you have any ideas, you are welcome!

Body:
I would pivot the data and use asfreq to sample the data, then stack:

(df.assign(group=df.groupby('Date').cumcount())
  .set_index(['Date','group'])['Name']
  .unstack()
  .asfreq('D').ffill()
  .unstack()
  .reset_index('group',drop=True)
  .reset_index(name='Name')
)

Output:

          Date     Name
0   2002-07-31     Paul
1   2002-07-31     John
2   2002-07-31   Silvia
3   2002-07-31     Mike
4   2002-07-31    Cindy
..         ...      ...
305 2002-09-30  Francis
306 2002-09-30  Michael
307 2002-09-30  Charlie
308 2002-09-30      Joe
309 2002-09-30   Hilary

[310 rows x 2 columns]


问:
How to get output of program, when running vscode lldb debugger, on the integrated terminal?
When I run the debug, the output from my program isn't displayed on the integrated terminal.
This actually used to work a few days ago. I haven't changed any config files and yet, perhaps due to an update, this has changed.

Note that there is no "console" option with lldb.

This also creates a major issue that I can't provide input to my running program.

This is what I see in the integrated terminal:

```<code>[1] + Done    "/usr/bin/lldb-mi" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-871ntlpp.93i" 1>"/tmp/Microsoft-MIEngine-Out-msz8v24g.agq"
</code>```

And that's it. The case is the same when using "externalConsole":true.

How do I keep whatever output is currently in the debug terminal inside it, but also see the normal program output and be able to give input in the integrated terminal?

Also, this behavior leads me to think, currently, what is even the point of having the integrated terminal? Nothing is happening there.

here are my config files:

```<code>"version": "0.2.0",
"configurations": [
    {
        "name": "clang++ build and debug active file",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": false,
        "MIMode": "lldb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ],
        "preLaunchTask": "clang++ build active file",
        "miDebuggerPath": "/usr/bin/lldb-mi"
    }
]
</code>```

```<code>"version": "2.0.0",
"tasks": [
    {
        "type": "shell",
        "label": "clang++ build active file",
        "command": "/usr/bin/clang++",
        "args": [
            "-g",
            "${file}",
            "-o",
            "${fileDirname}/${fileBasenameNoExtension}"
        ],
        "options": {
            "cwd": "/usr/bin"
        },
        "problemMatcher": [
            "$gcc"
        ],
        "group": "build"
    }
]
</code>```

答:
unfortunately

https://code.visualstudio.com/docs/cpp/launch-json-reference

macOS: When set to true, it will spawn an external console through lldb-mi. When set to false, the output can be seen in VS Code's debugConsole. Due to limitations within lldb-mi, integratedTerminal support is not available.

Body:
When I run the debug, the output from my program isn't displayed on the integrated terminal.
This actually used to work a few days ago. I haven't changed any config files and yet, perhaps due to an update, this has changed.

Note that there is no "console" option with lldb.

This also creates a major issue that I can't provide input to my running program.

This is what I see in the integrated terminal:

[1] + Done    "/usr/bin/lldb-mi" --interpreter=mi --tty=${DbgTerm} 0<"/tmp/Microsoft-MIEngine-In-871ntlpp.93i" 1>"/tmp/Microsoft-MIEngine-Out-msz8v24g.agq"

And that's it. The case is the same when using "externalConsole":true.

How do I keep whatever output is currently in the debug terminal inside it, but also see the normal program output and be able to give input in the integrated terminal?

Also, this behavior leads me to think, currently, what is even the point of having the integrated terminal? Nothing is happening there.

here are my config files:

"version": "0.2.0",
"configurations": [
    {
        "name": "clang++ build and debug active file",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": false,
        "MIMode": "lldb",
        "setupCommands": [
            {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
            }
        ],
        "preLaunchTask": "clang++ build active file",
        "miDebuggerPath": "/usr/bin/lldb-mi"
    }
]

"version": "2.0.0",
"tasks": [
    {
        "type": "shell",
        "label": "clang++ build active file",
        "command": "/usr/bin/clang++",
        "args": [
            "-g",
            "${file}",
            "-o",
            "${fileDirname}/${fileBasenameNoExtension}"
        ],
        "options": {
            "cwd": "/usr/bin"
        },
        "problemMatcher": [
            "$gcc"
        ],
        "group": "build"
    }
]


问:
Azure Data Explorer (ADX) vs Polybase vs Databricks

Question

Today I discovered another Azure service called Azure Data Explorer (ADX). Sorry for such comparison of services, I have good understanding of all except ADX. I feel like there is a big functionality overlay, so want to know the exact role of ADX in Azure infrastructure.

What is the use case when ADX is significantly better than Synapse/Databricks?

My understanding of ADX

AFAIK, ADX is a cluster (with per hour billing, like Databricks or Synapse, not like ADLA) that is handling database for you and is optimized for streaming ingestion and ad-hoc queries at scale. It also supports external tables, that has worse performance but cheaper (you pay for Blob/ADLS storage).

Details

I don't understand why do we need ADX if:

Azure Synapse has similar pricing model (cluster, per-hour), also it supports streaming ingestion and ad-hoc querying at scale. Azure Synapse support querying BlobStorage/ADLS through Polybase external tables.

Databricks is another service that is capable of doing it. Using Databricks Ingest and Delta Lake - you can ingest streaming data and consume them in both: streaming and batching way. Actually you can have interactive cluster that will handle ad-hoc queries for you.

Also if you want a real-time analytics - use Azure Stream Analytics. If you want Athena-like experience - use ADLA (still it doesn't support ADLS gen2).

答:
Azure Data Explorer is focused on high velocity, high volume high variance (the 3 Vs of big data). It provides super fast interactive queries over such data that is streaming in. It supports json and text natively, including full text search and indexing.

It is used in a broad set of scenarios associated with sensing activity and time series in a large set of verticals: IoT, API logs, transaction monitoring and ad hoc data exploration.

Microsoft is offering ADX as a service as it is the major service that Microsoft is using for its own telemetry and all the analytical solutions as a service that we offer in Security, operational monitoring, game analytics, product insights usage analytics, Iot, Connected vehicles is built on ADX. You can find a full list in our docs. For clarity, SQL, Synapse, CosmosDB is storing its telemetry in Azure Data explorer...

SQL DW (AKA Synapse SQL pool) is an excellent data warehouse and implements the modern data warehouse pattern. ETL->Curated data model-> Load and serve via analysis services or power BI.

ADX is for real time analytics, enabling applying schema on read (SOR) on data as fresh as seconds old.

Consider ADX as a fully managed platform when replacing SOLR/Lucine based variants used for logs, time series databases and more.

Try it out in large workloads and you will see it is dramatically cheaper than the alternatives and much more powerful and performant.

Reach out to me if you need help.


问:
SafariViewControllerDidFinish does not fire when swiping down to dismiss
I have a delegate on a SFSafariViewController that does clean up tasks in the safariViewControllerDidFinish event. In iOS 13+, the user is able to swipe down to dismiss, but this event is not fired in that case. I do not want to disable this gesture by enabling isModalInPresentation.

Is there a way to make the safariViewControllerDidFinish fire for this case, or how can I detect the user swiping down to dismiss the Safari view controller?

答:
You can know when the user dismisses the SFSafariViewController by swiping down by making yourself the presentation controller's delegate and overriding presentationControllerDidDismiss(_:). Check out the documentation on this topic.

Note: This method will not get called if you use dismiss(animated:) programmatically.


问:
What is the meaning of 'in the same block formatting context?'
In the CSS 2.1 specification;

"This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box. The 'clear' property does not consider floats inside the element itself or in other block formatting contexts."

As we know, the property float can eatablish a new block formatting context, that means there won't any element is in the same block formatting context with floating element except floating element's child.  Yes, right?

答:
If I may refer to the other question related to this ( for the images!) :
How does the CSS Block Formatting Context work?

in the first 2 images all the elements , left column, right column, h3, p and the 2 x floated boxes are all in the same Block formatting Context, the root element is responsible for positioning them all, so all floats are counted when clearance is invoked.

in the 3rd image "main content" or middle column is made into a new Block Formatting Context.. so only the left, middle and right columns are now in the "root" Block Formatting Context. Whereas the actual content of the middle column the h3, p and two purple floated boxes are now in a different one, though they're all in the same new one.

It's like you drew a boundary around the middle column and isolated it so floats within it can now ignore the floats outside it (if cleared), and also elements inside it can take 100% width without counting the space being used by the side column floats

and yes it different from block and inline elements.. the context is the rectangle in which all the elements appear, the elements in the context are either block or inline as normal, Block Level elements and Block boxes (and inline and anonymous..) are described under the Visual Formatting Model (not context)

ContentLicense: CC BY-SA 3.0


问:
Postgres: How to alter jsonb value type for each element in an array?
I have a jsonb column named items in Postgres 10.12 like this:

```<code>{
    "items": [
        {
            "itemQty": 2,
            "itemName": "snake"
        },
        {
            "itemQty": 1,
            "itemName": "x kodiyum"
        }
    ]
}
</code>```

Now I want to convert itemQty type to string for every array element so that the new values are like this:

```<code>{
    "items": [
        {
            "itemQty": "2",
            "itemName": "snake"
        },
        {
            "itemQty": "1",
            "itemName": "x kodiyum"
        }
    ]
}
</code>```

How do I do this? I have gone through the documentation for Postgres jsonb and couldn't figure out.

On the server-side, I am using Spring boot and Hibernate with com.vladmihalcea.hibernate.type.json (Hibernate Types 52) if it helps.

Thanks

答:
You could unnest the array, modify the elements, and then rebuild it. Assuming that the primary key of your table is id, that would be:

```<code>select jsonb_build_object(
    'items', jsonb_agg(
        jsonb_build_object(
            'itemQty',  (x.obj ->> 'itemQty')::text,
            'itemName', x.obj ->> 'Name'
        )
    )
    )new_items
from mytable t
cross join lateral jsonb_array_elements(t.items -> 'items') as x(obj)
group by id
</code>```

Note that the explicit cast to ::text is not really needed here, as ->> extract text values anyway: I kept it because it makes the intent clearer.

If you want an update statement:

```<code>update mytable t
set items = (
    select jsonb_build_object(
        'items', jsonb_agg(
            jsonb_build_object(
                'itemQty',  (x.obj ->> 'itemQty')::text,
                'itemName', x.obj ->> 'Name'
            )
        )
    )
    from jsonb_array_elements(t.items -> 'items') as x(obj)
)
</code>```

Demo on DB Fiddle

Body:
I have a jsonb column named items in Postgres 10.12 like this:

{
    "items": [
        {
            "itemQty": 2,
            "itemName": "snake"
        },
        {
            "itemQty": 1,
            "itemName": "x kodiyum"
        }
    ]
}

Now I want to convert itemQty type to string for every array element so that the new values are like this:

{
    "items": [
        {
            "itemQty": "2",
            "itemName": "snake"
        },
        {
            "itemQty": "1",
            "itemName": "x kodiyum"
        }
    ]
}

How do I do this? I have gone through the documentation for Postgres jsonb and couldn't figure out.

On the server-side, I am using Spring boot and Hibernate with com.vladmihalcea.hibernate.type.json (Hibernate Types 52) if it helps.

Thanks

Body:
You could unnest the array, modify the elements, and then rebuild it. Assuming that the primary key of your table is id, that would be:

select jsonb_build_object(
    'items', jsonb_agg(
        jsonb_build_object(
            'itemQty',  (x.obj ->> 'itemQty')::text,
            'itemName', x.obj ->> 'Name'
        )
    )
    )new_items
from mytable t
cross join lateral jsonb_array_elements(t.items -> 'items') as x(obj)
group by id

Note that the explicit cast to ::text is not really needed here, as ->> extract text values anyway: I kept it because it makes the intent clearer.

If you want an update statement:

update mytable t
set items = (
    select jsonb_build_object(
        'items', jsonb_agg(
            jsonb_build_object(
                'itemQty',  (x.obj ->> 'itemQty')::text,
                'itemName', x.obj ->> 'Name'
            )
        )
    )
    from jsonb_array_elements(t.items -> 'items') as x(obj)
)

Demo on DB Fiddle


问:
Cannot resize the image in HTML page using bootstrap carousel
Cannot resize the image in my webpage. images are displayed in full size. I am using Bootstrap 4 carousel component. But the images seem to be non-responsive.

.carousel-item {
    width: 100%;
    height: auto;
    object-fit: cover;
}

The corresponding carousel part is as follows:```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="carouselExampleInterval" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner">
            <div class="carousel-item active" data-interval="10000">
                <img src="{% static 'images/car4-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item" data-interval="2000">
                <img src="{% static 'images/car2-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
            <div class="carousel-item">
                <img src="{% static 'images/car3-carousel.jpg' %}" class="d-block w-100" alt="">
            </div>
        </div>

            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>

            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>

    </div></code>```

Please help.

答:
img {
  max-width: 100%;
  height: 50vh;
  object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>

<div id="carouselExampleInterval" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active" data-interval="10000">
      <img src="https://images.unsplash.com/photo-1590948616180-fbe9e1fa7eaf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" class="d-block w-100" alt="">
    </div>
    <div class="carousel-item" data-interval="2000">
      <img src="https://images.unsplash.com/photo-1590948616180-fbe9e1fa7eaf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" class="d-block w-100" alt="">
    </div>
    <div class="carousel-item">
      <img src="https://images.unsplash.com/photo-1590948616180-fbe9e1fa7eaf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" class="d-block w-100" alt="">
    </div>
  </div>

    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>

    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>

</div></code>```

Body:
Cannot resize the image in my webpage. images are displayed in full size. I am using Bootstrap 4 carousel component. But the images seem to be non-responsive.

.carousel-item {
    width: 100%;
    height: auto;
    object-fit: cover;
}

The corresponding carousel part is as follows:

            Previous

            Next

Please help.

Body:
img {
  max-width: 100%;
  height: 50vh;
  object-fit: cover;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
</script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
</script>

<div id="carouselExampleInterval" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active" data-interval="10000">
      <img src="https://images.unsplash.com/photo-1590948616180-fbe9e1fa7eaf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" class="d-block w-100" alt="">
    </div>
    <div class="carousel-item" data-interval="2000">
      <img src="https://images.unsplash.com/photo-1590948616180-fbe9e1fa7eaf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" class="d-block w-100" alt="">
    </div>
    <div class="carousel-item">
      <img src="https://images.unsplash.com/photo-1590948616180-fbe9e1fa7eaf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60" class="d-block w-100" alt="">
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleInterval" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleInterval" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>


问:
Set database from SINGLE USER mode to MULTI USER
I need help with setting a database that was restored in SINGLE_USER mode to MULTI_USER. Every time I run

```<code>ALTER DATABASE BARDABARD
SET MULTI_USER;
GO
</code>```

I get this error:

Changes to the state or options of database 'BARDABARD' cannot be made at this time.

The database is in single-user mode, and a user is currently connected to it.

It needs to be in non-SINGLE_USER mode to set it to another mode, but I can’t set the database in any another mode while it is SINGLE_USER mode.

答:
You couldn't do that becouse database in single mode. Above all right but you should know that: when you opened the sql management studio it doesn't know any user on the database but when you click the database it consider you the single user and your command not working.
Just do that: Close management studio and re open it. new query window without selecting any database write the command script.

```<code>USE [master];
GO
ALTER DATABASE [tuncayoto] SET MULTI_USER WITH NO_WAIT;
GO
</code>```

make f5 wolla everything ok !

Body:
I need help with setting a database that was restored in SINGLE_USER mode to MULTI_USER. Every time I run

ALTER DATABASE BARDABARD
SET MULTI_USER;
GO

I get this error:

Changes to the state or options of database 'BARDABARD' cannot be made at this time.

The database is in single-user mode, and a user is currently connected to it.

It needs to be in non-SINGLE_USER mode to set it to another mode, but I can’t set the database in any another mode while it is SINGLE_USER mode.

Body:
You couldn't do that becouse database in single mode. Above all right but you should know that: when you opened the sql management studio it doesn't know any user on the database but when you click the database it consider you the single user and your command not working.
Just do that: Close management studio and re open it. new query window without selecting any database write the command script.

USE [master];
GO
ALTER DATABASE [tuncayoto] SET MULTI_USER WITH NO_WAIT;
GO

make f5 wolla everything ok !


问:
AWS RDS performance is very very low
There are two databases, AWS RDS and Digitalocean $ 5 VPS.
I imported the same .sql file to both databases, the performance difference between them is almost 66000%

```<code>select count(special_cargo_id) from special_cargos;
</code>```

AWS RDS elapsed time = 35.681seconds

DO 5$ VPS on Mysql elapsed time = 0.086seconds

Details:

Table Lenght

1.85GB Rows ~260k

MySQL Version 8

Table Engine InnoDB

RDS OUTPUT

```<code>CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) DEFAULT '',
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) DEFAULT '',
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) DEFAULT '',
  `weight` varchar(5) DEFAULT '',
  `width` varchar(5) NOT NULL DEFAULT '',
  `desi` varchar(5) DEFAULT '',
  `length` varchar(255) DEFAULT '',
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL DEFAULT '0',
  `customer_city_name` varchar(55) DEFAULT '',
  `customer_zone_id` int(11) NOT NULL DEFAULT '0',
  `customer_zone_name` varchar(55) DEFAULT '',
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) DEFAULT '',
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) DEFAULT '',
  `product` text,
  `sendText` text,
  `returnText` text,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` tinyint(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`),
  KEY `index_special_cargos` (`special_cargo_id`)
) ENGINE=InnoDB AUTO_INCREMENT=497539 DEFAULT CHARSET=utf8

+-----------------------+----------+
|Variable_name          |Value     |
+-----------------------+----------+
|innodb_buffer_pool_size|1073741824|
+-----------------------+----------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|146973|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
</code>```

SIMPLE VPS ON MYSQL OUTPUT

```<code>CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) NOT NULL,
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) NOT NULL,
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) NOT NULL,
  `weight` varchar(5) NOT NULL,
  `width` varchar(5) NOT NULL,
  `desi` varchar(5) NOT NULL,
  `length` varchar(255) NOT NULL,
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL,
  `customer_city_name` varchar(55) NOT NULL,
  `customer_zone_id` int(11) NOT NULL,
  `customer_zone_name` varchar(55) NOT NULL,
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) NOT NULL,
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) NOT NULL,
  `product` text,
  `sendText` text NOT NULL,
  `returnText` text NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` int(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`)
) ENGINE=InnoDB AUTO_INCREMENT=497037 DEFAULT CHARSET=utf8

+-----------------------+---------+
|Variable_name          |Value    |
+-----------------------+---------+
|innodb_buffer_pool_size|134217728|
+-----------------------+---------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|133967|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
</code>```

答:
Can you provide the output of:

```<code>SHOW CREATE TABLE special_cargos;
SHOW GLOBAL VARIABLES LIKE 'innodb_buffer_pool_size';
EXPLAIN select count(special_cargo_id) from special_cargos;
</code>```

on both RDS and your non-RDS instance?

Assuming for a moment that special_cargo_id is the primary key, and it fits into RAM, and innodb_buffer_pool_size is configured reasonably (on a server with 2GB of RAM, 1GB is a reasonable amount, though RDS should come pre-configured to a sane value), it should be running similarly on both nodes.

Two possible explanations come to mind:

1) On RDS you don't have special_cargo_id defined as the PK.

2) RDS is for some reason choosing to not use the index (comparison of EXPLAIN output will confirm whether this is happening).

Edit:

Actually - are you sure your $5 VPS is using InnoDB? If you are getting an answer back in 0.08s, that sounds like it isn't actually scanning even the index. There is a good chance that on the VPS you are using MyISAM, which updates the number of rows in the table header after every write, specifically to make SELECT COUNT(*) FROM table_name; queries return instantaneously - like you have observed.

Edit 2:

Wow - so VPS is configured with only 128MB of innodb_buffer_pool_size and it is STILL going faster than RDS configured with 1GB of innodb_buffer_pool_size, and the execution plan on both is the same?

OK, try this:

```<code>select count(1) from special_cargos FORCE INDEX (PRIMARY);
</code>```

Title: AWS RDS performance is very very low

Body:
There are two databases, AWS RDS and Digitalocean $ 5 VPS.
I imported the same .sql file to both databases, the performance difference between them is almost 66000%

select count(special_cargo_id) from special_cargos;

AWS RDS elapsed time = 35.681seconds

DO 5$ VPS on Mysql elapsed time = 0.086seconds

Details:

Table Lenght

1.85GB Rows ~260k

MySQL Version 8

Table Engine InnoDB

RDS OUTPUT

CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) DEFAULT '',
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) DEFAULT '',
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) DEFAULT '',
  `weight` varchar(5) DEFAULT '',
  `width` varchar(5) NOT NULL DEFAULT '',
  `desi` varchar(5) DEFAULT '',
  `length` varchar(255) DEFAULT '',
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL DEFAULT '0',
  `customer_city_name` varchar(55) DEFAULT '',
  `customer_zone_id` int(11) NOT NULL DEFAULT '0',
  `customer_zone_name` varchar(55) DEFAULT '',
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) DEFAULT '',
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) DEFAULT '',
  `product` text,
  `sendText` text,
  `returnText` text,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` tinyint(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`),
  KEY `index_special_cargos` (`special_cargo_id`)
) ENGINE=InnoDB AUTO_INCREMENT=497539 DEFAULT CHARSET=utf8

+-----------------------+----------+
|Variable_name          |Value     |
+-----------------------+----------+
|innodb_buffer_pool_size|1073741824|
+-----------------------+----------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|146973|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+

SIMPLE VPS ON MYSQL OUTPUT

CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) NOT NULL,
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) NOT NULL,
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) NOT NULL,
  `weight` varchar(5) NOT NULL,
  `width` varchar(5) NOT NULL,
  `desi` varchar(5) NOT NULL,
  `length` varchar(255) NOT NULL,
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL,
  `customer_city_name` varchar(55) NOT NULL,
  `customer_zone_id` int(11) NOT NULL,
  `customer_zone_name` varchar(55) NOT NULL,
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) NOT NULL,
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) NOT NULL,
  `product` text,
  `sendText` text NOT NULL,
  `returnText` text NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` int(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`)
) ENGINE=InnoDB AUTO_INCREMENT=497037 DEFAULT CHARSET=utf8

+-----------------------+---------+
|Variable_name          |Value    |
+-----------------------+---------+
|innodb_buffer_pool_size|134217728|
+-----------------------+---------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|133967|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+

Body:
Can you provide the output of:

SHOW CREATE TABLE special_cargos;
SHOW GLOBAL VARIABLES LIKE 'innodb_buffer_pool_size';
EXPLAIN select count(special_cargo_id) from special_cargos;

on both RDS and your non-RDS instance?

Assuming for a moment that special_cargo_id is the primary key, and it fits into RAM, and innodb_buffer_pool_size is configured reasonably (on a server with 2GB of RAM, 1GB is a reasonable amount, though RDS should come pre-configured to a sane value), it should be running similarly on both nodes.

Two possible explanations come to mind:

1) On RDS you don't have special_cargo_id defined as the PK.

2) RDS is for some reason choosing to not use the index (comparison of EXPLAIN output will confirm whether this is happening).

Edit:

Actually - are you sure your $5 VPS is using InnoDB? If you are getting an answer back in 0.08s, that sounds like it isn't actually scanning even the index. There is a good chance that on the VPS you are using MyISAM, which updates the number of rows in the table header after every write, specifically to make SELECT COUNT(*) FROM table_name; queries return instantaneously - like you have observed.

Edit 2:

Wow - so VPS is configured with only 128MB of innodb_buffer_pool_size and it is STILL going faster than RDS configured with 1GB of innodb_buffer_pool_size, and the execution plan on both is the same?

OK, try this:

select count(1) from special_cargos FORCE INDEX (PRIMARY);


问:
How to split and concatenate a string
I have a filename in a string. I want to split the given string into 2 (1 is filename without extension, 2 is only extension) strings. Then add _dev to the end of first string and concatenate with 2nd one.

ex:

```<code>Dim name as string="abc.txt"
Dim finalName as string
</code>```

The finalName should be like this "abc_dev.txt"

Any suggestions please?

答:
Try the following:

```<code>Dim newName as String = oldName.Insert(oldName.LastIndexOf("."), "_dev")
</code>```

Refer to:

String.Insert Method

String.IndexOf Method (String)

String.LastIndexOf Method (String)

Title: How to split and concatenate a string

Body:
I have a filename in a string. I want to split the given string into 2 (1 is filename without extension, 2 is only extension) strings. Then add _dev to the end of first string and concatenate with 2nd one.

ex:

Dim name as string="abc.txt"
Dim finalName as string

The finalName should be like this "abc_dev.txt"

Any suggestions please?

Body:
Try the following:

Dim newName as String = oldName.Insert(oldName.LastIndexOf("."), "_dev")

Refer to:

String.Insert Method

String.IndexOf Method (String)

String.LastIndexOf Method (String)


问:
Operator Overloading as member function
Why is it giving the error.

```<code> class Complex{
    int real,imaginary;
    public:
    Complex():real(0),imaginary(0){};
    Complex(int real, int imaginary):real(real),imaginary(imaginary){};
    int getreal()const{return real;}

    int getimaginary()const{return imaginary;};
    Complex &operator=(const Complex& );
    Complex operator*(){
      return Complex(real,-imaginary);
    }
    Complex  operator+(const Complex &a, const Complex &d){

      return  Complex (d.getreal()+a.getreal(),a.getimaginary()+d.getimaginary());
    }

  };
</code>```

When trying to overload the assingment operator.
Eroor says: too many parameter

What operators can we overload as member function and what not

答:
When overriding operators that have left and right parameters, you should just pass the right parameter and declare it like this:

```<code>Complex operator+(const Complex &d){
    return Complex(d.getreal() + getreal(), getimaginary() + d.getimaginary());
}
</code>```

When doing that, when you call getreal() or directly access that variable without specifing the parameter, it will use the left parameter of the operator.

Some of the operators that cannot be overloaded are scope (::), ternary (:), sizeof, member access (.) and some others.

Title: Operator Overloading as member function

Body:
Why is it giving the error.

 class Complex{
    int real,imaginary;
    public:
    Complex():real(0),imaginary(0){};
    Complex(int real, int imaginary):real(real),imaginary(imaginary){};
    int getreal()const{return real;}

    int getimaginary()const{return imaginary;};
    Complex &operator=(const Complex& );
    Complex operator*(){
      return Complex(real,-imaginary);
    }
    Complex  operator+(const Complex &a, const Complex &d){

      return  Complex (d.getreal()+a.getreal(),a.getimaginary()+d.getimaginary());
    }

  };

When trying to overload the assingment operator.
Eroor says: too many parameter

What operators can we overload as member function and what not

Body:
When overriding operators that have left and right parameters, you should just pass the right parameter and declare it like this:

Complex operator+(const Complex &d){
    return Complex(d.getreal() + getreal(), getimaginary() + d.getimaginary());
}

When doing that, when you call getreal() or directly access that variable without specifing the parameter, it will use the left parameter of the operator.

Some of the operators that cannot be overloaded are scope (::), ternary (:), sizeof, member access (.) and some others.


问:
verifying signature of apache release files
In most of the places, it is mentioned that either "RSA Key ID" or "DSA Key ID" should be used for receiving the public keys. http://www.apache.org/info/verification.html

For one of the packages downloaded, jmeter, there is no "KEY ID", there is only "RSA Key". What does this indicate? Any idea how to verify signature using RSA Key ?

Below is a sample output:

```<code>gpg --verify apache-jmeter-5.3.zip.asc apache-jmeter-5.3\ \(1\).zip
gpg: Signature made Monday 11 May 2020 01:34:58 AM IST
gpg:                using RSA key C4923F9ABFB2F1A06F08E88BAC214CAA0612B399
gpg: Can't check signature: No public key
</code>```

答:
Download JMeter (as per 9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure you should always be using the latest version, current version is JMeter 5.3)

```<code>wget -q https://downloads.apache.org//jmeter/binaries/apache-jmeter-5.3.tgz
</code>```

Download the PGP key:

```<code>wget -q https://www.apache.org/dist/jmeter/binaries/apache-jmeter-5.3.tgz.asc
</code>```

Check the downloaded bundle against the key:

```<code>gpg --verify apache-jmeter-5.3.tgz.asc apache-jmeter-5.3.tgz
</code>```

if you're getting No public key message it means that this C4923F9ABFB2F1A06F08E88BAC214CAA0612B399 key is not known at your local machine, you need to import it from PGP servers, i.e. from https://sks-keyservers.net/

```<code>gpg --keyserver hkp://pool.sks-keyservers.net  --receive-keys C4923F9ABFB2F1A06F08E88BAC214CAA0612B399
</code>```

Once done you should be able to repeat step 3 successfully

Body:
In most of the places, it is mentioned that either "RSA Key ID" or "DSA Key ID" should be used for receiving the public keys. http://www.apache.org/info/verification.html

For one of the packages downloaded, jmeter, there is no "KEY ID", there is only "RSA Key". What does this indicate? Any idea how to verify signature using RSA Key ?

Below is a sample output:

gpg --verify apache-jmeter-5.3.zip.asc apache-jmeter-5.3\ \(1\).zip
gpg: Signature made Monday 11 May 2020 01:34:58 AM IST
gpg:                using RSA key C4923F9ABFB2F1A06F08E88BAC214CAA0612B399
gpg: Can't check signature: No public key

Body:
Download JMeter (as per 9 Easy Solutions for a JMeter Load Test “Out of Memory” Failure you should always be using the latest version, current version is JMeter 5.3)

wget -q https://downloads.apache.org//jmeter/binaries/apache-jmeter-5.3.tgz

Download the PGP key:

wget -q https://www.apache.org/dist/jmeter/binaries/apache-jmeter-5.3.tgz.asc

Check the downloaded bundle against the key:

gpg --verify apache-jmeter-5.3.tgz.asc apache-jmeter-5.3.tgz

if you're getting No public key message it means that this C4923F9ABFB2F1A06F08E88BAC214CAA0612B399 key is not known at your local machine, you need to import it from PGP servers, i.e. from https://sks-keyservers.net/

gpg --keyserver hkp://pool.sks-keyservers.net  --receive-keys C4923F9ABFB2F1A06F08E88BAC214CAA0612B399

Once done you should be able to repeat step 3 successfully


问:
How to parse multiple sql statements with Calcite
I want to know how to parse multiple statements in one string.

sqlparser.parseStmt() can only parse one statement.

For example, I have one string:

```<code>Create Table tbl1(id bigint); Select * from tbl1;
</code>```

How to split the string to two SQL statements.

I expect to get a list of SqlNode.

答: You can use parseStmtList(), a method of the class SqlParser (reference). It returns a SqlNodeList.

Body:
I want to know how to parse multiple statements in one string.

sqlparser.parseStmt() can only parse one statement.

For example, I have one string:

Create Table tbl1(id bigint); Select * from tbl1;

How to split the string to two SQL statements.

I expect to get a list of SqlNode.


问:
How to rename a header and add values (to this column) based on other header name?
I have multiple Pandas dataframes like this one (for different years):

df1=

```<code>        Unnamed: 0           b      c     Monthly Flow (2018)
1              nan   -0.041619  43.91               -0.041619
2              nan    0.011913  43.91               -0.041619
3              nan   -0.048801  43.91               -0.041619
4              nan    0.002857  43.91               -0.041619
5              nan    0.002204  43.91               -0.041619
6              nan   -0.007692  43.91               -0.041619
7              nan   -0.014992  43.91               -0.041619
8              nan   -0.035381  43.91               -0.041619
</code>```

And I would like to assign to the nan the year in the Monthly Flow (2018) column, thus achieving this output:

```<code>       Year           b      c     Monthly Flow (2018)
1      2018   -0.041619  43.91               -0.041619
2      2018    0.011913  43.91               -0.041619
3      2018   -0.048801  43.91               -0.041619
4      2018    0.002857  43.91               -0.041619
5      2018    0.002204  43.91               -0.041619
6      2018   -0.007692  43.91               -0.041619
7      2018   -0.014992  43.91               -0.041619
8      2018   -0.035381  43.91               -0.041619
</code>```

I know how to replace these nan by a specific year, one dataframe at a time.

But, since I have a lot of dataframes (and will have more in the future), I would like to know a way to do this automatically, for example by extracting the year value from column Monthly Flow (2018).

Body:
I have multiple Pandas dataframes like this one (for different years):

df1=

        Unnamed: 0           b      c     Monthly Flow (2018)
1              nan   -0.041619  43.91               -0.041619
2              nan    0.011913  43.91               -0.041619
3              nan   -0.048801  43.91               -0.041619
4              nan    0.002857  43.91               -0.041619
5              nan    0.002204  43.91               -0.041619
6              nan   -0.007692  43.91               -0.041619
7              nan   -0.014992  43.91               -0.041619
8              nan   -0.035381  43.91               -0.041619

And I would like to assign to the nan the year in the Monthly Flow (2018) column, thus achieving this output:

       Year           b      c     Monthly Flow (2018)
1      2018   -0.041619  43.91               -0.041619
2      2018    0.011913  43.91               -0.041619
3      2018   -0.048801  43.91               -0.041619
4      2018    0.002857  43.91               -0.041619
5      2018    0.002204  43.91               -0.041619
6      2018   -0.007692  43.91               -0.041619
7      2018   -0.014992  43.91               -0.041619
8      2018   -0.035381  43.91               -0.041619

I know how to replace these nan by a specific year, one dataframe at a time.

But, since I have a lot of dataframes (and will have more in the future), I would like to know a way to do this automatically, for example by extracting the year value from column Monthly Flow (2018).

Body:
Using re

import re
def find_year(column):
    year = column.name
    return int(re.search(r'\d{4}',year).group(0))

df = df.rename(columns={'Unnamed: 0' : 'Year'})
# change 3 to match the column location of your target column
df['Year'] = df['Year'].fillna(find_year(df.iloc[:,3]))

print(df)
     Year         b      c  Monthly Flow (2018)
0  2018.0 -0.041619  43.91            -0.041619
1  2018.0  0.011913  43.91            -0.041619
2  2018.0 -0.048801  43.91            -0.041619
3  2018.0  0.002857  43.91            -0.041619
4  2018.0  0.002204  43.91            -0.041619
5  2018.0 -0.007692  43.91            -0.041619
6  2018.0 -0.014992  43.91            -0.041619
7  2018.0 -0.035381  43.91            -0.041619


问:
Show loading message in bootbox while ajax process is running?
I have page in my application that displays status. The status is displayed in drop down menu with two options Active/Inactive. The user can change the status by simply clicking on the menu and choosing the option. For that process I use JQuery/Ajax onchange trigger to track status change. The code is working fine and saves the value in datatbase. The issue I'm experiencing is related to bootbox and displaying loading message. When user clicks on the menu and changes the status ajax will send the request. At that point dialog window will show on the user screen with the loading message. Once ajax request is complete loading dialog should hide and display message tot he user that status successfully saved. Here is the code example:

function alertBox(title, message, size) {
  title = title || "Alert";
  message = message || "Alert Box";
  size = size || "lg";

  bootbox.alert({
    size: size,
    title: title,
    message: message
  });
};

$('.status').on('change', function() {
  let $curr_fld = $(this),
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      message: '
 Loading...
',
      closeButton: false
    });

  $curr_fld.prop("disabled", true);
  /*** Start: This is a code for testing. ***/
  /*
  setTimeout(function() {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    alertBox('Alert Message', status_id);
  }, 3000);
  */
  /*** End: This is a code for testing. ***/

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    if (obj.status === 200) {
      alertBox('Alert Message', obj);
    } else {
      alertBox('Alert Message', obj);
    }
  }).fail(function(jqXHR, textStatus, errorThrown) {
    $curr_fld.prop("disabled", false);
    alertBox('Error', textStatus);
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.4.0/bootbox.min.js"></script>

<table class="table table-striped table-bordered" id="tbl_nofa">
  <thead>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="text-center"> South</td>
      <td class="text-center">
        <select class="custom-select status" name="status_1" id="status_1" data-id="1">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> North</td>
      <td class="text-center">
        <select class="custom-select status" name="status_2" id="status_2" data-id="2">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> East</td>
      <td class="text-center">
        <select class="custom-select status" name="status_3" id="status_3" data-id="3">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> West</td>
      <td class="text-center">
        <select class="custom-select status" name="status_4" id="status_4" data-id="4">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </tfoot>
</table></code>```

If you run code example above, you will see once the ajax request is complete loading dialog is still on the screen. I'm not sure why since I have .modal('hide') in place. If you comment out the block of code with setTimeout and comment out the ajax code you will see that loading dialog works just fine. If anyone knows how to solve this issue please let me know.

答:
As per Daniel Gimenez, the issue is that dialog.modal('close') get's called very soon a easy fix to this will be to use setTimeout() , this will allow you to keep those fancy animations also:

Replace all dialog.modal('hide') with

```<code>setTimeout(function(){
   dialog.modal('hide')
},200);
</code>```

Hence your complete code will be:

function alertBox(title, message, size) {
  title = title || "Alert";
  message = message || "Alert Box";
  size = size || "lg";

  bootbox.alert({
    size: size,
    title: title,
    message: message
  });
};

$('.status').on('change', function() {
  let $curr_fld = $(this),
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      message: '
 Loading...
',
      closeButton: false
    });

  $curr_fld.prop("disabled", true);
  /*** Start: This is a code for testing. ***/
  /*
  setTimeout(function() {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    alertBox('Alert Message', status_id);
  }, 3000);
  */
  /*** End: This is a code for testing. ***/

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    setTimeout(function(){
        dialog.modal('hide')
        $curr_fld.prop("disabled", false);
        if (obj.status === 200) {
          alertBox('Alert Message', obj);
        } else {
          alertBox('Alert Message', obj);
        }
    },200);

  }).fail(function(jqXHR, textStatus, errorThrown) {
    setTimeout(function(){
        dialog.modal('hide')
        $curr_fld.prop("disabled", false);
        alertBox('Error', textStatus);
    },200);

  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.4.0/bootbox.min.js"></script>

<table class="table table-striped table-bordered" id="tbl_nofa">
  <thead>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="text-center"> South</td>
      <td class="text-center">
        <select class="custom-select status" name="status_1" id="status_1" data-id="1">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> North</td>
      <td class="text-center">
        <select class="custom-select status" name="status_2" id="status_2" data-id="2">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> East</td>
      <td class="text-center">
        <select class="custom-select status" name="status_3" id="status_3" data-id="3">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> West</td>
      <td class="text-center">
        <select class="custom-select status" name="status_4" id="status_4" data-id="4">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </tfoot>
</table></code>```

Body:
I have page in my application that displays status. The status is displayed in drop down menu with two options Active/Inactive. The user can change the status by simply clicking on the menu and choosing the option. For that process I use JQuery/Ajax onchange trigger to track status change. The code is working fine and saves the value in datatbase. The issue I'm experiencing is related to bootbox and displaying loading message. When user clicks on the menu and changes the status ajax will send the request. At that point dialog window will show on the user screen with the loading message. Once ajax request is complete loading dialog should hide and display message tot he user that status successfully saved. Here is the code example:

function alertBox(title, message, size) {
  title = title || "Alert";
  message = message || "Alert Box";
  size = size || "lg";

  bootbox.alert({
    size: size,
    title: title,
    message: message
  });
};

$('.status').on('change', function() {
  let $curr_fld = $(this),
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      message: '
 Loading...
',
      closeButton: false
    });

  $curr_fld.prop("disabled", true);
  /*** Start: This is a code for testing. ***/
  /*
  setTimeout(function() {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    alertBox('Alert Message', status_id);
  }, 3000);
  */
  /*** End: This is a code for testing. ***/

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    if (obj.status === 200) {
      alertBox('Alert Message', obj);
    } else {
      alertBox('Alert Message', obj);
    }
  }).fail(function(jqXHR, textStatus, errorThrown) {
    $curr_fld.prop("disabled", false);
    alertBox('Error', textStatus);
  });

});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

      Section
      Status

       South

        <select class="custom-select status" name="status_1" id="status_1" data-id="1">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>

       North

        <select class="custom-select status" name="status_2" id="status_2" data-id="2">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>

       East

        <select class="custom-select status" name="status_3" id="status_3" data-id="3">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>

       West

        <select class="custom-select status" name="status_4" id="status_4" data-id="4">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>

      Section
      Status

If you run code example above, you will see once the ajax request is complete loading dialog is still on the screen. I'm not sure why since I have .modal('hide') in place. If you comment out the block of code with setTimeout and comment out the ajax code you will see that loading dialog works just fine. If anyone knows how to solve this issue please let me know.

Body:
As per Daniel Gimenez, the issue is that dialog.modal('close') get's called very soon a easy fix to this will be to use setTimeout() , this will allow you to keep those fancy animations also:

Replace all dialog.modal('hide') with

setTimeout(function(){
   dialog.modal('hide')
},200);

Hence your complete code will be:

function alertBox(title, message, size) {
  title = title || "Alert";
  message = message || "Alert Box";
  size = size || "lg";

  bootbox.alert({
    size: size,
    title: title,
    message: message
  });
};

$('.status').on('change', function() {
  let $curr_fld = $(this),
    status_id = $curr_fld.attr('data-id'),
    dialog = bootbox.dialog({
      message: '<p class="text-center mb-0"><i class="fa fa-spin fa-cog"></i> Loading...</p>',
      closeButton: false
    });

  $curr_fld.prop("disabled", true);
  /*** Start: This is a code for testing. ***/
  /*
  setTimeout(function() {
    dialog.modal('hide');
    $curr_fld.prop("disabled", false);
    alertBox('Alert Message', status_id);
  }, 3000);
  */
  /*** End: This is a code for testing. ***/

  $.ajax({
    type: 'POST',
    url: 'test.php?id=1',
    data: {
      'status_id': status_id
    },
    dataType: 'json'
  }).done(function(obj) {
    setTimeout(function(){
        dialog.modal('hide')
        $curr_fld.prop("disabled", false);
        if (obj.status === 200) {
          alertBox('Alert Message', obj);
        } else {
          alertBox('Alert Message', obj);
        }
    },200);

  }).fail(function(jqXHR, textStatus, errorThrown) {
    setTimeout(function(){
        dialog.modal('hide')
        $curr_fld.prop("disabled", false);
        alertBox('Error', textStatus);
    },200);

  });

});

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/5.4.0/bootbox.min.js"></script>

<table class="table table-striped table-bordered" id="tbl_nofa">
  <thead>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="text-center"> South</td>
      <td class="text-center">
        <select class="custom-select status" name="status_1" id="status_1" data-id="1">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> North</td>
      <td class="text-center">
        <select class="custom-select status" name="status_2" id="status_2" data-id="2">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> East</td>
      <td class="text-center">
        <select class="custom-select status" name="status_3" id="status_3" data-id="3">
          <option value="A" selected>Active</option>
          <option value="I">Inactive</option>
        </select>
      </td>
    </tr>
    <tr>
      <td class="text-center"> West</td>
      <td class="text-center">
        <select class="custom-select status" name="status_4" id="status_4" data-id="4">
          <option value="A">Active</option>
          <option value="I" selected>Inactive</option>
        </select>
      </td>
    </tr>
  </tbody>
  <tfoot>
    <tr class="bg-dark">
      <th class="text-center text-white">Section</th>
      <th class="text-center text-white">Status</th>
    </tr>
  </tfoot>
</table>


问:
Possible exeptions when uploading/downloading files to Google Cloud Storage
I am using .NET Google.Cloud.Storage.V1 library to upload and download files to and from Google Cloud Storage. I am interested in Exception handling. I know it is a bad practice to catch general Exception therefore I am trying to sort out what types of exceptions could I encounter. So far I have found these three:

1) HttpRequestException when something is wrong with connection

2) OperationCanceledException this might be thrown when connection is lost during started upload/download

3) GoogleApiException  when file does not exist in cloud, bucket is already existing, etc.

Is there anything else I should be aware of?

答:
Well, it's "bad practice" because you typically only want to catch exceptions when you can do something about them. If you don't know what types of exceptions are thrown, what can you do to handle them?

The typical practice is to catch uncaught exceptions as high up the call stack as possible where you can do something more graceful than shutting down the process. For web apps this may mean redirecting to an error page, for forms it may be showing a message box, etc.

So if you are only catching exceptions to do general logging or something basic, there's nothing wrong with catching Exception.

To answer the actual question, .NET doesn't have metadata to indicate what exceptions could be thrown like Java or other platforms do. You'd have to rely on the documentation, if any. Plus, it would be an implementation detail that would be subject to change without breaking compatibility.


问:
In common-lisp how can i override/change evaluation behaviour for a specific type of object?
In common-lisp, I want to implement a kind of reference system like this:

Suppose that I have:

(defclass reference () ((host) (port) (file)))

and also I have:

(defun fetch-remote-value (reference) ...) which fetches and deserializes a lisp object.

How could I intervene in the evaluation process so as whenever a reference object is being evaluated, the remote value gets fetched and re-evaluated again to produce the final result?

EDIT:

A more elaborate description of what I want to accomplish:

Using cl-store I serialize lisp objects and send them to a remote file(or db or anything) to be saved. Upon successful storage I keep the host,port and file in a reference object. I would like, whenever eval gets called on a reference object, to first retrieve the object, and then call eval on the retrieved value. Since a reference can be also serialized in other (parent) objects or aggregate types, I can get free recursive remote reference resolution by modyfing eval so i dont have to traverse and resolve the loaded object's child references myself.

EDIT:
Since objects always evaluate to themselves, my question is a bit wrongly posed. Essentially what I would like to do is:

I would like intercept the evaluation of symbols so that when their value is an object of type REFERENCE then instead of returning the object as the result of the symbol evaluation, to return the result of (fetch-remote-value object) ?

答:
In short: you cannot do this, except by rewriting the function eval and modifying your Lisp's compiler. The rules of evaluation are fixed Lisp standard.

Edit After reading the augmented question, I don't think, that you can achieve full transperency for your references here. In a scenario like

```<code>(defclass foo () (reference :accessor ref))
(ref some-foo)
</code>```

The result of the call to ref is simply a value; it will not be considered for evaluation regardless of its type.

Of course, you could define your accessors in a way, which does the resolution transparently:

```<code>(defmacro defresolver (name class slot)
    `(defmethod ,name ((inst ,class))
        (fetch-remote-reference (slot-value inst ',slot))))

(defresolver foo-reference foo reference)
</code>```

Edit You can (sort of) hook into the symbol resolution mechanism of Common Lisp using symbol macros:

```<code>(defmacro let-with-resolution (bindings &body body)
    `(symbol-macrolet ,(mapcar #'(lambda (form) (list (car form) `(fetch-aux ,(cadr form)))) bindings) ,@body))

(defmethod fetch-aux ((any t)) any)
(defmethod fetch-aux ((any reference)) (fetch-remote-reference any))
</code>```

However, now things become pretty arcane; and the variables are no longer variables, but magic symbols, which merely look like variables. For example, modifying the content of a variable "bound" by this macro is not possible. The best you can do with this approach is to provide a setf expansion for fetch-aux, which modifies the original place.

Body:
In short: you cannot do this, except by rewriting the function eval and modifying your Lisp's compiler. The rules of evaluation are fixed Lisp standard.

Edit After reading the augmented question, I don't think, that you can achieve full transperency for your references here. In a scenario like

(defclass foo () (reference :accessor ref))
(ref some-foo)

The result of the call to ref is simply a value; it will not be considered for evaluation regardless of its type.

Of course, you could define your accessors in a way, which does the resolution transparently:

(defmacro defresolver (name class slot)
    `(defmethod ,name ((inst ,class))
        (fetch-remote-reference (slot-value inst ',slot))))

(defresolver foo-reference foo reference)

Edit You can (sort of) hook into the symbol resolution mechanism of Common Lisp using symbol macros:

(defmacro let-with-resolution (bindings &body body)
    `(symbol-macrolet ,(mapcar #'(lambda (form) (list (car form) `(fetch-aux ,(cadr form)))) bindings) ,@body))

(defmethod fetch-aux ((any t)) any)
(defmethod fetch-aux ((any reference)) (fetch-remote-reference any))

However, now things become pretty arcane; and the variables are no longer variables, but magic symbols, which merely look like variables. For example, modifying the content of a variable "bound" by this macro is not possible. The best you can do with this approach is to provide a setf expansion for fetch-aux, which modifies the original place.


问:
Maintain an auto-cleanable list of threads in Python
I maintain a threads list, and I want to auto-remove threads from the list when they are finished.

I found this method:

```<code>import threading, time

def f(seconds, info):
    print('starting', seconds)
    time.sleep(seconds)
    print('finished', seconds)
    threads.remove(info['thread'])

def newaction(seconds):
    info = {}
    thread = threading.Thread(target=f, args=(seconds, info))
    info['thread'] = thread
    thread.start()
    threads.append(thread)

threads = []
newaction(1)
newaction(2)
for _ in range(10):
    time.sleep(0.3)
    print(threads)
</code>```

It works:

```<code>starting 1
starting 2
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
finished 1
[<Thread(Thread-2, started 712)>]
[<Thread(Thread-2, started 712)>]
[<Thread(Thread-2, started 712)>]
finished 2
[]
[]
[]
[]
</code>```

But the fact of having to pass a dict info is a bit a hack. I used it because obviously I can't pass thread in args...

```<code>thread = threading.Thread(target=f, args=(seconds, thread))
#                                                     ^ not created yet!
</code>```

...when the Thread object is not created yet!

Is there a more natural way in Python to maintain an auto-cleanable list of threads?

答:
You have the current_thread() function.

```<code>import threading, time

def f(seconds):
    print('starting', seconds)
    time.sleep(seconds)
    print('finished', seconds)
    threads.remove(threading.current_thread())

def newaction(seconds):
    thread = threading.Thread(target=f, args=(seconds,))
    thread.start()
    threads.append(thread)

threads = []
newaction(1)
newaction(2)
for _ in range(10):
    time.sleep(0.3)
    print(threads)
</code>```

Output:

```<code>starting 1
starting 2
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
finished 1
[<Thread(Thread-2, started 4388)>]
[<Thread(Thread-2, started 4388)>]
[<Thread(Thread-2, started 4388)>]
finished 2
[]
[]
[]
[]
</code>```

Body:
I maintain a threads list, and I want to auto-remove threads from the list when they are finished.

I found this method:

import threading, time

def f(seconds, info):
    print('starting', seconds)
    time.sleep(seconds)
    print('finished', seconds)
    threads.remove(info['thread'])

def newaction(seconds):
    info = {}
    thread = threading.Thread(target=f, args=(seconds, info))
    info['thread'] = thread
    thread.start()
    threads.append(thread)

threads = []
newaction(1)
newaction(2)
for _ in range(10):
    time.sleep(0.3)
    print(threads)

It works:

starting 1
starting 2
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
[<Thread(Thread-1, started 1612)>, <Thread(Thread-2, started 712)>]
finished 1
[<Thread(Thread-2, started 712)>]
[<Thread(Thread-2, started 712)>]
[<Thread(Thread-2, started 712)>]
finished 2
[]
[]
[]
[]

But the fact of having to pass a dict info is a bit a hack. I used it because obviously I can't pass thread in args...

thread = threading.Thread(target=f, args=(seconds, thread))
#                                                     ^ not created yet!

...when the Thread object is not created yet!

Is there a more natural way in Python to maintain an auto-cleanable list of threads?

Body:
You have the current_thread() function.

import threading, time

def f(seconds):
    print('starting', seconds)
    time.sleep(seconds)
    print('finished', seconds)
    threads.remove(threading.current_thread())

def newaction(seconds):
    thread = threading.Thread(target=f, args=(seconds,))
    thread.start()
    threads.append(thread)

threads = []
newaction(1)
newaction(2)
for _ in range(10):
    time.sleep(0.3)
    print(threads)

Output:

starting 1
starting 2
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
[<Thread(Thread-1, started 4588)>, <Thread(Thread-2, started 4388)>]
finished 1
[<Thread(Thread-2, started 4388)>]
[<Thread(Thread-2, started 4388)>]
[<Thread(Thread-2, started 4388)>]
finished 2
[]
[]
[]
[]


问:
Apache Helix run-helix-controller.sh command gives error
I have installed apache Helix 1.0.0 version. I am able to setup a cluster and add resources.
But when i try to start run-helix-controller.sh it gives below error.

Here is command  : ./run-helix-controller.sh --zkSvr localhost:2181 --cluster jbpm-cluster

ERROR
[2020-05-20 06:22:29,773] [INFO ] [main] [org.apache.helix.controller.HelixControllerMain:208] - Cluster manager started, zkServer: lpwaidqu02:2181, clusterName:jbpm-cluster, controllerName:null, mode:STANDALONE
Exception in thread "main" java.lang.NoSuchFieldError: Rebalancer
        at org.apache.helix.InstanceType.(InstanceType.java:39)
        at org.apache.helix.controller.HelixControllerMain.startHelixController(HelixControllerMain.java:156)
        at org.apache.helix.controller.HelixControllerMain.main(HelixControllerMain.java:212)

答:
Have you tried the steps in this guide?
http://helix.apache.org/0.9.7-docs/Quickstart.html

Seems like there are a few steps (like "add cluster") before ./run-helix-controller.sh command.