问:
Full Calendar 4.x for the Vaadin Framework 14+ not displaying in 24 hours format
enter image description here I have created a FullCalendar, it is displaying the time in AM/PM. When I am adding the enteries to the calendar, I format the LocalDateTime to 24 hours format but the Calendar displays it in AM/PM format.

How I can display the Calendar entries in 24 hours format?
 My Formatter is defined as:

```<code>public static final DateTimeFormatter TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER =
    DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", AppConstants.APP_LOCALE);

Entry entry = new Entry();
entry.setEditable(false);
entry.setTitle(game.getHomeClub() + " - " +game.getHomeTeam());

Instant now = Instant.now();

String t = LocalDateTime.of(game.getGameTime().toLocalDate(), game.getGameTime().toLocalTime())
.format(FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER);

entry.setStart(calendar.getTimezone().convertToUTC(LocalDateTime.parse(t, FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER)));

entry.setEnd(game.getGameTime().plus(2, ChronoUnit.HOURS));
</code>```

```<code>calendar = new MyFullCalendar();

calendar.setWeekNumbersVisible(true);
calendar.setNowIndicatorShown(false);
calendar.setNumberClickable(true);
calendar.changeView(CalendarViewImpl.AGENDA_WEEK);

calendar.setLocale(Locale.GERMANY);

private void createTimedEntry(FullCalendar calendar, String title, String start, int minutes, String color) {
    Entry entry = new Entry();
    setValues(calendar, entry, title, start, minutes, ChronoUnit.MINUTES, color);
    calendar.addEntry(entry);
}
</code>```

答:
I know, the question is a bit old, but this answer may help anyone who is still searchting for an answer :)

Regardless of any i18n settings, you may use initial options on the server side to modifiy the event time format.

JsonObject initialOptions = Json.createObject();
JsonObject eventTimeFormat = Json.createObject();
//{ hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }
eventTimeFormat.put("hour", "2-digit");
eventTimeFormat.put("minute", "2-digit");
eventTimeFormat.put("meridiem", false);
eventTimeFormat.put("hour12", false);
initialOptions.put("eventTimeFormat", eventTimeFormat);

FullCalendar calendar = FullCalendarBuilder.create()
        .withInitialOptions(defaultInitialOptions)
        // ...
        .build();

```

Any initial options you can use you may obtain from the native library docs: https://fullcalendar.io/docs/eventTimeFormat (and other pages)

Body:
enter image description here I have created a FullCalendar, it is displaying the time in AM/PM. When I am adding the enteries to the calendar, I format the LocalDateTime to 24 hours format but the Calendar displays it in AM/PM format.

How I can display the Calendar entries in 24 hours format?
 My Formatter is defined as:

public static final DateTimeFormatter TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER =
    DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss", AppConstants.APP_LOCALE);

Entry entry = new Entry();
entry.setEditable(false);
entry.setTitle(game.getHomeClub() + " - " +game.getHomeTeam());

Instant now = Instant.now();

String t = LocalDateTime.of(game.getGameTime().toLocalDate(), game.getGameTime().toLocalTime())
.format(FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER);

entry.setStart(calendar.getTimezone().convertToUTC(LocalDateTime.parse(t, FormattingUtils.TWENTY_FOUR_HOURS_DATE_TIME_FORMATTER)));

entry.setEnd(game.getGameTime().plus(2, ChronoUnit.HOURS));

calendar = new MyFullCalendar();

calendar.setWeekNumbersVisible(true);
calendar.setNowIndicatorShown(false);
calendar.setNumberClickable(true);
calendar.changeView(CalendarViewImpl.AGENDA_WEEK);

calendar.setLocale(Locale.GERMANY);

private void createTimedEntry(FullCalendar calendar, String title, String start, int minutes, String color) {
    Entry entry = new Entry();
    setValues(calendar, entry, title, start, minutes, ChronoUnit.MINUTES, color);
    calendar.addEntry(entry);
}

Body:
I know, the question is a bit old, but this answer may help anyone who is still searchting for an answer :)

Regardless of any i18n settings, you may use initial options on the server side to modifiy the event time format.

JsonObject initialOptions = Json.createObject();
JsonObject eventTimeFormat = Json.createObject();
//{ hour: 'numeric', minute: '2-digit', timeZoneName: 'short' }
eventTimeFormat.put("hour", "2-digit");
eventTimeFormat.put("minute", "2-digit");
eventTimeFormat.put("meridiem", false);
eventTimeFormat.put("hour12", false);
initialOptions.put("eventTimeFormat", eventTimeFormat);

FullCalendar calendar = FullCalendarBuilder.create()
        .withInitialOptions(defaultInitialOptions)
        // ...
        .build();

Any initial options you can use you may obtain from the native library docs: https://fullcalendar.io/docs/eventTimeFormat (and other pages)


来源: stackexchange

问:
PyQT5 - Change value of other cells when ComboBox is checked of Unchecked
I am using QTableView to display Pandas.Thank to the codes from StackOverFlow, I can do it.

I want to update the value of the cell on the right of a ComboBox when I check or uncheck some values of the ComboBox but I am new to PyQt5 and I don't know how to do.

When I select 'A' => the cell on the right will be 'A', then I check 'B' => the cell on the right will be 'A,B'. If I deselect A => the cell on the right will be 'B'

I have been searching but I cant not find a solution.
I really need your help.

This is what I am trying to do.

```<code>import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QComboBox, QVBoxLayout
from PyQt5.QtCore import Qt

dept_list = ['A','B','C','D','E','F','G','H']

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole or role == Qt.EditRole:
            # See below for the nested-list data structure.
            # .row() indexes into the outer list,
            # .column() indexes into the sub-list
            value = self._data.iloc[index.row(), index.column()]
            return str(value)

    def rowCount(self, index):
        # The length of the outer list.
        return self._data.shape[0]

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return self._data.shape[1]

    def flags(self, index):
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable

    def setData(self, index, value, role):
        if role == Qt.EditRole:
            self._data.iloc[index.row(), index.column()] = value
            self._data.iat[index.row(), self._data.shape[1]-1] = value
            self.dataChanged.emit(index, index)
            return True

    def headerData(self, section, orientation, role):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._data.columns[section])
            if orientation == Qt.Vertical:
                return str(self._data.index[section])

class CheckableComboBox(QComboBox):
    def __init__(self):
        super().__init__()
        self._changed = False
        self.view().pressed.connect(self.handleItemPressed)
        self.checked_item=[]

        for i in range(len(dept_list)):
            self.addItem(dept_list[i])
            self.setItemChecked(i, False)

    def setItemChecked(self, index, checked=False):
        item = self.model().item(index, self.modelColumn())  # QStandardItem object

        if checked:
            item.setCheckState(Qt.Checked)

        else:
            item.setCheckState(Qt.Unchecked)

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)

        if item.checkState() == Qt.Checked:
            item.setCheckState(Qt.Unchecked)
            if item.text() in self.checked_item:

                self.checked_item.remove(item.text())
            print(self.checked_item)

        else:
            item.setCheckState(Qt.Checked)
            self.checked_item.append(item.text())
            print(self.checked_item)
        self._changed = True

        self.check_items()

    def hidePopup(self):
        if not self._changed:
            super().hidePopup()
        self._changed = False

    def item_checked(self, index):

        # getting item at index
        item = self.model().item(index, 0)

        # return true if checked else false
        return item.checkState() == Qt.Checked

    def check_items(self):
        # blank list
        checkedItems = []

        # traversing the items
        for i in range(self.count()):

            # if item is checked add it to the list
            if self.item_checked(i):
                checkedItems.append(i)
                # checkedItems.append(self.model().item(i, 0).text())

        # call this method
        self.update_labels(checkedItems)

    # method to update the label
    def update_labels(self, item_list):

        n = ''
        count = 0

        # traversing the list
        for i in item_list:

            # if count value is 0 don't add comma
            if count == 0:
                n += ' % s' % i
            # else value is greater then 0
            # add comma
            else:
                n += ', % s' % i

            # increment count
            count += 1

        # loop
        for i in range(self.count()):

            # getting label
            text_label = self.model().item(i, 0).text()

            # default state
            if text_label.find('-') >= 0:
                text_label = text_label.split('-')[0]

            # shows the selected items
            item_new_text_label = text_label + ',' + n

           # setting text to combo box
            self.setItemText(i, item_new_text_label)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.table = QtWidgets.QTableView()
        self.combo_box_list=[]
        import pandas as pd
        df = pd.read_excel(r"E:\092021-12 2022 1001.xlsx", skiprows=7)

        # data = pd.DataFrame([[1, 9, 2], [1, 0, -1], [3, 5, 2], [3, 3, 2], [5, 8, 9],],
        #                     columns=["A", "B", "C"],
        #                     index=["Row 1", "Row 2", "Row 3", "Row 4", "Row 5"],)

        df['Allocation Selection'] = ''
        df['Allocation']=''

        self.model = TableModel(df)
        self.table.setModel(self.model)
        # combo = CheckableComboBox()
        # for i in range(len(dept_list)):
        #     combo.addItem(dept_list[i])
        #     combo.setItemChecked(i, False)

        for i in range(df.shape[0]):
            combo = CheckableComboBox()
            self.combo_box_list.append(combo)
            # pix = QPersistentModelIndex(index)
            # combo.currentIndexChanged[str].connect(lambda txt, pix=pix: self.tableView.model().setData(QModelIndex(pix), txt))
            self.table.setIndexWidget(self.model.index(i, df.shape[1] - 2), combo)
        self.setCentralWidget(self.table)
        self.setGeometry(600, 100, 400, 200)

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
</code>```

答:
If I understand correctly, you are using QTableView to display a pandas dataframe. In this case it should be quite simple. You need to use the signal that comes from the QComboBox when an item is selected - probably currentIndexChanged(). You need to connect this to a function that will identify which items in your QComboBox are checked, and from this build the string that will go into the dataframe at the right place. Once the dataframe is updated, your QTableView should update to display the new cell of the dataframe.  Without knowing more about your exact setup (the checkable combobox) I can't be more specific.

Edit: Here is a working solution. The first step was to make the combobox aware of what row it is in - in this case I just passed the row number as a variable to the combobox on creation. It's a quick and dirty way to do it - it would be better to find the row of the table that the widget is in dynamically. The second step is to define a custom signal which passes the row and the checked item list to a function in the main class which updates the dataframe at that row with the new checked list.

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QComboBox, QVBoxLayout
from PyQt5.QtCore import Qt, pyqtSignal

dept_list = ['A','B','C','D','E','F','G','H']

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole or role == Qt.EditRole:
            # See below for the nested-list data structure.
            # .row() indexes into the outer list,
            # .column() indexes into the sub-list
            value = self._data.iloc[index.row(), index.column()]
            return str(value)

    def rowCount(self, index):
        # The length of the outer list.
        return self._data.shape[0]

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return self._data.shape[1]

    def flags(self, index):
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable

    def setData(self, index, value, role):
        if role == Qt.EditRole:
            self._data.iloc[index.row(), index.column()] = value
            self._data.iat[index.row(), self._data.shape[1]-1] = value
            self.dataChanged.emit(index, index)
            return True

    def headerData(self, section, orientation, role):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._data.columns[section])
            if orientation == Qt.Vertical:
                return str(self._data.index[section])

class CheckableComboBox(QComboBox):

    check_changed = pyqtSignal(int, list)

    def __init__(self, row):
        super().__init__()
        self._changed = False
        self.view().pressed.connect(self.handleItemPressed)
        self.checked_item=[]

        self.row = row

        for i in range(len(dept_list)):
            self.addItem(dept_list[i])
            self.setItemChecked(i, False)

    def setItemChecked(self, index, checked=False):
        item = self.model().item(index, self.modelColumn())  # QStandardItem object

        if checked:
            item.setCheckState(Qt.Checked)

        else:
            item.setCheckState(Qt.Unchecked)

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)

        if item.checkState() == Qt.Checked:
            item.setCheckState(Qt.Unchecked)
            if item.text() in self.checked_item:

                self.checked_item.remove(item.text())
            print(self.checked_item)

        else:
            item.setCheckState(Qt.Checked)
            self.checked_item.append(item.text())
            print(self.checked_item)
        self._changed = True

        self.check_changed.emit(self.row, self.checked_item)

        self.check_items()

    def hidePopup(self):
        if not self._changed:
            super().hidePopup()
        self._changed = False

    def item_checked(self, index):

        # getting item at index
        item = self.model().item(index, 0)

        # return true if checked else false
        return item.checkState() == Qt.Checked

    def check_items(self):
        # blank list
        checkedItems = []

        # traversing the items
        for i in range(self.count()):

            # if item is checked add it to the list
            if self.item_checked(i):
                checkedItems.append(i)
                # checkedItems.append(self.model().item(i, 0).text())

        # call this method
        self.update_labels(checkedItems)

    # method to update the label
    def update_labels(self, item_list):

        n = ''
        count = 0

        # traversing the list
        for i in item_list:

            # if count value is 0 don't add comma
            if count == 0:
                n += ' % s' % i
            # else value is greater then 0
            # add comma
            else:
                n += ', % s' % i

            # increment count
            count += 1

        # loop
        for i in range(self.count()):

            # getting label
            text_label = self.model().item(i, 0).text()

            # default state
            if text_label.find('-') >= 0:
                text_label = text_label.split('-')[0]

            # shows the selected items
            item_new_text_label = text_label + ',' + n

           # setting text to combo box
            self.setItemText(i, item_new_text_label)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.table = QtWidgets.QTableView()
        self.combo_box_list=[]
        import pandas as pd
        #df = pd.read_excel(r"E:\092021-12 2022 1001.xlsx", skiprows=7)

        self.df = pd.DataFrame([[1, 9, 2], [1, 0, -1], [3, 5, 2], [3, 3, 2], [5, 8, 9],],
                            columns=["A", "B", "C"])

        self.df['Allocation Selection'] = ''
        self.df['Allocation']=''

        self.model = TableModel(self.df)
        self.table.setModel(self.model)

        for i in range(self.df.shape[0]):
            combo = CheckableComboBox(i)
            combo.check_changed.connect(self.update_df)
            self.combo_box_list.append(combo)
            self.table.setIndexWidget(self.model.index(i, self.df.shape[1] - 2), combo)

        self.setCentralWidget(self.table)
        self.setGeometry(600, 100, 400, 200)

    def update_df(self, row, checked):
        print(row, checked)
        self.df.at[row,'Allocation'] = checked

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
```

ContentLicense: CC BY-SA 4.0

Body:
I am using QTableView to display Pandas.Thank to the codes from StackOverFlow, I can do it.

I want to update the value of the cell on the right of a ComboBox when I check or uncheck some values of the ComboBox but I am new to PyQt5 and I don't know how to do.

When I select 'A' => the cell on the right will be 'A', then I check 'B' => the cell on the right will be 'A,B'. If I deselect A => the cell on the right will be 'B'

I have been searching but I cant not find a solution.
I really need your help.

This is what I am trying to do.

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QComboBox, QVBoxLayout
from PyQt5.QtCore import Qt

dept_list = ['A','B','C','D','E','F','G','H']

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole or role == Qt.EditRole:
            # See below for the nested-list data structure.
            # .row() indexes into the outer list,
            # .column() indexes into the sub-list
            value = self._data.iloc[index.row(), index.column()]
            return str(value)

    def rowCount(self, index):
        # The length of the outer list.
        return self._data.shape[0]

    def columnCount(self, index):
        # The following takes the first sub-list, and returns
        # the length (only works if all rows are an equal length)
        return self._data.shape[1]

    def flags(self, index):
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable

    def setData(self, index, value, role):
        if role == Qt.EditRole:
            self._data.iloc[index.row(), index.column()] = value
            self._data.iat[index.row(), self._data.shape[1]-1] = value
            self.dataChanged.emit(index, index)
            return True

    def headerData(self, section, orientation, role):
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._data.columns[section])
            if orientation == Qt.Vertical:
                return str(self._data.index[section])

class CheckableComboBox(QComboBox):
    def __init__(self):
        super().__init__()
        self._changed = False
        self.view().pressed.connect(self.handleItemPressed)
        self.checked_item=[]

        for i in range(len(dept_list)):
            self.addItem(dept_list[i])
            self.setItemChecked(i, False)

    def setItemChecked(self, index, checked=False):
        item = self.model().item(index, self.modelColumn())  # QStandardItem object

        if checked:
            item.setCheckState(Qt.Checked)

        else:
            item.setCheckState(Qt.Unchecked)

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)

        if item.checkState() == Qt.Checked:
            item.setCheckState(Qt.Unchecked)
            if item.text() in self.checked_item:

                self.checked_item.remove(item.text())
            print(self.checked_item)

        else:
            item.setCheckState(Qt.Checked)
            self.checked_item.append(item.text())
            print(self.checked_item)
        self._changed = True

        self.check_items()

    def hidePopup(self):
        if not self._changed:
            super().hidePopup()
        self._changed = False

    def item_checked(self, index):

        # getting item at index
        item = self.model().item(index, 0)

        # return true if checked else false
        return item.checkState() == Qt.Checked

    def check_items(self):
        # blank list
        checkedItems = []

        # traversing the items
        for i in range(self.count()):

            # if item is checked add it to the list
            if self.item_checked(i):
                checkedItems.append(i)
                # checkedItems.append(self.model().item(i, 0).text())

        # call this method
        self.update_labels(checkedItems)

    # method to update the label
    def update_labels(self, item_list):

        n = ''
        count = 0

        # traversing the list
        for i in item_list:

            # if count value is 0 don't add comma
            if count == 0:
                n += ' % s' % i
            # else value is greater then 0
            # add comma
            else:
                n += ', % s' % i

            # increment count
            count += 1

        # loop
        for i in range(self.count()):

            # getting label
            text_label = self.model().item(i, 0).text()

            # default state
            if text_label.find('-') >= 0:
                text_label = text_label.split('-')[0]

            # shows the selected items
            item_new_text_label = text_label + ',' + n

           # setting text to combo box
            self.setItemText(i, item_new_text_label)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.table = QtWidgets.QTableView()
        self.combo_box_list=[]
        import pandas as pd
        df = pd.read_excel(r"E:\092021-12 2022 1001.xlsx", skiprows=7)

        # data = pd.DataFrame([[1, 9, 2], [1, 0, -1], [3, 5, 2], [3, 3, 2], [5, 8, 9],],
        #                     columns=["A", "B", "C"],
        #                     index=["Row 1", "Row 2", "Row 3", "Row 4", "Row 5"],)

        df['Allocation Selection'] = ''
        df['Allocation']=''

        self.model = TableModel(df)
        self.table.setModel(self.model)
        # combo = CheckableComboBox()
        # for i in range(len(dept_list)):
        #     combo.addItem(dept_list[i])
        #     combo.setItemChecked(i, False)

        for i in range(df.shape[0]):
            combo = CheckableComboBox()
            self.combo_box_list.append(combo)
            # pix = QPersistentModelIndex(index)
            # combo.currentIndexChanged[str].connect(lambda txt, pix=pix: self.tableView.model().setData(QModelIndex(pix), txt))
            self.table.setIndexWidget(self.model.index(i, df.shape[1] - 2), combo)
        self.setCentralWidget(self.table)
        self.setGeometry(600, 100, 400, 200)

app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()


问:
How to use Subquery which returned more than one result
My SQL query

```<code>UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)
</code>```

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks

答: UPDATE Task SET Done = 1 WHERE ID IN (SELECT ID FROM User WHERE UserName = @UserName)</p>

ContentLicense: CC BY-SA 3.0

Body:
My SQL query

UPDATE Task SET Done = 1 WHERE (ID = (SELECT ID FROM User WHERE UserName = @UserName)

I tried and got an error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression. The statement has been terminated.

Is there any possible way to do that (for example a for loop)? Thanks


问:
Teradata: UPDATE failed. 7547: Target row updated by multiple source rows
Table1 contains id, date, flag.
Table2 contains id, date_from, date_to + some other attributes

Attribute flag from Table1 has to be updated with the following logic:

```<code>UPDATE t1 from Table1 t1, Table2 t2
SET flag = 1
WHERE t1.id = t2.id and t1.date between t2.date_from and t2.date_to
</code>```

The result is error 7547: Target row updated by multiple source rows.
Obviously, the problem is that Table2 contains intersecting intervals.
How to rewrite query to update the flag in this case?

答: Usually it's when the Update identifies multiple sources (in your example from t2) in the target (t1). Try to make t2.id unique.</p>

Body:
Table1 contains id, date, flag.
Table2 contains id, date_from, date_to + some other attributes

Attribute flag from Table1 has to be updated with the following logic:

UPDATE t1 from Table1 t1, Table2 t2
SET flag = 1
WHERE t1.id = t2.id and t1.date between t2.date_from and t2.date_to

The result is error 7547: Target row updated by multiple source rows.
Obviously, the problem is that Table2 contains intersecting intervals.
How to rewrite query to update the flag in this case?


问:
errorTypeError: Cannot read properties of undefined (reading 'map')
I'm trying to use Strapi Headless CMS to create blog posts. I managed to fetch the JSON data but I'm unable to display it as HTML using the map() function. I want to display this data into the HTML but I keep getting this error. I already tried with a for loop and foreach() but I keep getting the same error like this or errorTypeError: Cannot read properties of undefined (reading 'data'). Here's my code so far:

```<code> const blogPosts = "http://localhost:1337/api/blogposts";

fetch(blogPosts)
.then((response) => {
  return response.json();
})
.then((data) => console.log(data.data[0].attributes))

.then((data) => {
  let posts = data;

  posts.map(function (post) {
    let body = document.createElement("div");

    body.innerHTML = `${post.data.data[0].attributes.body}`;
    li.appendChild(body);
  });
})

.catch(function (err) {
  console.log("error" + err);
});
</code>```

The JSON file looks like this:

```<code>{data: Array(1)
     data: Array(1)
       0:
         attributes:
           body: "text"
           createdAt: "2022-02-11T10:29:48.930Z"
           publishedAt: "2022-02-11T10:29:58.780Z"
           updatedAt: "2022-02-11T10:29:58.790Z"
</code>```

答:
TypeError: Cannot read properties of undefined (reading 'data')

As error says, It is not able to read the data property as you are having only one data object in the response.

Valid JSON :

```<code>{
    "data": [{
        "attributes": {
            "body": "text",
            "createdAt": "2022-02-11T10:29:48.930Z",
            "publishedAt": "2022-02-11T10:29:58.780Z",
            "updatedAt": "2022-02-11T10:29:58.790Z"
        }
    }]
}
</code>```

Hence, access it by calling data[0].attributes.body instead of data.data[0].attributes.body.

Body:
I'm trying to use Strapi Headless CMS to create blog posts. I managed to fetch the JSON data but I'm unable to display it as HTML using the map() function. I want to display this data into the HTML but I keep getting this error. I already tried with a for loop and foreach() but I keep getting the same error like this or errorTypeError: Cannot read properties of undefined (reading 'data'). Here's my code so far:

 const blogPosts = "http://localhost:1337/api/blogposts";

fetch(blogPosts)
.then((response) => {
  return response.json();
})
.then((data) => console.log(data.data[0].attributes))

.then((data) => {
  let posts = data;

  posts.map(function (post) {
    let body = document.createElement("div");

    body.innerHTML = `${post.data.data[0].attributes.body}`;
    li.appendChild(body);
  });
})

.catch(function (err) {
  console.log("error" + err);
});

The JSON file looks like this:

{data: Array(1)
     data: Array(1)
       0:
         attributes:
           body: "text"
           createdAt: "2022-02-11T10:29:48.930Z"
           publishedAt: "2022-02-11T10:29:58.780Z"
           updatedAt: "2022-02-11T10:29:58.790Z"

Body:
TypeError: Cannot read properties of undefined (reading 'data')

As error says, It is not able to read the data property as you are having only one data object in the response.

Valid JSON :

{
    "data": [{
        "attributes": {
            "body": "text",
            "createdAt": "2022-02-11T10:29:48.930Z",
            "publishedAt": "2022-02-11T10:29:58.780Z",
            "updatedAt": "2022-02-11T10:29:58.790Z"
        }
    }]
}

Hence, access it by calling data[0].attributes.body instead of data.data[0].attributes.body.


问:
Overriding the table name in Flask-Alchemy
I am creating a Flask application and accessing the MySQL database using Flask-Alchemy.

I have following Class to access a table:

```<code>class price_table(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    trans_id = db.Column(db.Integer)
    timestamp = db.Column(db.Integer)
    order_type = db.Column(db.String(25))
    price = db.Column(db.Numeric(15,8))
    quantity = db.Column(db.Numeric(25,8))
    def __repr__(self):
            return 'id'
</code>```

For the table 'price_table' this works brilliantly, but problem is I have a few tables with the same columns as 'price_table' from which I only know the name at runtime.

I want to reuse the class above so I thought I could change tablename to the name of the table I need to read, but that does not work, the program keeps reading the 'price-table'

How do I override the tablename at runtime?

答: You can overwrite price_table.table.name attribute, yet keep in mind that it will affect your price_table model so, unless you want to use it to create a new specialized version of this table in the db and you are not interacting with price_table model - I wouldn't recommend that.

Body:
I am creating a Flask application and accessing the MySQL database using Flask-Alchemy.

I have following Class to access a table:

class price_table(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    trans_id = db.Column(db.Integer)
    timestamp = db.Column(db.Integer)
    order_type = db.Column(db.String(25))
    price = db.Column(db.Numeric(15,8))
    quantity = db.Column(db.Numeric(25,8))
    def __repr__(self):
            return 'id'

For the table 'price_table' this works brilliantly, but problem is I have a few tables with the same columns as 'price_table' from which I only know the name at runtime.

I want to reuse the class above so I thought I could change tablename to the name of the table I need to read, but that does not work, the program keeps reading the 'price-table'

How do I override the tablename at runtime?


问:
odoo 8 change from models.Model to osv.osv
In my odoo 8 itu use two kind of class, models.Model and osv.osv and I need it to change form models.Model to osv.osv

```<code>class purchase_extend2(models.Model):
_inherit = 'purchase.order'

allowed_credit = fields.Float(string="Customer Debt", compute="_get_allowed_credit", )

@api.one
@api.depends('customer_id')
def _get_allowed_credit(self):
    invoice_pool = self.env['account.invoice']
    confirmed_so_objs = invoice_pool.search([('state', '=', 'open'), ('partner_id', '=', self.customer_id.id)])
    self.allowed_credit = sum([so.amount_total for so in confirmed_so_objs])
</code>```

how to change it into this class?

```<code>class purchase_extend2(osv.osv):
</code>```

Thank you

答:
You need to use a functional field

Example:

from openerp.osv import osv, fields

class PurchaseOrderExtend(osv.osv):
    _inherit = 'purchase.order'

    def _get_allowed_credit(self, cr, uid, ids, field_name, arg, context):
        res = {}
        invoice_pool = self.pool.get('account.invoice')
        for order in self.browse(cr, uid, ids, context=context):
            confirmed_so_objs = invoice_pool.search_read(cr, uid, [('state', '=', 'open'), ('partner_id', '=', order.partner_id.id)], ['amount_total'])
            res[order.id] = {'allowed_credit': sum(so['amount_total'] for so in confirmed_so_objs)}
        return res

    _columns = {
        'allowed_credit': fields.function(_get_allowed_credit, type="float", string="Customer Debt", multi='_get_allowed_credit')
    }
```
<p>To use exceptions, use the following import:</p>
```from openerp.exceptions import Warning
```

Body:
In my odoo 8 itu use two kind of class, models.Model and osv.osv and I need it to change form models.Model to osv.osv

class purchase_extend2(models.Model):
_inherit = 'purchase.order'

allowed_credit = fields.Float(string="Customer Debt", compute="_get_allowed_credit", )

@api.one
@api.depends('customer_id')
def _get_allowed_credit(self):
    invoice_pool = self.env['account.invoice']
    confirmed_so_objs = invoice_pool.search([('state', '=', 'open'), ('partner_id', '=', self.customer_id.id)])
    self.allowed_credit = sum([so.amount_total for so in confirmed_so_objs])

how to change it into this class?

class purchase_extend2(osv.osv):

Thank you

Body:
You need to use a functional field

Example:

from openerp.osv import osv, fields

class PurchaseOrderExtend(osv.osv):
    _inherit = 'purchase.order'

    def _get_allowed_credit(self, cr, uid, ids, field_name, arg, context):
        res = {}
        invoice_pool = self.pool.get('account.invoice')
        for order in self.browse(cr, uid, ids, context=context):
            confirmed_so_objs = invoice_pool.search_read(cr, uid, [('state', '=', 'open'), ('partner_id', '=', order.partner_id.id)], ['amount_total'])
            res[order.id] = {'allowed_credit': sum(so['amount_total'] for so in confirmed_so_objs)}
        return res

    _columns = {
        'allowed_credit': fields.function(_get_allowed_credit, type="float", string="Customer Debt", multi='_get_allowed_credit')
    }

To use exceptions, use the following import:

from openerp.exceptions import Warning


问:
Using ingress in multi namespace cluster AKS
I have a cluster, I created namespaces for different teams. Then, I tried to apply an ingress to one namespace with this command kubectl apply -f ing2_dev_plat.yaml -n namespace_name.

After, this error was thrown. How can I properly configure the work of ingress controller in several namespaces?

Nginx ingress contoller service is in default namespace.

```<code>Error from server (BadRequest): error when creating "ing2_dev_plat.yaml": admission webhook "validate.nginx.ingress.kubernetes.io" denied the request:
-------------------------------------------------------------------------------
Error: exit status 1
2022/02/11 09:17:49 [warn] 3250#3250: the "http2_max_field_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:143
nginx: [warn] the "http2_max_field_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:143
2022/02/11 09:17:49 [warn] 3250#3250: the "http2_max_header_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:144
nginx: [warn] the "http2_max_header_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:144
2022/02/11 09:17:49 [warn] 3250#3250: the "http2_max_requests" directive is obsolete, use the "keepalive_requests" directive instead in /tmp/nginx-cfg1414424955:145
nginx: [warn] the "http2_max_requests" directive is obsolete, use the "keepalive_requests" directive instead in /tmp/nginx-cfg1414424955:145
2022/02/11 09:17:49 [emerg] 3250#3250: duplicate location "/" in /tmp/nginx-cfg1414424955:1045
nginx: [emerg] duplicate location "/" in /tmp/nginx-cfg1414424955:1045
nginx: configuration file /tmp/nginx-cfg1414424955 test failed
</code>```

答:
As I said in my comment under the question:

nginx: [emerg] duplicate location "/" in /tmp/nginx-cfg1414424955:1045
```
<p>may indicate you have the same location defined twice.</p>
<p>If you have any other Ingress resources with <code>path: /</code>, you have to edit those accordingly.</p>
<p>You can get all Ingress resources with their paths with</p>
<pre class="lang-text prettyprint-override"><code>kubectl get ingress -A -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.rules[*].http.paths[*].path}{"\n"}{end}'
</code>```

Body:
I have a cluster, I created namespaces for different teams. Then, I tried to apply an ingress to one namespace with this command kubectl apply -f ing2_dev_plat.yaml -n namespace_name.

After, this error was thrown. How can I properly configure the work of ingress controller in several namespaces?

Nginx ingress contoller service is in default namespace.

Error from server (BadRequest): error when creating "ing2_dev_plat.yaml": admission webhook "validate.nginx.ingress.kubernetes.io" denied the request:
-------------------------------------------------------------------------------
Error: exit status 1
2022/02/11 09:17:49 [warn] 3250#3250: the "http2_max_field_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:143
nginx: [warn] the "http2_max_field_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:143
2022/02/11 09:17:49 [warn] 3250#3250: the "http2_max_header_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:144
nginx: [warn] the "http2_max_header_size" directive is obsolete, use the "large_client_header_buffers" directive instead in /tmp/nginx-cfg1414424955:144
2022/02/11 09:17:49 [warn] 3250#3250: the "http2_max_requests" directive is obsolete, use the "keepalive_requests" directive instead in /tmp/nginx-cfg1414424955:145
nginx: [warn] the "http2_max_requests" directive is obsolete, use the "keepalive_requests" directive instead in /tmp/nginx-cfg1414424955:145
2022/02/11 09:17:49 [emerg] 3250#3250: duplicate location "/" in /tmp/nginx-cfg1414424955:1045
nginx: [emerg] duplicate location "/" in /tmp/nginx-cfg1414424955:1045
nginx: configuration file /tmp/nginx-cfg1414424955 test failed

Body:
As I said in my comment under the question:

nginx: [emerg] duplicate location "/" in /tmp/nginx-cfg1414424955:1045

may indicate you have the same location defined twice.

If you have any other Ingress resources with path: /, you have to edit those accordingly.

You can get all Ingress resources with their paths with

kubectl get ingress -A -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.rules[*].http.paths[*].path}{"\n"}{end}'


问:
Error "virtualenv : command not found" but install location is in PYTHONPATH
This has been driving me crazy for the past 2 days.
I installed virtualenv on my Macbook using pip install virtualenv.
But when I try to create a new virtualenv using virtualenv venv, I get the error saying "virtualenv : command not found".

I used pip show virtualenv and the location of the installation is "Location: /usr/local/lib/python2.7/site-packages" but I can't figure out where the executable is. I tried dozens other similar looking posts but those solutions do not work for me.

Any ideas what might be going wrong here?

答:
I use asdf and had to do a reshim after installing virtualenv. asdf reshim

Fixed due to this response


问:
What is practical use of IDEA MPS and Eclipse Xtext
Both of those frameworks deal with meta-model:

XText (Eclipse)

MPS (JetBrain)

Do you have example of practical applications based on meta-model transformation with those tools?

答:
I think the main usage of XText is firstly to create a DSL from the grammer you defined and an eclipse workbench auto-generated for you. Secondly, it can transform the scrpit written in your DSL into java. The built-in expressions from XText2 is a plus.
The framework gives you a free IDE to support your writing DSL you created. And the DSL is the ulimate product to provide. It can be used to abstract the rules and logics from the real world. For example, in our project, the product config rule. Only specialist knows them, so they write some in the DSL you create.</p>

ContentLicense: CC BY-SA 2.5


问:
OMNeT++ & Veins steady state vehicle density
I want to keep a constant number of cars in my (long) simulation  (OMNeT+Veins). I do not care about mobility that much so i could probably use the Veins in-built function *.manager.numVehicles = 100. The thing is that if i do not specify any(enough) vehicle flows (from SUMO) my simulation terminates instantly (because of no events). So i create some flows (that exit the simulation sooner) and Veins fills up for the cars as they dissappear.

Is there a more elegant way to do this? I'd prefer to just use the numVehicles function since it's easier and the cars move minimally so they remain in the simulation for long.

I need steady-state vehicular density (number of vehicles fixed - even if old ones leave and new ones enter to replace them at the same instant).

Thanks,
Andreas

答: https://stackoverflow.com/a/71071341/7215379 has a solution. It actually is meant to keep the number of vehicles in simulation constant. You can look into the possibility of reusing it.</p>


问:
Constant width in bokeh graph with datetime axis
I set up a stacked bar graph in bokeh, each bar indicating one month:

The respective code bit looks as follows:

p.vbar_stack(
        categories,
        x="zeit",
        width=2629800000 * 0.9,
        color=Category20c[len(categories)],
        source=plot_data,
    )
```

The width is specified in milliseconds, corresponding to the average length of a month. I multiply this by 0.9 to create a gap between bars. The problem is that due to actual differences in month lengths, the gaps between bars differ. This is most striking between February and March (e.g. the third and fourth bar from the left in the picture).

How can I make bar widths (and gaps) robust to lenghts of months?

答:
If you are happy to have variable width bars you can use a timedelta for the width. We have to create one for each month. This deals with the Feb/March issue. I've used line_width for the separation between the bars.

```<code>df['days'] = df.index.to_series().apply(lambda x: datetime.timedelta(days=x.days_in_month))

plot_data = ColumnDataSource(df)

p.vbar_stack(
    categories,
    x="zeit",
    width='days',
    line_width=1,
    line_color='white',
    color=Category20c[len(categories)],
    source=plot_data,
)
</code>```

Body:
I set up a stacked bar graph in bokeh, each bar indicating one month:

The respective code bit looks as follows:

p.vbar_stack(
        categories,
        x="zeit",
        width=2629800000 * 0.9,
        color=Category20c[len(categories)],
        source=plot_data,
    )

The width is specified in milliseconds, corresponding to the average length of a month. I multiply this by 0.9 to create a gap between bars. The problem is that due to actual differences in month lengths, the gaps between bars differ. This is most striking between February and March (e.g. the third and fourth bar from the left in the picture).

How can I make bar widths (and gaps) robust to lenghts of months?

Body:
If you are happy to have variable width bars you can use a timedelta for the width. We have to create one for each month. This deals with the Feb/March issue. I've used line_width for the separation between the bars.

df['days'] = df.index.to_series().apply(lambda x: datetime.timedelta(days=x.days_in_month))

plot_data = ColumnDataSource(df)

p.vbar_stack(
    categories,
    x="zeit",
    width='days',
    line_width=1,
    line_color='white',
    color=Category20c[len(categories)],
    source=plot_data,
)


问:
Detecting Green Colour from Image - CV2 Python
I am trying to detect green colour from images, for that I using cv2, by defining upper and lower limit of green colour as [40, 0, 0] and [90, 255, 255], this works well,

but, when I tested this image, I got detected the white region also, the output is mask image, the expected mask output is only black colour

the code is

```<code>frame = cv2.imread('img.jpg')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower = np.array([40, 0, 0])
upper = np.array([90, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
res = cv2.bitwise_and(frame,frame, mask= mask)
cv2.imshow('mask',mask)
</code>```

Why the upper and lower bound of green detects the white regions in the input image, and is there any other way to detect only green colour from the image

thanks

答:
The problem you are having is because the color [50,0,255] (which is in your range) is white, as seen here. (in this picture divide Hue by 2 and multiply Saturation and value with 2.55.)

If you only want green you should set your limits something like the following:
Lower [40,70,120]
Upper [90,255,255]
This way you make sure that white and black that have a hue between 40 and 90 don't get picked up in your program.

Body:
I am trying to detect green colour from images, for that I using cv2, by defining upper and lower limit of green colour as [40, 0, 0] and [90, 255, 255], this works well,

but, when I tested this image, I got detected the white region also, the output is mask image, the expected mask output is only black colour

the code is

frame = cv2.imread('img.jpg')
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower = np.array([40, 0, 0])
upper = np.array([90, 255, 255])
mask = cv2.inRange(hsv, lower, upper)
res = cv2.bitwise_and(frame,frame, mask= mask)
cv2.imshow('mask',mask)

Why the upper and lower bound of green detects the white regions in the input image, and is there any other way to detect only green colour from the image

thanks


问:
What is the help() syntax for finding the documentation of a method (eg. groupby) of a python module (eg. pandas)?
Stuff that I have tried on the Terminal and has not worked is as follows:

import pandas as pd

help(pd.groupby)

pd.groupby()??

help(groupby)

答:
try this</p>
```<code>help(pd.DataFrame.groupby)
</code>```

Body:
try this

help(pd.DataFrame.groupby)


问:
Updating table based on same table with a max value
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

```<code>update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1
</code>```

But doesn't work, only does the first regid group.

答:
Here's a solution (in MySQL 8.0+) using a CTE:

```<code>WITH numbered_table AS (
 SELECT id, ROW_NUMBER() OVER (PARTITION BY regid ORDER BY docid DESC) AS rownum
 FROM mytable
)
UPDATE mytable JOIN numbered_table USING (id)
SET archived = 1
WHERE rownum > 1
AND archived = 0;
</code>```

Second solution, if you use an older version of MySQL that doesn't support CTE syntax:

You don't really need to compute the max docid value. If you want to update all rows except for the row with the max docid value, then you can check if a row can be matched to any other row with a greater docid value.

```<code>UPDATE mytable AS t1
INNER JOIN mytable AS t2 ON t1.regid = t2.regid AND t1.docid < t2.docid
SET t1.archived = 1
WHERE t1.archived = 0;
</code>```

This will be true for all rows except the row with the max value. That row will be excluded automatically by the join.

Body:
Have a table data structure like below:

id
regid
docid
archived

1
1000
1
0

2
1000
2
0

3
1000
3
0

4
2000
1
0

5
2000
2
0

6
3000
1
0

7
3000
2
0

8
3000
3
0

9
3000
4
0

What I'm trying to do update the archived column to 1 where the docid is less than the max docid, by each regid group.

So I should end up with id's 3, 5 & 9 not being set to 1

Have tried:

update table t1
join (select max(docid) as maxdocid, regid from table) t2 on t1.docid < t2.maxdocid and t1.regid = t2.regid
set t1.archived = 1

But doesn't work, only does the first regid group.

Body:
Here's a solution (in MySQL 8.0+) using a CTE:

WITH numbered_table AS (
 SELECT id, ROW_NUMBER() OVER (PARTITION BY regid ORDER BY docid DESC) AS rownum
 FROM mytable
)
UPDATE mytable JOIN numbered_table USING (id)
SET archived = 1
WHERE rownum > 1
AND archived = 0;

Second solution, if you use an older version of MySQL that doesn't support CTE syntax:

You don't really need to compute the max docid value. If you want to update all rows except for the row with the max docid value, then you can check if a row can be matched to any other row with a greater docid value.

UPDATE mytable AS t1
INNER JOIN mytable AS t2 ON t1.regid = t2.regid AND t1.docid < t2.docid
SET t1.archived = 1
WHERE t1.archived = 0;

This will be true for all rows except the row with the max value. That row will be excluded automatically by the join.


问:
Extract table from the website using scrapy
I want to scrape text from table they will give me data but they will not given me data in these format shown in pic

```<code>from scrapy import Spider
from scrapy.http import Request

class AuthorSpider(Spider):
    name = 'book'
    start_urls = ['https://blogsrl.it/gb/4-no-food']
    def parse(self, response):
        books = response.xpath("//h3/a/@href").extract()
        for book in books:
            url = response.urljoin(book)
            yield Request(url, callback=self.parse_book)

    def parse_book(self, response):
        rows=response.xpath("//dl[@class='data-sheet']")
        details={}
        for row in rows:
            key = row.xpath('.//dt//text()').get(default='').strip()
            value=row.xpath('.//dd/text()').getall()
            value = ''.join(value).strip()
            details[key] = value
        yield details
</code>```

答:
I think the issue is with your XPATH. Your XPATH will not return you a list instead it will return the string since it's only targeting 1 element.

Perhaps try

```<code>rows=response.xpath("//dl[@class='data-sheet']//dt | //dl[@class='data-sheet']//dd ")
</code>```

Body:
I want to scrape text from table they will give me data but they will not given me data in these format shown in pic

from scrapy import Spider
from scrapy.http import Request

class AuthorSpider(Spider):
    name = 'book'
    start_urls = ['https://blogsrl.it/gb/4-no-food']
    def parse(self, response):
        books = response.xpath("//h3/a/@href").extract()
        for book in books:
            url = response.urljoin(book)
            yield Request(url, callback=self.parse_book)

    def parse_book(self, response):
        rows=response.xpath("//dl[@class='data-sheet']")
        details={}
        for row in rows:
            key = row.xpath('.//dt//text()').get(default='').strip()
            value=row.xpath('.//dd/text()').getall()
            value = ''.join(value).strip()
            details[key] = value
        yield details

Body:
I think the issue is with your XPATH. Your XPATH will not return you a list instead it will return the string since it's only targeting 1 element.

Perhaps try

rows=response.xpath("//dl[@class='data-sheet']//dt | //dl[@class='data-sheet']//dd ")


问:
Virtual paint() is not getting called while drawing Polyline
I am new to Qt, and wants to write code to change Qt's default selection behaviour. So I am trying to override virtual paint method. But paint method is not getting called.

Below code, just print the polyline and paint() tries to change its selection behaviour.

polyline.h

```<code>class Polyline : public QGraphicsPathItem
{
public:
    Polyline();
    virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
    {
        auto copied_option = *option;
        copied_option.state &= ~QStyle::State_Selected;
        auto selected = option->state & QStyle::State_Selected;
        QGraphicsPathItem::paint(painter, &copied_option, widget);
        if (selected)
        {
            painter->save();
            painter->setBrush(Qt::red);
            painter->setPen(QPen(option->palette.windowText(), 5, Qt::DotLine));
            painter->drawPath(shape());
            painter->restore();
        }
    }
    QGraphicsPathItem* drawPolyline();
};

</code>```

polyline.cpp

```<code>#include "polyline.h"

Polyline::Polyline()
{}

QGraphicsPathItem* Polyline::drawPolyline()
{
    QPolygonF polygon;
    polygon<< QPointF (150,450) << QPointF (350,450) <<QPointF (350,200) << QPointF (250,100)<<QPointF (150,200);

    QPainterPath pPath;

    pPath.addPolygon(polygon);
    QGraphicsPathItem* new_item = new QGraphicsPathItem(pPath);
    new_item->setPen(QPen(QColor("red"), 5));
    new_item->setPath(pPath);
    new_item->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
    return new_item;
}

</code>```

main.cpp

```<code>#include "polyline.h"
#include <QGraphicsScene>
#include <QGraphicsView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView view;
    QGraphicsScene scene;
    view.setScene(&scene);

    Polyline p;
    QGraphicsPathItem* poly = p.drawPolyline();
    scene.addItem(poly);
    view.show();
    return a.exec();
}

</code>```

Where am I wrong ?

答:
The problem is that you don't create any Polyline object and attach it to the window or a widget.

As such there's just no Polyline object to call the paint function on.

A simple solution it to have your drawPolyline function create a Polyline object instead of the QGraphicsPathItem object you create now:

```<code>QGraphicsPathItem* new_item = new Polyline(pPath);
</code>```

Remember to modify the Polyline constructor to take the path, and forward it to the base QGraphicsPathItem class.

Another improvement is to realize that drawPolyline doesn't really need to be a member function at all. And that it's rather badly named. I would suggest you define it as a source-file local function, renamed as createPolyline instead:

```<code>namespace
{
    QGraphicsPathItem* createPolyline()
    {
        // The body of your `drawPolyline` function
        // With the fix mentioned above
        // ...
    }
}
</code>```

Then use this function instead:

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView view;
    QGraphicsScene scene;
    view.setScene(&scene);

    scene.addItem(createPolyline());
    view.show();
    return a.exec();
}
</code>```

Body:
I am new to Qt, and wants to write code to change Qt's default selection behaviour. So I am trying to override virtual paint method. But paint method is not getting called.

Below code, just print the polyline and paint() tries to change its selection behaviour.

polyline.h

class Polyline : public QGraphicsPathItem
{
public:
    Polyline();
    virtual void paint (QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
    {
        auto copied_option = *option;
        copied_option.state &= ~QStyle::State_Selected;
        auto selected = option->state & QStyle::State_Selected;
        QGraphicsPathItem::paint(painter, &copied_option, widget);
        if (selected)
        {
            painter->save();
            painter->setBrush(Qt::red);
            painter->setPen(QPen(option->palette.windowText(), 5, Qt::DotLine));
            painter->drawPath(shape());
            painter->restore();
        }
    }
    QGraphicsPathItem* drawPolyline();
};

polyline.cpp

#include "polyline.h"

Polyline::Polyline()
{}

QGraphicsPathItem* Polyline::drawPolyline()
{
    QPolygonF polygon;
    polygon<< QPointF (150,450) << QPointF (350,450) <<QPointF (350,200) << QPointF (250,100)<<QPointF (150,200);

    QPainterPath pPath;

    pPath.addPolygon(polygon);
    QGraphicsPathItem* new_item = new QGraphicsPathItem(pPath);
    new_item->setPen(QPen(QColor("red"), 5));
    new_item->setPath(pPath);
    new_item->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
    return new_item;
}

main.cpp

#include "polyline.h"
#include <QGraphicsScene>
#include <QGraphicsView>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView view;
    QGraphicsScene scene;
    view.setScene(&scene);

    Polyline p;
    QGraphicsPathItem* poly = p.drawPolyline();
    scene.addItem(poly);
    view.show();
    return a.exec();
}

Where am I wrong ?

Body:
The problem is that you don't create any Polyline object and attach it to the window or a widget.

As such there's just no Polyline object to call the paint function on.

A simple solution it to have your drawPolyline function create a Polyline object instead of the QGraphicsPathItem object you create now:

QGraphicsPathItem* new_item = new Polyline(pPath);

Remember to modify the Polyline constructor to take the path, and forward it to the base QGraphicsPathItem class.

Another improvement is to realize that drawPolyline doesn't really need to be a member function at all. And that it's rather badly named. I would suggest you define it as a source-file local function, renamed as createPolyline instead:

namespace
{
    QGraphicsPathItem* createPolyline()
    {
        // The body of your `drawPolyline` function
        // With the fix mentioned above
        // ...
    }
}

Then use this function instead:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QGraphicsView view;
    QGraphicsScene scene;
    view.setScene(&scene);

    scene.addItem(createPolyline());
    view.show();
    return a.exec();
}


问:
different width for same column of different row
I have a table with several rows.

My 1st row has the full width of the table table.

The 2nd row has 4 columns with different sizes for each of them.

The 3rd row's first column's width is greater than the total width (1st coloumn's width+2nd coloumn's width +25) of the 2nd row.

Which attribute should I use for this type of design? colonspan is not working in this case

答: If you aren't going to have anything immediately adjacent to the shorter rows, you can make all the rows the same width (the width of the widest table row), and adjust the size of each row using colspan on the cells, and setting the cells beyond the end of the row to have no border (thus appearing not to exist). However, if you are going to have any content there, you will have to either use a different method than this or include that content in the "invisible" cells.</p>


问:
Android - How to play/ preview .MOV video format using video view in android?
What are the ways to play .mov video formats in android application? Unfortunately, android does not support .mov video formats.</p>

答: You could try to convert it(no re-encoding) to mp4 container format by using FFMPEG tools in advance.</p>


问:
Problem with web scraping - JavaSript on website is disabled

Hello,

I've been playing with discord bots (in Python) for a while now and I've come across a problem with scraping information on some websites that protect themselves from data collection by disabling javascript on their side so you can't get to their data.

I have already looked at many websites recommending changing in headers among other things, but it has not helped.

The next step was to use selenium, which returns me this information.

We're sorry but Hive-Engine Explorer doesn't work properly without JavaScript enabled. Please enable it to continue.

Code:

```<code>  chrome_options = Options()
  chrome_options.add_argument('--no-sandbox')
  chrome_options.add_argument("--disable-gpu")
  chrome_options.add_argument('--disable-dev-shm-usage')

  driver = webdriver.Chrome(options=chrome_options)
  driver.get("https://he.dtools.dev/richlist/BEE")
  htmlSource = driver.page_source
  print(htmlSource)
</code>```

I also checked how it looks like on the browser side itself and as we can see after entering the page there is no way to see the html file

Image from website

My question is, is it possible to bypass such security measures? Unfortunately I wanted to download the information from the API but it is not possible in this case.

答:
You don't need to run Selenium to get this data, the site uses a backend api to deliver the data which you can replicate easily in python:</p>
```<code>import requests
import pandas as pd
import time
import json

token = 'BEE'
limit = 100

id_ = int(time.time())

headers =   {
    'accept':'application/json, text/plain, */*',
    'content-type':'application/json',
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.3'
    }
url = 'https://api.hive-engine.com/rpc/contracts'

payload = {"jsonrpc":"2.0","id":id_,"method":"find","params":{"contract":"tokens","table":"balances","query":{"symbol":token},"offset":0,"limit":limit}}
resp = requests.post(url,headers=headers,data=json.dumps(payload)).json()

df= pd.DataFrame(resp['result'])
df.to_csv('HiveData.csv',index=False)

print('Saved to HiveData.csv')
</code>```

Body:
Hello,

I've been playing with discord bots (in Python) for a while now and I've come across a problem with scraping information on some websites that protect themselves from data collection by disabling javascript on their side so you can't get to their data.

I have already looked at many websites recommending changing in headers among other things, but it has not helped.

The next step was to use selenium, which returns me this information.

We're sorry but Hive-Engine Explorer doesn't work properly without JavaScript enabled. Please enable it to continue.

Code:

  chrome_options = Options()
  chrome_options.add_argument('--no-sandbox')
  chrome_options.add_argument("--disable-gpu")
  chrome_options.add_argument('--disable-dev-shm-usage')

  driver = webdriver.Chrome(options=chrome_options)
  driver.get("https://he.dtools.dev/richlist/BEE")
  htmlSource = driver.page_source
  print(htmlSource)

I also checked how it looks like on the browser side itself and as we can see after entering the page there is no way to see the html file

Image from website

My question is, is it possible to bypass such security measures? Unfortunately I wanted to download the information from the API but it is not possible in this case.

Body:
You don't need to run Selenium to get this data, the site uses a backend api to deliver the data which you can replicate easily in python:

import requests
import pandas as pd
import time
import json

token = 'BEE'
limit = 100

id_ = int(time.time())

headers =   {
    'accept':'application/json, text/plain, */*',
    'content-type':'application/json',
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.3'
    }
url = 'https://api.hive-engine.com/rpc/contracts'

payload = {"jsonrpc":"2.0","id":id_,"method":"find","params":{"contract":"tokens","table":"balances","query":{"symbol":token},"offset":0,"limit":limit}}
resp = requests.post(url,headers=headers,data=json.dumps(payload)).json()

df= pd.DataFrame(resp['result'])
df.to_csv('HiveData.csv',index=False)

print('Saved to HiveData.csv')


问:
Grouped points in ggplot next to each other
I am trying to recreat the following plot using ggplot2:

But I am not able to separate the points into the different groups. What I get something similar to this:

```<code>library(ggplot2)

mpg %>%  ggplot(aes(class, displ)) +
  geom_jitter(aes(fill=drv), width=.09, shape =21)
</code>```

How can this be done?

答:
I think you are looking for position_jitterdodge which is an argument of geom_point

library(ggplot2)

mpg |>  ggplot(aes(class, displ)) +
  geom_point(aes(fill=drv), position = position_jitterdodge(jitter.width = 0.05, jitter.height = 0.5, dodge.width = 0.4), shape =21)

```

Created on 2022-02-11 by the reprex package (v2.0.1)

Body:
I am trying to recreat the following plot using ggplot2:

But I am not able to separate the points into the different groups. What I get something similar to this:

library(ggplot2)

mpg %>%  ggplot(aes(class, displ)) +
  geom_jitter(aes(fill=drv), width=.09, shape =21)

How can this be done?

Body:
I think you are looking for position_jitterdodge which is an argument of geom_point

library(ggplot2)

mpg |>  ggplot(aes(class, displ)) +
  geom_point(aes(fill=drv), position = position_jitterdodge(jitter.width = 0.05, jitter.height = 0.5, dodge.width = 0.4), shape =21)

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
Dynamic navigation bar Flutter
I have an app for mobile that I would like to adapt for the web. The bottom navigation bar is not looking good for web and I have implemented responsive UI for the rest of the app screens.

Is there a way to make the horizontal bottom navigation bar, vertical for web/desktop layouts or a package to do the same?

答:
You can control the size and change the widget.

check this example

or you can use

LayoutBuilder

Check this link for LayoutBuilder

Title: Dynamic navigation bar Flutter


问:
How to get the current time as 13-digit integer in Ruby?
I have this jQuery function that returns the current time as the number of milliseconds since the epoch (Jan 1, 1970):

```<code>time = new Date().getTime();
</code>```

Is there a way to do the same in Ruby?

Right now, I am using Ruby's Time.now.to_i which works great but returns a 10-digit integer (number of seconds)

How can I get it to display the number of milliseconds, as in jQuery?

答:
Use Process.clock_gettime:

>> Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
=> 1644588106765
```

See https://ruby-doc.org/core-3.1.0/Process.html#method-c-clock_gettime

Body:
I have this jQuery function that returns the current time as the number of milliseconds since the epoch (Jan 1, 1970):

time = new Date().getTime();

Is there a way to do the same in Ruby?

Right now, I am using Ruby's Time.now.to_i which works great but returns a 10-digit integer (number of seconds)

How can I get it to display the number of milliseconds, as in jQuery?

Body:
Use Process.clock_gettime:

>> Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
=> 1644588106765

See https://ruby-doc.org/core-3.1.0/Process.html#method-c-clock_gettime


问:
For Each Loop stops after deleting one row
I am trying to use an if else statement to delete the entire row when a text value is found in a cell within a given range.

The code stops after deleting one row.

Sub DeleteSpecificRow()
    Set RR = Range("C1:C8")
    For Each cell In RR
        If cell.Value = "Site subcode " Or cell.Value = "Sample type" Or cell.Value = "Lab Sample ID code" Or cell.Value = "name determinand" Then cell.EntireRow.Delete
    Next cell
End Sub
```

I tried without using CELL at the end of the next but had the same affect.

答:
Try to loop in reverse, because if row is deleted address of all rows below also changes, which result your RR range obsolete and code stops. (e.g. if row 3 is deleted, row 4 becomes the new row 3, while your RR range points to the old address.)</p>
```<code>Sub DeleteSpecificRow()
    Set RR = Range("C1:C8")
    With RR
        For i = .cells.count to 1 step -1
            If .cells(i).Value = "Site subcode " Or .cells(i).Value = "Sample type" Or .cells(i).Value = "Lab Sample ID code" Or .cells(i).Value = "name determinand" Then .cells(i).EntireRow.Delete
        Next
    End with
End Sub
</code>```

Body:
I am trying to use an if else statement to delete the entire row when a text value is found in a cell within a given range.

The code stops after deleting one row.

Sub DeleteSpecificRow()
    Set RR = Range("C1:C8")
    For Each cell In RR
        If cell.Value = "Site subcode " Or cell.Value = "Sample type" Or cell.Value = "Lab Sample ID code" Or cell.Value = "name determinand" Then cell.EntireRow.Delete
    Next cell
End Sub

I tried without using CELL at the end of the next but had the same affect.

Body:
Try to loop in reverse, because if row is deleted address of all rows below also changes, which result your RR range obsolete and code stops. (e.g. if row 3 is deleted, row 4 becomes the new row 3, while your RR range points to the old address.)

Sub DeleteSpecificRow()
    Set RR = Range("C1:C8")
    With RR
        For i = .cells.count to 1 step -1
            If .cells(i).Value = "Site subcode " Or .cells(i).Value = "Sample type" Or .cells(i).Value = "Lab Sample ID code" Or .cells(i).Value = "name determinand" Then .cells(i).EntireRow.Delete
        Next
    End with
End Sub


问:
Read data from .xlsx file on S3 using Nodejs Lambda
I'm still new in NodeJs and AWS, so forgive me if this is a noob question.

I am trying to read the data from an excel file (.xlsx). The lambda function receives the extension of the file type.

Here is my code:

```<code>exports.handler = async (event, context, callback) => {
    console.log('Received event:', JSON.stringify(event, null, 2));
    if (event.fileExt === undefined) {
        callback("400 Invalid Input");
    }

    let returnData = "";
    const S3 = require('aws-sdk/clients/s3');
    const s3 = new S3();

    switch(event.fileExt)
    {
        case "plain":
        case "txt":
            // Extract text
            const params = {Bucket: 'filestation', Key: 'MyTXT.'+event.fileExt};

            try {
                await s3.getObject(params, function(err, data) {
                  if (err) console.log(err, err.stack); // an error occurred
                  else{           // successful response
                      returnData = data.Body.toString('utf-8');
                      context.done(null, returnData);
                  }
                }).promise();

            } catch (error) {
                console.log(error);
                return;
            }

            break;
        case "xls":
        case "xlsx":
            returnData = "Excel";
            // Extract text

            const params2 = {Bucket: 'filestation', Key: 'MyExcel.'+event.fileExt};
            const readXlsxFile = require("read-excel-file/node");

            try {
                const doc = await s3.getObject(params2);
                const parsedDoc = await readXlsxFile(doc);
                console.log(parsedDoc)
            } catch (err) {
                console.log(err);
                const message = `Error getting object.`;
                console.log(message);
                throw new Error(message);
            }

            break;
        case "docx":
            returnData = "Word doc";
            // Extract text
            break;
        default:
            callback("400 Invalid Operator");
            break;
    }
    callback(null, returnData);
};
</code>```

The textfile part works. But the xlsx part makes the function time out.
I did install the read-excel-file dependency and uploaded the zip so that I have access to it.
But the function times out with this message:
"errorMessage": "2020-11-02T13:06:50.948Z 120bfb48-f29c-4e3f-9507-fc88125515fd Task timed out after 3.01 seconds"

Any help would be appreciated! Thanks for your time.

答:
using the xlsx npm library. here's how we did it.

assuming the file is under the root project path.

```<code>const xlsx = require('xlsx');

// read your excel file
let readFile = xlsx.readFile('file_example_XLSX_5000.xlsx')

// get first-sheet's name
let sheetName = readFile.SheetNames[0];

// convert sheets to JSON. Best if sheet has a headers specified.
console.log(xlsx.utils.sheet_to_json(readFile.Sheets[sheetName]));
</code>```

Body:
I'm still new in NodeJs and AWS, so forgive me if this is a noob question.

I am trying to read the data from an excel file (.xlsx). The lambda function receives the extension of the file type.

Here is my code:

exports.handler = async (event, context, callback) => {
    console.log('Received event:', JSON.stringify(event, null, 2));
    if (event.fileExt === undefined) {
        callback("400 Invalid Input");
    }

    let returnData = "";
    const S3 = require('aws-sdk/clients/s3');
    const s3 = new S3();

    switch(event.fileExt)
    {
        case "plain":
        case "txt":
            // Extract text
            const params = {Bucket: 'filestation', Key: 'MyTXT.'+event.fileExt};

            try {
                await s3.getObject(params, function(err, data) {
                  if (err) console.log(err, err.stack); // an error occurred
                  else{           // successful response
                      returnData = data.Body.toString('utf-8');
                      context.done(null, returnData);
                  }
                }).promise();

            } catch (error) {
                console.log(error);
                return;
            }

            break;
        case "xls":
        case "xlsx":
            returnData = "Excel";
            // Extract text

            const params2 = {Bucket: 'filestation', Key: 'MyExcel.'+event.fileExt};
            const readXlsxFile = require("read-excel-file/node");

            try {
                const doc = await s3.getObject(params2);
                const parsedDoc = await readXlsxFile(doc);
                console.log(parsedDoc)
            } catch (err) {
                console.log(err);
                const message = `Error getting object.`;
                console.log(message);
                throw new Error(message);
            }

            break;
        case "docx":
            returnData = "Word doc";
            // Extract text
            break;
        default:
            callback("400 Invalid Operator");
            break;
    }
    callback(null, returnData);
};

The textfile part works. But the xlsx part makes the function time out.
I did install the read-excel-file dependency and uploaded the zip so that I have access to it.
But the function times out with this message:
"errorMessage": "2020-11-02T13:06:50.948Z 120bfb48-f29c-4e3f-9507-fc88125515fd Task timed out after 3.01 seconds"

Any help would be appreciated! Thanks for your time.

Body:
using the xlsx npm library. here's how we did it.

assuming the file is under the root project path.

const xlsx = require('xlsx');

// read your excel file
let readFile = xlsx.readFile('file_example_XLSX_5000.xlsx')

// get first-sheet's name
let sheetName = readFile.SheetNames[0];

// convert sheets to JSON. Best if sheet has a headers specified.
console.log(xlsx.utils.sheet_to_json(readFile.Sheets[sheetName]));


问:
how do I reference the values from textboxes on form submit that reside in my usercontrol? ASP.NET(VB)
I can't believe I couldn't find an answer to this question after literally hours of searching the web. Is this so basic that everyone just knows how to do this? As you might have guessed I'm new to asp.net(vb).

My situation:
I have a large form that reuses several elements, so I decided to create a usercontrol with some common fields. The problem is when the form is filled out by a user and submitted, how do I reference those values so I can input them to my database???

Example:

```<code>Using Conn As New SqlConnection(connect)
        Using Cmd As New SqlCommand(SQL, Conn)
            Cmd.Parameters.AddWithValue("@Acct_Company", txtPartner.Text)
            Cmd.Parameters.AddWithValue("@Acct_AccountNum", txtPartnerAccount.Text)
</code>```

So, above two Cmd lines are for normally inserted textboxes in my form, but what would the line look like to reference any usercontrol form fields?

Any help would be greatly appreciated.

答:
You need to expose the controls some how to the page that contains the user control. One way to to this is like this (within the control code):

```<code>Property CompanyName As String
  Get
    Return txtPartner.Text
  End Get
  Set(value As String)
    txtPartner.Text = value
  End Set
End Property
</code>```

Then, the page containing the user control can access the value like this:

```<code>myControl.CompanyName
</code>```

Body:
I can't believe I couldn't find an answer to this question after literally hours of searching the web. Is this so basic that everyone just knows how to do this? As you might have guessed I'm new to asp.net(vb).

My situation:
I have a large form that reuses several elements, so I decided to create a usercontrol with some common fields. The problem is when the form is filled out by a user and submitted, how do I reference those values so I can input them to my database???

Example:

Using Conn As New SqlConnection(connect)
        Using Cmd As New SqlCommand(SQL, Conn)
            Cmd.Parameters.AddWithValue("@Acct_Company", txtPartner.Text)
            Cmd.Parameters.AddWithValue("@Acct_AccountNum", txtPartnerAccount.Text)

So, above two Cmd lines are for normally inserted textboxes in my form, but what would the line look like to reference any usercontrol form fields?

Any help would be greatly appreciated.

Body:
You need to expose the controls some how to the page that contains the user control. One way to to this is like this (within the control code):

Property CompanyName As String
  Get
    Return txtPartner.Text
  End Get
  Set(value As String)
    txtPartner.Text = value
  End Set
End Property

Then, the page containing the user control can access the value like this:

myControl.CompanyName


问:
Escape double ampersand in powershell script when using Invoke-Expression
I am trying to build a command using different strings that are created conditionally.
This command is for adding a key to vault.

Thing is, either in key description or value double ampersands can occur.

I managed to escape single ampersand, but not the two or more.

Current code, excluding parameter passing etc for brevity:

```<code>[string]$params = "az keyvault secret set --name `'$name`' --vault-name `'$destinationVault`' "

    if($description -ne '')
    {
        # Escaping ampersand so that it can be used in Invoke-Expression
        $params += "--description `'$($description -replace '&', '"&"')`' "
    }

    $params += "--disabled $(if($enabled) { "false" } else { "true" }) "

    if($expires -ne '')
    {
        $params += "--expires `'$(([DateTime]($expires)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($notBefore -ne '')
    {
        $params += "--not-before `'$(([DateTime]($notBefore)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($tags -ne '')
    {
        $params += "--tags `'$tags`' "
    }
    else
    {
        $params += "--tags `"`" "
    }

    $params += "--value `'$($value -replace '&', '"&"')`'"

    return $params
</code>```

Returned params is used by parent script - $result = Invoke-Expression (Build-SetSecretCommand $secret $destinationKeyVault)

Result of this code ran on example data with single & in secret value in console looks like that:

```<code>az keyvault secret set --name 'secret_name' --vault-name 'vault_name' --disabled false --tags 'file-encoding=utf-8' --value 'super_secret://+_with_symbols"&"ampersand!'
</code>```

and translates to super_secret://+_with_symbols&ampersand! in created secret value.

As mentioned, code works with single &, but if there are more than one symbols like that, I am getting errors like

```<code>Invoke-Expression : At line:1 char:23
+ Write-Host asdasdasd a&&&&&asdASsdad asd a    ada   &7
The token '&&' is not a valid statement separator in this version.
</code>```

答:
After analyzing and applying bulk of knowledge from mklement0 excellent post, I wrote a small utility to fill my needs - to escape ", &, | and any combination of such characters, mostly in connection strings, etc.

```<code>function ConvertTo-CmdSafeString
{
    [OutputType([string])]
    param (
        [Parameter()]
        [string]$Source
    )
    if($Source -notmatch ' ')
    {
        $Source = $Source -replace '[\"]', '"$&'
        $Source = $Source -replace '[\"\|&]{1,}', '"$&"'
    }

    return $Source
}
</code>```

This, given the

$secret.value of

```<code>"abc"bca""abc"""bca""""abc&abc&&abc&&&abc""||&&"abc"|&&|"|"|"|"||abc||abc|||abc&|abc|&|&abc"&abc"&|&"abc&&||abc""'"&&||""abc"''
</code>```

It converts it to

```<code>""""abc""""bca""""""abc""""""""bca""""""""""abc"&"abc"&&"abc"&&&"abc"""""||&&"""abc"""|&&|""|""|""|""||"abc"||"abc"|||"abc"&|"abc"|&|&"abc"""&"abc"""&|&"""abc"&&||"abc""""""'"""&&||"""""abc""""''
</code>```

Which after executing $azsecret = (az $data) | ConvertFrom-Json

gives us $azsecret.value of

```<code>"abc"bca""abc"""bca""""abc&abc&&abc&&&abc""||&&"abc"|&&|"|"|"|"||abc||abc|||abc&|abc|&|&abc"&abc"&|&"abc&&||abc""'"&&||""abc"''
</code>```

If you see some errors in it or missed edge-cases, please let me know.

Body:
I am trying to build a command using different strings that are created conditionally.
This command is for adding a key to vault.

Thing is, either in key description or value double ampersands can occur.

I managed to escape single ampersand, but not the two or more.

Current code, excluding parameter passing etc for brevity:

[string]$params = "az keyvault secret set --name `'$name`' --vault-name `'$destinationVault`' "

    if($description -ne '')
    {
        # Escaping ampersand so that it can be used in Invoke-Expression
        $params += "--description `'$($description -replace '&', '"&"')`' "
    }

    $params += "--disabled $(if($enabled) { "false" } else { "true" }) "

    if($expires -ne '')
    {
        $params += "--expires `'$(([DateTime]($expires)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($notBefore -ne '')
    {
        $params += "--not-before `'$(([DateTime]($notBefore)).ToUniversalTime().ToString($dateFormat))`' "
    }

    if($tags -ne '')
    {
        $params += "--tags `'$tags`' "
    }
    else
    {
        $params += "--tags `"`" "
    }

    $params += "--value `'$($value -replace '&', '"&"')`'"

    return $params

Returned params is used by parent script - $result = Invoke-Expression (Build-SetSecretCommand $secret $destinationKeyVault)

Result of this code ran on example data with single & in secret value in console looks like that:

az keyvault secret set --name 'secret_name' --vault-name 'vault_name' --disabled false --tags 'file-encoding=utf-8' --value 'super_secret://+_with_symbols"&"ampersand!'

and translates to super_secret://+_with_symbols&ampersand! in created secret value.

As mentioned, code works with single &, but if there are more than one symbols like that, I am getting errors like

Invoke-Expression : At line:1 char:23
+ Write-Host asdasdasd a&&&&&asdASsdad asd a    ada   &7
The token '&&' is not a valid statement separator in this version.

Body:
After analyzing and applying bulk of knowledge from mklement0 excellent post, I wrote a small utility to fill my needs - to escape ", &, | and any combination of such characters, mostly in connection strings, etc.

function ConvertTo-CmdSafeString
{
    [OutputType([string])]
    param (
        [Parameter()]
        [string]$Source
    )
    if($Source -notmatch ' ')
    {
        $Source = $Source -replace '[\"]', '"$&'
        $Source = $Source -replace '[\"\|&]{1,}', '"$&"'
    }

    return $Source
}

This, given the

$secret.value of

"abc"bca""abc"""bca""""abc&abc&&abc&&&abc""||&&"abc"|&&|"|"|"|"||abc||abc|||abc&|abc|&|&abc"&abc"&|&"abc&&||abc""'"&&||""abc"''

It converts it to

""""abc""""bca""""""abc""""""""bca""""""""""abc"&"abc"&&"abc"&&&"abc"""""||&&"""abc"""|&&|""|""|""|""||"abc"||"abc"|||"abc"&|"abc"|&|&"abc"""&"abc"""&|&"""abc"&&||"abc""""""'"""&&||"""""abc""""''

Which after executing $azsecret = (az $data) | ConvertFrom-Json

gives us $azsecret.value of

"abc"bca""abc"""bca""""abc&abc&&abc&&&abc""||&&"abc"|&&|"|"|"|"||abc||abc|||abc&|abc|&|&abc"&abc"&|&"abc&&||abc""'"&&||""abc"''

If you see some errors in it or missed edge-cases, please let me know.


问:
when create xamarin.android app has error
Hello When I create a Xamarin app on Android, I encounter the following errors after creating the application

1-failed linking file resources. 2-attribute layout_behavior (aka
com.companyname.app2:layout_behavior) not found.

After seeing this problem, I saw the used version of Android, which was Android 11, and changed it to version 8.1.
The errors were fixed, but it showed me new errors

Package Xamarin.Google.Android.Material 1.0.0.1 is not compatible with monoandroid81 (MonoAndroid,Version=v8.1). Package Xamarin.Google.Android.Material 1.0.0.1 supports: monoandroid90 (MonoAndroid,Version=v9.0)
Package Xamarin.AndroidX.AppCompat 1.2.0.5 is not compatible with monoandroid81 (MonoAndroid,Version=v8.1). Package Xamarin.AndroidX.AppCompat 1.2.0.5 supports: monoandroid90 (MonoAndroid,Version=v9.0)

Because the program has an error, I can not use nuget
And I guess Visual Studio builds my project with Android 11 libraries.
But I do not know how to change this
Please help me to fix the errors

答:
This problem was not resolved and eventually I had to replace Windows and reinstall Visual Studio
And after reinstalling Visual Studio, I no longer had this problem</p>


问:
To extend the react-select interface property in typescript
I have customize a react-select drop-down component for my react-project.When i try to extend the interface using React.HTMLAttributes<HTMLSelectElement | HTMLInputElement>. It shows "No overload matches this call".
I have tried to extend different attributes to get the default values like id, label, name, placeholder, etc.
How can I get the default properties inside the props?
Did anyone experience any similar issue?

sample code:

```<code>import * as React from "react";

import ReactSelect from 'react-select';

export interface SelectProps extends React.HTMLAttributes<HTMLSelectElement | HTMLInputElement> {
    options: Array<any>;
    isMulti: boolean;
    isDisabled: boolean;

};

const Select: React.FC<SelectProps> = (props: SelectProps) => {

    return (<div>
        <label htmlFor={props.id}>{props.label}</label>
        <div>
            <ReactSelect
                {...props}
            />
        </div>
    </div>)
}
export default Select;
</code>```

After using the above code, I am not able to get props.id or props.name, etc.

答:
Edit:

React-Select v5 now natively supports TypeScript, therefore some type changes have been made (details).

Here's an updated example for v5 (react-select/async), similar to the original one with v4:

```<code>import ReactSelectAsync, { AsyncProps } from "react-select/async";
import { GroupBase } from "react-select";

interface CustomSelectAsyncProps {
  additionalCustomProp: number;
}

function SelectAsync<
  OptionType,
  IsMulti extends boolean = false,
  GroupType extends GroupBase<OptionType> = GroupBase<OptionType>
>({
  additionalCustomProp,
  ...props
}: AsyncProps<OptionType, IsMulti, GroupType> & CustomSelectAsyncProps) {
  return <ReactSelectAsync {...props} />;
}

export default SelectAsync;
</code>```

Codesandbox

Original Answer:

This is documented on the official react-select documentation.

Quote:

Wrapping the Select component
Oftentimes the Select component is wrapped in another component that is used throughout an app and the wrapper should be just as flexible as the original Select component (i.e., allow for different Option types, groups, single-select, or multi-select). In order to provide this flexibility, the wrapping component should re-declare the generics and forward them to the underlying Select. Here is an example of how to do that:

```<code>function CustomSelect<
  Option,
  IsMulti extends boolean = false,
  Group extends GroupBase<Option> = GroupBase<Option>
>(props: Props<Option, IsMulti, Group>) {
  return (
    <Select {...props} theme={(theme) => ({ ...theme, borderRadius: 0 })} />
  );
}
</code>```

It also explains how to extend the props with additional custom props:

You can use module augmentation to add custom props to the Select prop types:

```<code>declare module 'react-select/dist/declarations/src/Select' {
  export interface Props<
    Option,
    IsMulti extends boolean,
    Group extends GroupBase<Option>
  > {
    myCustomProp: string;
  }
}
</code>```

But I personally prefer to just add a custom interface using the & character with a custom interface to add custom props (example with ReactSelectAsync, see ... & CustomSelectAsyncProps):

```<code>interface CustomSelectAsyncProps {
  additionalCustomProp: number;
}

function SelectAsync<
  OptionType extends OptionTypeBase,
  IsMulti extends boolean = false,
  GroupType extends GroupTypeBase<OptionType> = GroupTypeBase<OptionType>
>({
  additionalCustomProp,
  ...props
}: Props<OptionType, IsMulti, GroupType> & CustomSelectAsyncProps) {
  return (
    <ReactSelectAsync {...props} />
  );
}
</code>```

Body:
I have customize a react-select drop-down component for my react-project.When i try to extend the interface using React.HTMLAttributes<HTMLSelectElement | HTMLInputElement>. It shows "No overload matches this call".
I have tried to extend different attributes to get the default values like id, label, name, placeholder, etc.
How can I get the default properties inside the props?
Did anyone experience any similar issue?

sample code:

import * as React from "react";

import ReactSelect from 'react-select';

export interface SelectProps extends React.HTMLAttributes<HTMLSelectElement | HTMLInputElement> {
    options: Array<any>;
    isMulti: boolean;
    isDisabled: boolean;

};

const Select: React.FC<SelectProps> = (props: SelectProps) => {

    return (

        {props.label}

            <ReactSelect
                {...props}
            />

)
}
export default Select;

After using the above code, I am not able to get props.id or props.name, etc.

Body:
Edit:

React-Select v5 now natively supports TypeScript, therefore some type changes have been made (details).

Here's an updated example for v5 (react-select/async), similar to the original one with v4:

import ReactSelectAsync, { AsyncProps } from "react-select/async";
import { GroupBase } from "react-select";

interface CustomSelectAsyncProps {
  additionalCustomProp: number;
}

function SelectAsync<
  OptionType,
  IsMulti extends boolean = false,
  GroupType extends GroupBase<OptionType> = GroupBase<OptionType>
>({
  additionalCustomProp,
  ...props
}: AsyncProps<OptionType, IsMulti, GroupType> & CustomSelectAsyncProps) {
  return <ReactSelectAsync {...props} />;
}

export default SelectAsync;

Codesandbox

Original Answer:

This is documented on the official react-select documentation.

Quote:

Wrapping the Select component
Oftentimes the Select component is wrapped in another component that is used throughout an app and the wrapper should be just as flexible as the original Select component (i.e., allow for different Option types, groups, single-select, or multi-select). In order to provide this flexibility, the wrapping component should re-declare the generics and forward them to the underlying Select. Here is an example of how to do that:

function CustomSelect<
  Option,
  IsMulti extends boolean = false,
  Group extends GroupBase<Option> = GroupBase<Option>
>(props: Props<Option, IsMulti, Group>) {
  return (
    <Select {...props} theme={(theme) => ({ ...theme, borderRadius: 0 })} />
  );
}

It also explains how to extend the props with additional custom props:

You can use module augmentation to add custom props to the Select prop types:

declare module 'react-select/dist/declarations/src/Select' {
  export interface Props<
    Option,
    IsMulti extends boolean,
    Group extends GroupBase<Option>
  > {
    myCustomProp: string;
  }
}

But I personally prefer to just add a custom interface using the & character with a custom interface to add custom props (example with ReactSelectAsync, see ... & CustomSelectAsyncProps):

interface CustomSelectAsyncProps {
  additionalCustomProp: number;
}

function SelectAsync<
  OptionType extends OptionTypeBase,
  IsMulti extends boolean = false,
  GroupType extends GroupTypeBase<OptionType> = GroupTypeBase<OptionType>
>({
  additionalCustomProp,
  ...props
}: Props<OptionType, IsMulti, GroupType> & CustomSelectAsyncProps) {
  return (
    <ReactSelectAsync {...props} />
  );
}


问:
How do I configure prettier to format YAML files to indent the list-items with zero space indent
When I run npx prettier --write pipeline.yml, it formats all child lines including dashes (-) with 2 space indents from the parent lines, like below:

```<code>resources:
  - name: concourse-examples
    type: git
    icon: github
    check_every: 30m
    source:
      uri: https://github.com/concourse/examples

jobs:
  - name: set-self
    public: true
    plan:
      - get: concourse-examples
        trigger: true
      - set_pipeline: self
        file: concourse-examples/pipelines/set-pipelines.yml
</code>```

I want all child lines, except the ones start with dashes (-), to be indented with 2 spaces from their parent lines, like below:

```<code>resources:
- name: concourse-examples
  type: git
  icon: github
  check_every: 30m
  source:
    uri: https://github.com/concourse/examples

jobs:
- name: set-self
  public: true
  plan:
  - get: concourse-examples
    trigger: true
  - set_pipeline: self
    file: concourse-examples/pipelines/set-pipelines.yml
</code>```

How can I achieve this?

答:
You can't. Quoting the option philosophy:

Prettier is not a kitchen-sink code formatter that attempts to print your code in any way you wish. It is opinionated.

Body:
When I run npx prettier --write pipeline.yml, it formats all child lines including dashes (-) with 2 space indents from the parent lines, like below:

resources:
  - name: concourse-examples
    type: git
    icon: github
    check_every: 30m
    source:
      uri: https://github.com/concourse/examples

jobs:
  - name: set-self
    public: true
    plan:
      - get: concourse-examples
        trigger: true
      - set_pipeline: self
        file: concourse-examples/pipelines/set-pipelines.yml

I want all child lines, except the ones start with dashes (-), to be indented with 2 spaces from their parent lines, like below:

resources:
- name: concourse-examples
  type: git
  icon: github
  check_every: 30m
  source:
    uri: https://github.com/concourse/examples

jobs:
- name: set-self
  public: true
  plan:
  - get: concourse-examples
    trigger: true
  - set_pipeline: self
    file: concourse-examples/pipelines/set-pipelines.yml

How can I achieve this?


问:
Attaching an identifier to an Oracle session
My Java application uses db sessions, via Hibernate.

What I want to do is somehow, when I create a session in my app, is to identify that session as an 'application' session. The reason is that I wish (via a before trigger) to restrict the updates that users can make to a table, while giving the application carte-blanche to do what it likes.

In other words, my trigger does something like this:

```<code>if(user is an application)
   allow update
else
   raise oracle error
end if
</code>```

Anyone know the best way to do this?

答:
It might be more simple to grant the privileges to a role and then have the application set that role.

http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10004.htm#sthref9521

OwnerDisplayName: Visage

Body:
My Java application uses db sessions, via Hibernate.

What I want to do is somehow, when I create a session in my app, is to identify that session as an 'application' session. The reason is that I wish (via a before trigger) to restrict the updates that users can make to a table, while giving the application carte-blanche to do what it likes.

In other words, my trigger does something like this:

if(user is an application)
   allow update
else
   raise oracle error
end if

Anyone know the best way to do this?

OwnerDisplayName: David Aldridge