问:
QML How to sort a tableView just by clicking on the header of the column
so in my project I'm using a tableview  which has model: tableModel fopm  Qt.labs.qmlmodels
1.0; so I want sort it using some methods , I find the class QAbsructProxyModel , I dont know if I used it well but I found problems on filtring and sorting here is below my code, thanks in advance` neeed help please

```<code>    import QtQuick 2.15
import QtQuick.Window 2.12
import Qt.labs.qmlmodels 1.0
import QtQuick.Controls 2.15
import QtQml.Models 2.15

import org.qtproject.example 1.0

ApplicationWindow {
    width: 1000
    height: 400
    visible: true

     header: ToolBar {
        TextField {
            id: searchBox

            placeholderText: "Search..."
            inputMethodHints: Qt.ImhNoPredictiveText

            //width: window.width / 5 * 2
            anchors.right: parent.right
            anchors.verticalCenter: parent.verticalCenter
        }
    }

    TableView {
        id:tableView
        anchors.fill: parent
        //sortIndicatorVisible: true

        //anchors.topMargin: 30
        columnSpacing: 1
        rowSpacing: 3
        anchors.topMargin:30
        //boundsBehavior: Flickable.StopAtBounds

        model:SortFilterProxyModel {
            id: proxyModel
            source: sourceModel.rowCount> 0 ? sourceModel : null
            onSourceChanged: console.log(source+" source")

            sortOrder: Qt.AscendingOrder//tableView.sortIndicatorOrder

            sortCaseSensitivity: Qt.CaseInsensitive
            sortRole: sourceModel.rowCount > 0 ? " nomdetrame": ""
            onSortRoleChanged: console.log(" role")
            filterString: "*" + searchBox.text + "*"
            //onFilterStringChanged: console.log(filterString)
            filterSyntax: SortFilterProxyModel.Wildcard
            filterCaseSensitivity: Qt.CaseInsensitive
        }

            TableModel {
            id:sourceModel

            TableModelColumn{ display: " teta"}
            TableModelColumn { display: "visibilite" }
            TableModelColumn { display: "couleur" }
            TableModelColumn{ display: "chaine_can"}
            TableModelColumn{ display: "nomdetrame" }
            TableModelColumn{ display: "nondusignal"}
            TableModelColumn { display: "valeurDec" }
            TableModelColumn { display: "valeurHex" }
            TableModelColumn { display: "TxouRx" }

            // Each row is one type of fruit that can be ordered
            rows: [
                {
                    // Each property is one cell/column.
                    teta:"+",
                    visibilite: false,
                    couleur: "red",
                    chaine_can: "CAN 4",
                    nomdetrame: "rRX",
                    nondusignal: "1.50",
                    valeurDec: "CAN 4",
                    valeurHex: "rRX",
                    TxouRx: "Tx"
                },
                {   teta:"+",
                    visibilite: false,
                    couleur: "grey",
                    chaine_can: "CAN 1",
                    nomdetrame: "rRX",
                    nondusignal: "1.5",
                    valeurDec: "CAN 4",
                    valeurHex: "rRX",
                    TxouRx: "Rx"
                },
                {   teta:"+",
                    visibilite: true,
                    couleur: "black",
                    chaine_can: "CAN 2",
                    nomdetrame: "rRX",
                    nondusignal: "1",
                    valeurDec: "CAN 4",
                    valeurHex: "RXE",
                    TxouRx: "Tx"
                }
            ]

        }

        delegate:  DelegateChooser {

            DelegateChoice{
                column: 0
                //width: 100
            delegate:Button{
                    id:teta
                    text:"+"
                    //anchors.fill: parent
                    onClicked:{tableView.sourceModel.appendRow({
                                                   // Each property is one cell/column.
                                                   teta:"+",
                                                   visibilite: false,
                                                   couleur: "red",
                                                   chaine_can: "CAN 4",
                                                   nomdetrame: "rRX",
                                                   nondusignal: "1.50",
                                                   valeurDec: "CAN 4",
                                                   valeurHex: "rRX",
                                                   TxouRx: "Tx"
                                               }
                                               )}

                }
                //z: -1
            }

            DelegateChoice{
                column: 1
            delegate:Rectangle{
                border.color: "black"
                implicitWidth: 80
                CheckBox{
                //anchors.fill: parent
                    anchors.centerIn: parent
                checked: model.display

            }
        }
            }
            DelegateChoice{
                column: 2
            delegate:Rectangle {
                implicitWidth: 80
                //anchors.fill: parent
                 border.color: "black"
                color: model.display
                //z: -1
            }
        }
            DelegateChoice{
                column: 3
            delegate:Rectangle{
                border.color:"black"
                implicitWidth: 80

                Button{
                    anchors.fill: parent
                    onClicked: console.log(currentIndex)
//                    TextInput {
//                        //textRole: "display"
//                    anchors.fill: parent
//                    text:model.display
//                    //z: -1
//                }
                }

        }
            }
            DelegateChoice{
                column: 4
           delegate:Rectangle{
               border.color: "black"
               implicitWidth: 80
               TextInput {
                //anchors.fill: parent
                   anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 5
            delegate:Rectangle{
                border.color: "black"
                implicitWidth: 80
                TextInput {
                //anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 6
            delegate:Rectangle{
                implicitWidth: 80
                border.color: "black"
                TextInput {
//                anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 7
            delegate:Rectangle{
                implicitWidth: 80
                border.color: "black"

                TextInput {
                //anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 8
            delegate:Rectangle{
                implicitWidth: 80
                border.color: "black"
                TextInput {
                //anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display

                //z: -1
            }
            }
        }

    }
        Component.onCompleted: {
            console.log(searchBox.text)
            //console.log(tableView.model.getRow(0).couleur)}

}
    }
    HorizontalHeaderView{
        id:headerView
        anchors.left: tableView.left
      syncView: tableView
      model:[" ","Visible","Couleur","Chaine_Can","NomTrame","NomSignal","ValeurDec","ValeurHex","TX/RX"]

        MouseArea{
            id:ms
            anchors.fill: parent
            hoverEnabled: true

        }

    }

}

</code>```

c++ code:

```<code>include "sortfilterproxymodel.h"
#include <QtDebug>
#include <QtQml>

SortFilterProxyModel::SortFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent), m_complete(false)
{
    connect(this, &QSortFilterProxyModel::rowsInserted, this, &SortFilterProxyModel::countChanged);
    connect(this, &QSortFilterProxyModel::rowsRemoved, this, &SortFilterProxyModel::countChanged);
    qDebug()<<"je suis entré chez moi";
}

int SortFilterProxyModel::count() const
{
    return rowCount();
}

QObject *SortFilterProxyModel::source() const
{
    return sourceModel();
}

void SortFilterProxyModel::setSource(QObject *source)
{
    setSourceModel(qobject_cast<QAbstractItemModel *>(source));
    emit sourceChanged();
}

QByteArray SortFilterProxyModel::sortRole() const
{
    return m_sortRole;
}

void SortFilterProxyModel::setSortRole(const QByteArray &role)
{
    if (m_sortRole != role) {
        m_sortRole = role;
        if (m_complete)
            QSortFilterProxyModel::setSortRole(roleKey(role));
    }
}

void SortFilterProxyModel::setSortOrder(Qt::SortOrder order)
{
    QSortFilterProxyModel::sort(0, order);
}

QByteArray SortFilterProxyModel::filterRole() const
{
    return m_filterRole;
}

void SortFilterProxyModel::setFilterRole(const QByteArray &role)
{
    if (m_filterRole != role) {
        m_filterRole = role;
        if (m_complete)
            QSortFilterProxyModel::setFilterRole(roleKey(role));
    }
}

QString SortFilterProxyModel::filterString() const
{
    return filterRegExp().pattern();
}

void SortFilterProxyModel::setFilterString(const QString &filter)
{

    setFilterRegExp(QRegExp(filter, filterCaseSensitivity(), static_cast<QRegExp::PatternSyntax>(filterSyntax())));
    emit filterStringChanged();
}

SortFilterProxyModel::FilterSyntax SortFilterProxyModel::filterSyntax() const
{
    return static_cast<FilterSyntax>(filterRegExp().patternSyntax());
}

void SortFilterProxyModel::setFilterSyntax(SortFilterProxyModel::FilterSyntax syntax)
{
    setFilterRegExp(QRegExp(filterString(), filterCaseSensitivity(), static_cast<QRegExp::PatternSyntax>(syntax)));
}

QJSValue SortFilterProxyModel::get(int idx) const
{
    QJSEngine *engine = qmlEngine(this);
    QJSValue value = engine->newObject();
    if (idx >= 0 && idx < count()) {
        QHash<int, QByteArray> roles = roleNames();
        for (auto it = roles.cbegin(), end = roles.cend(); it != end; ++it)
            value.setProperty(QString::fromUtf8(it.value()), data(index(idx, 0), it.key()).toString());
    }
    return value;
}

void SortFilterProxyModel::classBegin()
{
}

void SortFilterProxyModel::componentComplete()
{
    m_complete = true;

    if (!m_sortRole.isEmpty())
        QSortFilterProxyModel::setSortRole(roleKey(m_sortRole));

    if (!m_filterRole.isEmpty())
        QSortFilterProxyModel::setFilterRole(roleKey(m_filterRole));

}

int SortFilterProxyModel::roleKey(const QByteArray &role) const
{
    return roleNames().key(role, -1);

}

QHash<int, QByteArray> SortFilterProxyModel::roleNames() const
{
    qDebug()<<"RoleNames";
    if (QAbstractItemModel *source = sourceModel()){
        qDebug()<<"RoleNames";
        //qDebug()<< source->roleNames();
                    //qDebug()<<roleNames().key(0)<< " keys";
        return source->roleNames();}
    return QHash<int, QByteArray>();
}

bool SortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    QRegExp rx = filterRegExp();
    if (rx.isEmpty())
        return true;
    QAbstractItemModel *model = sourceModel();
    if (filterRole().isEmpty()) {
        QHash<int, QByteArray> roles = roleNames();
        for (auto it = roles.cbegin(), end = roles.cend(); it != end; ++it) {
            QModelIndex sourceIndex = model->index(sourceRow, 0, sourceParent);
            QString key = model->data(sourceIndex, it.key()).toString();
            if (key.contains(rx))
                return true;
        }
        return false;
    }
    QModelIndex sourceIndex = model->index(sourceRow, 0, sourceParent);
    if (!sourceIndex.isValid())
        return true;
    QString key = model->data(sourceIndex, roleKey(filterRole())).toString();
    qDebug()<<rx;
    return key.contains(rx);
}

</code>```

答:
I could not able to run your code. Since I am using older version of Qt. So I make a simple working proto with reimplemented QSortFilterProxyModel class and used it in qml for filtering and sorting. My source model is a listview, in your case that's a table view. other things are the same.

The probable part of the code needs to check.
1. Reimplementation of filterAcceptsRow
2. Reimplementation of lessThan
3. Ensure making a call to invalidateFilter while changing the search text
4. Ensure making a call to default sort function while changing sortOrder

============ Sample code here ============

```<code>************** main.qml **************
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

import SortFilter 1.0

Window {
    id: rootId
    width: 320
    height: 568
    visible: true

    SortFilterProxy {
        id: sortFilterProxyModelId
        sourceModel: fruitModel
        sortRole: Qt.DisplayRole
        searchString: ""
        sortOrder: Qt.AscendingOrder
    }

    ListModel {
        id: fruitModel
        ListElement { name: "Apple" }
        ListElement { name: "Orange" }
        ListElement { name: "Banana" }
    }

    Column {
        anchors.fill: parent

        TextField {
            id: searchIpId
            height: 40
            width: parent.width
            focus: true
            placeholderText: "Enter search text"
            onTextChanged: sortFilterProxyModelId.searchString = text

            Button {
                id: sortButtonId
                height: parent.height - 10
                width: 60
                text: "sort"
                anchors.rightMargin: 10
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                onClicked: {
                    // call proxy
                    if(sortFilterProxyModelId.sortOrder == Qt.AscendingOrder)
                        sortFilterProxyModelId.sortOrder = Qt.DescendingOrder
                    else
                        sortFilterProxyModelId.sortOrder = Qt.AscendingOrder
                    searchIpId.forceActiveFocus()
                }
            }
        }

        ListView {
            width: parent.width
            height: parent.height - searchIpId.height
            model: sortFilterProxyModelId // change to proxy output
            delegate: Rectangle {
                width: parent.width
                height: 40
                color: index % 2 == 0 ? "white" : "#C0C0C0"
                Label {
                    anchors.fill: parent
                    anchors.margins: 10
                    text: name
                }
            }
        }
    }
}

************** sortfilterproxymodel.h **************
#ifndef SORTPROXYMODEL_H
#define SORTPROXYMODEL_H

#include <QSortFilterProxyModel>

class SortFilterProxyModel : public QSortFilterProxyModel
{
    Q_OBJECT
    Q_PROPERTY(QString searchString READ searchString WRITE setSearchString NOTIFY searchStringChanged)
    Q_PROPERTY(Qt::SortOrder sortOrder READ sortOrder WRITE setSortOrder NOTIFY sortOrderChanged)
public:
    explicit SortFilterProxyModel(QObject* parent = nullptr);

    QString searchString() const
    {
        return _searchString;
    }
    Qt::SortOrder sortOrder() const
    {
        return _sortOrder;
    }
    void setSearchString(const QString &searchString);
    void setSortOrder(const Qt::SortOrder &sortOrder);

signals:
    void searchStringChanged(QString searchString);
    void sortOrderChanged(Qt::SortOrder sortOrder);

protected:
    bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;   // custom sort logic
    bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const;             // custom filter logic

private:
    QString _searchString;
    Qt::SortOrder _sortOrder;
};

#endif // SORTPROXYMODEL_H

************** sortfilterproxymodel.cpp **************
 #include "sortfilterproxymodel.h"

SortFilterProxyModel::SortFilterProxyModel(QObject* parent) :
    QSortFilterProxyModel(parent)
{
    connect(this, &SortFilterProxyModel::searchStringChanged, this, &SortFilterProxyModel::invalidate); //
}

void SortFilterProxyModel::setSearchString(const QString &searchString)
{
    if (_searchString == searchString)
        return;

    _searchString = searchString;
    emit searchStringChanged(searchString); // connected with invalidateFilter, internally invalidateFilter makes call to filterAcceptsRow function
}

void SortFilterProxyModel::setSortOrder(const Qt::SortOrder &sortOrder)
{
    if(_sortOrder == sortOrder)
        return ;
    _sortOrder = sortOrder;
    sort(0, sortOrder);         // responsible call to make sorting, internally it will make a call to lessthan function
    emit sortOrderChanged(sortOrder);
}

bool SortFilterProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
    QVariant left = sourceModel()->data(source_left);
    QVariant right = sourceModel()->data(source_right);

    if(left.isValid() && right.isValid())
    {
        return left.toString() > right.toString();
    } else
    {
        return false;
    }
}

bool SortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
    QString data = sourceModel()->data(index, Qt::DisplayRole).value<QString>();

    if(_searchString.isEmpty() || _searchString.isNull())
        return true;

    if(data.contains(_searchString, Qt::CaseInsensitive))
        return true;

    return false;
}

</code>```

Body:
so in my project I'm using a tableview  which has model: tableModel fopm  Qt.labs.qmlmodels
1.0; so I want sort it using some methods , I find the class QAbsructProxyModel , I dont know if I used it well but I found problems on filtring and sorting here is below my code, thanks in advance` neeed help please

    import QtQuick 2.15
import QtQuick.Window 2.12
import Qt.labs.qmlmodels 1.0
import QtQuick.Controls 2.15
import QtQml.Models 2.15

import org.qtproject.example 1.0

ApplicationWindow {
    width: 1000
    height: 400
    visible: true

     header: ToolBar {
        TextField {
            id: searchBox

            placeholderText: "Search..."
            inputMethodHints: Qt.ImhNoPredictiveText

            //width: window.width / 5 * 2
            anchors.right: parent.right
            anchors.verticalCenter: parent.verticalCenter
        }
    }

    TableView {
        id:tableView
        anchors.fill: parent
        //sortIndicatorVisible: true

        //anchors.topMargin: 30
        columnSpacing: 1
        rowSpacing: 3
        anchors.topMargin:30
        //boundsBehavior: Flickable.StopAtBounds

        model:SortFilterProxyModel {
            id: proxyModel
            source: sourceModel.rowCount> 0 ? sourceModel : null
            onSourceChanged: console.log(source+" source")

            sortOrder: Qt.AscendingOrder//tableView.sortIndicatorOrder

            sortCaseSensitivity: Qt.CaseInsensitive
            sortRole: sourceModel.rowCount > 0 ? " nomdetrame": ""
            onSortRoleChanged: console.log(" role")
            filterString: "*" + searchBox.text + "*"
            //onFilterStringChanged: console.log(filterString)
            filterSyntax: SortFilterProxyModel.Wildcard
            filterCaseSensitivity: Qt.CaseInsensitive
        }

            TableModel {
            id:sourceModel

            TableModelColumn{ display: " teta"}
            TableModelColumn { display: "visibilite" }
            TableModelColumn { display: "couleur" }
            TableModelColumn{ display: "chaine_can"}
            TableModelColumn{ display: "nomdetrame" }
            TableModelColumn{ display: "nondusignal"}
            TableModelColumn { display: "valeurDec" }
            TableModelColumn { display: "valeurHex" }
            TableModelColumn { display: "TxouRx" }

            // Each row is one type of fruit that can be ordered
            rows: [
                {
                    // Each property is one cell/column.
                    teta:"+",
                    visibilite: false,
                    couleur: "red",
                    chaine_can: "CAN 4",
                    nomdetrame: "rRX",
                    nondusignal: "1.50",
                    valeurDec: "CAN 4",
                    valeurHex: "rRX",
                    TxouRx: "Tx"
                },
                {   teta:"+",
                    visibilite: false,
                    couleur: "grey",
                    chaine_can: "CAN 1",
                    nomdetrame: "rRX",
                    nondusignal: "1.5",
                    valeurDec: "CAN 4",
                    valeurHex: "rRX",
                    TxouRx: "Rx"
                },
                {   teta:"+",
                    visibilite: true,
                    couleur: "black",
                    chaine_can: "CAN 2",
                    nomdetrame: "rRX",
                    nondusignal: "1",
                    valeurDec: "CAN 4",
                    valeurHex: "RXE",
                    TxouRx: "Tx"
                }
            ]

        }

        delegate:  DelegateChooser {

            DelegateChoice{
                column: 0
                //width: 100
            delegate:Button{
                    id:teta
                    text:"+"
                    //anchors.fill: parent
                    onClicked:{tableView.sourceModel.appendRow({
                                                   // Each property is one cell/column.
                                                   teta:"+",
                                                   visibilite: false,
                                                   couleur: "red",
                                                   chaine_can: "CAN 4",
                                                   nomdetrame: "rRX",
                                                   nondusignal: "1.50",
                                                   valeurDec: "CAN 4",
                                                   valeurHex: "rRX",
                                                   TxouRx: "Tx"
                                               }
                                               )}

                }
                //z: -1
            }

            DelegateChoice{
                column: 1
            delegate:Rectangle{
                border.color: "black"
                implicitWidth: 80
                CheckBox{
                //anchors.fill: parent
                    anchors.centerIn: parent
                checked: model.display

            }
        }
            }
            DelegateChoice{
                column: 2
            delegate:Rectangle {
                implicitWidth: 80
                //anchors.fill: parent
                 border.color: "black"
                color: model.display
                //z: -1
            }
        }
            DelegateChoice{
                column: 3
            delegate:Rectangle{
                border.color:"black"
                implicitWidth: 80

                Button{
                    anchors.fill: parent
                    onClicked: console.log(currentIndex)
//                    TextInput {
//                        //textRole: "display"
//                    anchors.fill: parent
//                    text:model.display
//                    //z: -1
//                }
                }

        }
            }
            DelegateChoice{
                column: 4
           delegate:Rectangle{
               border.color: "black"
               implicitWidth: 80
               TextInput {
                //anchors.fill: parent
                   anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 5
            delegate:Rectangle{
                border.color: "black"
                implicitWidth: 80
                TextInput {
                //anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 6
            delegate:Rectangle{
                implicitWidth: 80
                border.color: "black"
                TextInput {
//                anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 7
            delegate:Rectangle{
                implicitWidth: 80
                border.color: "black"

                TextInput {
                //anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display
                //z: -1
            }
        }
            }
            DelegateChoice{
                column: 8
            delegate:Rectangle{
                implicitWidth: 80
                border.color: "black"
                TextInput {
                //anchors.fill: parent
                    anchors.centerIn: parent
                text:model.display

                //z: -1
            }
            }
        }

    }
        Component.onCompleted: {
            console.log(searchBox.text)
            //console.log(tableView.model.getRow(0).couleur)}

}
    }
    HorizontalHeaderView{
        id:headerView
        anchors.left: tableView.left
      syncView: tableView
      model:[" ","Visible","Couleur","Chaine_Can","NomTrame","NomSignal","ValeurDec","ValeurHex","TX/RX"]

        MouseArea{
            id:ms
            anchors.fill: parent
            hoverEnabled: true

        }

    }

}

c++ code:

include "sortfilterproxymodel.h"
#include <QtDebug>
#include <QtQml>

SortFilterProxyModel::SortFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent), m_complete(false)
{
    connect(this, &QSortFilterProxyModel::rowsInserted, this, &SortFilterProxyModel::countChanged);
    connect(this, &QSortFilterProxyModel::rowsRemoved, this, &SortFilterProxyModel::countChanged);
    qDebug()<<"je suis entré chez moi";
}

int SortFilterProxyModel::count() const
{
    return rowCount();
}

QObject *SortFilterProxyModel::source() const
{
    return sourceModel();
}

void SortFilterProxyModel::setSource(QObject *source)
{
    setSourceModel(qobject_cast<QAbstractItemModel *>(source));
    emit sourceChanged();
}

QByteArray SortFilterProxyModel::sortRole() const
{
    return m_sortRole;
}

void SortFilterProxyModel::setSortRole(const QByteArray &role)
{
    if (m_sortRole != role) {
        m_sortRole = role;
        if (m_complete)
            QSortFilterProxyModel::setSortRole(roleKey(role));
    }
}

void SortFilterProxyModel::setSortOrder(Qt::SortOrder order)
{
    QSortFilterProxyModel::sort(0, order);
}

QByteArray SortFilterProxyModel::filterRole() const
{
    return m_filterRole;
}

void SortFilterProxyModel::setFilterRole(const QByteArray &role)
{
    if (m_filterRole != role) {
        m_filterRole = role;
        if (m_complete)
            QSortFilterProxyModel::setFilterRole(roleKey(role));
    }
}

QString SortFilterProxyModel::filterString() const
{
    return filterRegExp().pattern();
}

void SortFilterProxyModel::setFilterString(const QString &filter)
{

    setFilterRegExp(QRegExp(filter, filterCaseSensitivity(), static_cast<QRegExp::PatternSyntax>(filterSyntax())));
    emit filterStringChanged();
}

SortFilterProxyModel::FilterSyntax SortFilterProxyModel::filterSyntax() const
{
    return static_cast<FilterSyntax>(filterRegExp().patternSyntax());
}

void SortFilterProxyModel::setFilterSyntax(SortFilterProxyModel::FilterSyntax syntax)
{
    setFilterRegExp(QRegExp(filterString(), filterCaseSensitivity(), static_cast<QRegExp::PatternSyntax>(syntax)));
}

QJSValue SortFilterProxyModel::get(int idx) const
{
    QJSEngine *engine = qmlEngine(this);
    QJSValue value = engine->newObject();
    if (idx >= 0 && idx < count()) {
        QHash<int, QByteArray> roles = roleNames();
        for (auto it = roles.cbegin(), end = roles.cend(); it != end; ++it)
            value.setProperty(QString::fromUtf8(it.value()), data(index(idx, 0), it.key()).toString());
    }
    return value;
}

void SortFilterProxyModel::classBegin()
{
}

void SortFilterProxyModel::componentComplete()
{
    m_complete = true;

    if (!m_sortRole.isEmpty())
        QSortFilterProxyModel::setSortRole(roleKey(m_sortRole));

    if (!m_filterRole.isEmpty())
        QSortFilterProxyModel::setFilterRole(roleKey(m_filterRole));

}

int SortFilterProxyModel::roleKey(const QByteArray &role) const
{
    return roleNames().key(role, -1);

}

QHash<int, QByteArray> SortFilterProxyModel::roleNames() const
{
    qDebug()<<"RoleNames";
    if (QAbstractItemModel *source = sourceModel()){
        qDebug()<<"RoleNames";
        //qDebug()<< source->roleNames();
                    //qDebug()<<roleNames().key(0)<< " keys";
        return source->roleNames();}
    return QHash<int, QByteArray>();
}

bool SortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    QRegExp rx = filterRegExp();
    if (rx.isEmpty())
        return true;
    QAbstractItemModel *model = sourceModel();
    if (filterRole().isEmpty()) {
        QHash<int, QByteArray> roles = roleNames();
        for (auto it = roles.cbegin(), end = roles.cend(); it != end; ++it) {
            QModelIndex sourceIndex = model->index(sourceRow, 0, sourceParent);
            QString key = model->data(sourceIndex, it.key()).toString();
            if (key.contains(rx))
                return true;
        }
        return false;
    }
    QModelIndex sourceIndex = model->index(sourceRow, 0, sourceParent);
    if (!sourceIndex.isValid())
        return true;
    QString key = model->data(sourceIndex, roleKey(filterRole())).toString();
    qDebug()<<rx;
    return key.contains(rx);
}

Body:
I could not able to run your code. Since I am using older version of Qt. So I make a simple working proto with reimplemented QSortFilterProxyModel class and used it in qml for filtering and sorting. My source model is a listview, in your case that's a table view. other things are the same.

The probable part of the code needs to check.
1. Reimplementation of filterAcceptsRow
2. Reimplementation of lessThan
3. Ensure making a call to invalidateFilter while changing the search text
4. Ensure making a call to default sort function while changing sortOrder

============ Sample code here ============

************** main.qml **************
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2

import SortFilter 1.0

Window {
    id: rootId
    width: 320
    height: 568
    visible: true

    SortFilterProxy {
        id: sortFilterProxyModelId
        sourceModel: fruitModel
        sortRole: Qt.DisplayRole
        searchString: ""
        sortOrder: Qt.AscendingOrder
    }

    ListModel {
        id: fruitModel
        ListElement { name: "Apple" }
        ListElement { name: "Orange" }
        ListElement { name: "Banana" }
    }

    Column {
        anchors.fill: parent

        TextField {
            id: searchIpId
            height: 40
            width: parent.width
            focus: true
            placeholderText: "Enter search text"
            onTextChanged: sortFilterProxyModelId.searchString = text

            Button {
                id: sortButtonId
                height: parent.height - 10
                width: 60
                text: "sort"
                anchors.rightMargin: 10
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                onClicked: {
                    // call proxy
                    if(sortFilterProxyModelId.sortOrder == Qt.AscendingOrder)
                        sortFilterProxyModelId.sortOrder = Qt.DescendingOrder
                    else
                        sortFilterProxyModelId.sortOrder = Qt.AscendingOrder
                    searchIpId.forceActiveFocus()
                }
            }
        }

        ListView {
            width: parent.width
            height: parent.height - searchIpId.height
            model: sortFilterProxyModelId // change to proxy output
            delegate: Rectangle {
                width: parent.width
                height: 40
                color: index % 2 == 0 ? "white" : "#C0C0C0"
                Label {
                    anchors.fill: parent
                    anchors.margins: 10
                    text: name
                }
            }
        }
    }
}

************** sortfilterproxymodel.h **************
#ifndef SORTPROXYMODEL_H
#define SORTPROXYMODEL_H

#include <QSortFilterProxyModel>

class SortFilterProxyModel : public QSortFilterProxyModel
{
    Q_OBJECT
    Q_PROPERTY(QString searchString READ searchString WRITE setSearchString NOTIFY searchStringChanged)
    Q_PROPERTY(Qt::SortOrder sortOrder READ sortOrder WRITE setSortOrder NOTIFY sortOrderChanged)
public:
    explicit SortFilterProxyModel(QObject* parent = nullptr);

    QString searchString() const
    {
        return _searchString;
    }
    Qt::SortOrder sortOrder() const
    {
        return _sortOrder;
    }
    void setSearchString(const QString &searchString);
    void setSortOrder(const Qt::SortOrder &sortOrder);

signals:
    void searchStringChanged(QString searchString);
    void sortOrderChanged(Qt::SortOrder sortOrder);

protected:
    bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const;   // custom sort logic
    bool filterAcceptsRow(int sourceRow,const QModelIndex &sourceParent) const;             // custom filter logic

private:
    QString _searchString;
    Qt::SortOrder _sortOrder;
};

#endif // SORTPROXYMODEL_H

************** sortfilterproxymodel.cpp **************
 #include "sortfilterproxymodel.h"

SortFilterProxyModel::SortFilterProxyModel(QObject* parent) :
    QSortFilterProxyModel(parent)
{
    connect(this, &SortFilterProxyModel::searchStringChanged, this, &SortFilterProxyModel::invalidate); //
}

void SortFilterProxyModel::setSearchString(const QString &searchString)
{
    if (_searchString == searchString)
        return;

    _searchString = searchString;
    emit searchStringChanged(searchString); // connected with invalidateFilter, internally invalidateFilter makes call to filterAcceptsRow function
}

void SortFilterProxyModel::setSortOrder(const Qt::SortOrder &sortOrder)
{
    if(_sortOrder == sortOrder)
        return ;
    _sortOrder = sortOrder;
    sort(0, sortOrder);         // responsible call to make sorting, internally it will make a call to lessthan function
    emit sortOrderChanged(sortOrder);
}

bool SortFilterProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
    QVariant left = sourceModel()->data(source_left);
    QVariant right = sourceModel()->data(source_right);

    if(left.isValid() && right.isValid())
    {
        return left.toString() > right.toString();
    } else
    {
        return false;
    }
}

bool SortFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
    QString data = sourceModel()->data(index, Qt::DisplayRole).value<QString>();

    if(_searchString.isEmpty() || _searchString.isNull())
        return true;

    if(data.contains(_searchString, Qt::CaseInsensitive))
        return true;

    return false;
}


来源: stackexchange

问:
Usage of printf and fgets together in a loop
I am trying to implement a simple program which infinitely reads input from the user and then prints it. But there are some problems. It is a simple issue but my Google searches didn't lead me any solution. Here is the code.

```<code>int main() {

    char pass[32];
    int x=10;

    while (x!=0) {

        printf("\nInput the password: ");
        fgets(pass, sizeof(pass), stdin);

        printf("that is what i read: %s", pass);
    }
    return 0;
}
</code>```

When I enter a string longer than 32 characters, it behaves anormally.

```<code>Input the password: pass
that is what i read: pass

Input the password: passsssss
that is what i read: passsssss

Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss

Input the password:
</code>```

You see in the third attempt, it prints the third line automatically. I didn't type the input 'that is what i read: sss'.

Why does that happen?

答: You limited your input variable to 32 characters, so in order to stop it from doing that, simply make pass[32] bigger.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to implement a simple program which infinitely reads input from the user and then prints it. But there are some problems. It is a simple issue but my Google searches didn't lead me any solution. Here is the code.

int main() {

    char pass[32];
    int x=10;

    while (x!=0) {

        printf("\nInput the password: ");
        fgets(pass, sizeof(pass), stdin);

        printf("that is what i read: %s", pass);
    }
    return 0;
}

When I enter a string longer than 32 characters, it behaves anormally.

Input the password: pass
that is what i read: pass

Input the password: passsssss
that is what i read: passsssss

Input the password: passssssssssssssssssssssssssssssss
that is what i read: passsssssssssssssssssssssssssss
Input the password: that is what i read: sss

Input the password:

You see in the third attempt, it prints the third line automatically. I didn't type the input 'that is what i read: sss'.

Why does that happen?


问:
Naming keys in resource files best practice
Does anyone have any recommendations on naming keys in resource files? For instance, do you base the name of your key on the text that needs to be localized or on the control that uses the text?

Say you have an edit button in several screens (one to edit a user, one to edit a group). You could use the following keys:

editUserButton.label=Edit User...

editGroupButton.label=Edit Group...

or

editUser=Edit User...

editGroup=Edit Group...

or

user.edit=Edit User...

group.edit=Edit Group...

What scheme do you prefer and why?

答:
We base it on the English version of the term. Ex:EditUser
That was it is easily readable by our developers and can be reused in multiple locations that term is required throughout the app.</p>

OwnerDisplayName: Christophe Herreman

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: schooner


问:
How to fix the page position when I resize my HTA
We are using HTAs to display detailed reporting information (about our automated tests). The HTA can become multiple page lengths. It works great for our users, but I have a usability issue: When a user has scrolled to a certain position in the report (say, teststep 42) and the user maximizes or resizes the HTA window, the user looses his current position in the report (he had jumped to teststep 32 for example) and has to scroll to the correct position again.

How can I fix the page position, so resizing the HTA window does not affect it?

I know, it is possible to use min-width etc. but the layout of the HTA is mend to vary in size and/or wrapping around the corner. The only thing I want is that the same information is directly visible on the screen after resizing. Is that possible?

答:
You should be able to use the scrollTop property of an element to know how far someone has scrolled down in the page.

Use the onscroll event of the containing div element to record the value of that property each time scrolling occurs.

Then use some sort of "after resize" event to set the scrollTop property to the last recorded value. I haven't tracked down which event does this yet, but I'm sure there is something that will work.

ContentLicense: CC BY-SA 3.0


问:
input type=file show only button
Is there a way to style (or script) <input type=file /> element to have visible only "Browse" button without text field?

Thanks

Edit:
Just to clarify why to I need this. I'm using multi file upload code from http://www.morningz.com/?p=5 and it doesn't need input text field because it never has value. Script just adds newly selected file to collection on page. It would look much better without text field, if it's possible.

答:
I Don't Know what your talking about, if you trying to style a input type file into a button that is easy for me all you will need is just html and CSS.

#File-Body>#File-For {
  display: none;
}

#Filebutton {
  width: 50px;
  height: 20px;
  border: 1px solid;
  border-radius: 2px;
  text-align: center;
}

#File-Body {
  width: 300px;
  height: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="File-Body">
  <label id="File-Lable" for="File-For">
    <div id="Filebutton">Edit</div>
  </label>
  <input id="File-For" type="file">
</div></code>```

If you want to test it Here it is http://jsfiddle.net/qm8j45c3/

Title: input type=file show only button

Body:
I Don't Know what your talking about, if you trying to style a input type file into a button that is easy for me all you will need is just html and CSS.

#File-Body>#File-For {
  display: none;
}

#Filebutton {
  width: 50px;
  height: 20px;
  border: 1px solid;
  border-radius: 2px;
  text-align: center;
}

#File-Body {
  width: 300px;
  height: 30px;
}

<div id="File-Body">
  <label id="File-Lable" for="File-For">
    <div id="Filebutton">Edit</div>
  </label>
  <input id="File-For" type="file">
</div>

If you want to test it Here it is http://jsfiddle.net/qm8j45c3/


问:
Replacing an alphanumerical text from a url with a combination of aplha numerical text from the same url
I am stuck with a unique situation where I need to replace an alphanumerical text in an url with a combination of another text in the same url

Here is an example url

web_url("ABC_584","URL=https://ABCD.com/dEKgZETqwmDAh1rP/ArcGIS/rest/services/Overlay_Character/FeatureServer/0/query?

in this url I need to replace "ABC_584" with "Overlay_Character_0"

"ABC_584" is not static and that changes, so anything in the quote after web_url("XYZ_0-9" (i.e XYZ_0-9 in this case), has to be replaced by text after "Service/" and the number after FeatureServer/ from the above url

One more thing "ABC_584" can also be "123_123" completely numerical!

There are 100's of URL which I need to do it for and thus manually not possible, I tried VB script, writing Excel formulas to no use

Anyone here who can help me with this using any of the approach possible via Excel or Python code?

Thanks for reading, do let me know if you need more information

答:
What you want to do can be done in gvim (or vi, vim) editor by a one line regex-replace command (one line for all URLs):

```<code>:%s/web_url(".*","\(.*services\/\(.*\)\/FeatureServer\/\(.*\)\/query\)\@=/web_url("\2_\3","/g
</code>```

A similar regex can also be done using Python (loop through all your URLs).

```<code>import re
print (re.sub("web_url\(\"(.*)\",\"(?=.*services\/(.*)\/FeatureServer\/(.*)\/query)",r'web_url("\2_\3","', [your url string]))
</code>```

If you really want to use Excel formula:

extract the "ABC_584" by =mid([url], 10, find(""",""",[url])-10)

extract the group after "services/" by =LEFT(SUBSTITUTE(MID([url],FIND("services/", [url])+LEN("services/"),1000),"/FeatureServer/","_"), LEN(SUBSTITUTE(MID([url],FIND("services/", [url])+LEN("services/"),1000),"/FeatureServer/","_"))-LEN("/query?"))

Replace (1) with (2) using Excel formula by =SUBSTITUTE([url], [1], [2])

Body:
What you want to do can be done in gvim (or vi, vim) editor by a one line regex-replace command (one line for all URLs):

:%s/web_url(".*","\(.*services\/\(.*\)\/FeatureServer\/\(.*\)\/query\)\@=/web_url("\2_\3","/g

A similar regex can also be done using Python (loop through all your URLs).

import re
print (re.sub("web_url\(\"(.*)\",\"(?=.*services\/(.*)\/FeatureServer\/(.*)\/query)",r'web_url("\2_\3","', [your url string]))

If you really want to use Excel formula:

extract the "ABC_584" by =mid([url], 10, find(""",""",[url])-10)

extract the group after "services/" by =LEFT(SUBSTITUTE(MID([url],FIND("services/", [url])+LEN("services/"),1000),"/FeatureServer/","_"), LEN(SUBSTITUTE(MID([url],FIND("services/", [url])+LEN("services/"),1000),"/FeatureServer/","_"))-LEN("/query?"))

Replace (1) with (2) using Excel formula by =SUBSTITUTE([url], [1], [2])


问:
Getting the result of jquery .post() function
I need to find out how to access "data" variable outside of the post function.  It will return either valid or invalid so I can finish the main function logic.

Is this the right way to do it:

```<code>$('#form_choose_methods').submit(function(){
    var voucher_code = $('#voucher_code').val();
    var check = $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
        function(data) {
    });
    alert(check);
    return false;
});
</code>```

check seems to be the object, but I want to know how to access result of it.

答:
```<code>$('#form_choose_methods').submit(function () {
    var voucher_code = $('#voucher_code').val();
    $.post(baseURL + "ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
        function (data) {
            if (data == "valid") {
                //do seomthing
            }
            else {
                //do something else
            }
        });
});
</code>```

Body:
I need to find out how to access "data" variable outside of the post function.  It will return either valid or invalid so I can finish the main function logic.

Is this the right way to do it:

$('#form_choose_methods').submit(function(){
    var voucher_code = $('#voucher_code').val();
    var check = $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
        function(data) {
    });
    alert(check);
    return false;
});

check seems to be the object, but I want to know how to access result of it.


问:
How to convert strings into column names in Google Bigquery?
I have a large data set in Google BigQuery with millions of rows of dirty data (App tracking) that I am trying to clean up. One of my problems is that the same data got sent to different columns for different events triggered in the App. By this I mean that maybe the country was sent to custom dimension 1 for some events, but to custom dimension 147 for other events. I can't post actual data, but a SELECT * FROM table_with_dirty_data would produce something like this:

date | session | eventAction | cd001 | cd002    | cd004    | cd005
-----|---------|-------------|-------|----------|----------|-------
1    | 1       | 'event_1'   | '1'   | 'Pizza'  | null     | '21'
1    | 1       | 'event_2'   | '10'  | '25'     | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | '3.1' | null     | '15'     | 'France'
1    | 2       | 'event_1'   | '6'   | 'Burger' | null     | '21'
1    | 2       | 'event_2'   | '21'  | '25'     | 'Burger' | '12.6'
```
<p>The ultimate goal here is to end up with a clean table that can be analyzed. Something like this:</p>
<pre class="lang-sql prettyprint-override"><code>date | session | eventAction | country  | vendor   | product  | price
-----|---------|-------------|----------|----------|----------|-------
1    | 1       | 'event_1'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_2'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 2       | 'event_1'   | 'Spain'  | '25'     | 'Burger' | '12.6'
1    | 2       | 'event_2'   | 'Spain'  | '25'     | 'Burger' | '12.6'
</code>```

I am aware that some events will need some degree of statistical imputation and data type casting, but for now I am only concerned with getting every variable into its own column. So I've created an auxiliary table (let's call it matrix) that looks like this:

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_2'  | 'cd020'    | 'cd146'    | 'cd056'
'event_3'  | 'cd001'    | 'cd020'    | 'cd035'
```
<p>and so on, where the value in each cell of column <code>variable_#</code> is the column name in the <code>table_with_dirty_data</code> where the information can be found. That is, <code>variable_1</code> can be found in a column called <code>cd020</code> for events with <code>event_name</code> 'event_1' and 'even_2', but in a column called <code>cd001</code> for events with <code>event_name</code> 'event_3'. So basically what <code>matrix</code> does is to map to which custom dimension each variable was sent for each event.</p>
<p>I have hundreds of different events in <code>table_with_dirty_data</code>, and <code>matrix</code> holds all 200 GA custom dimensions, so doing something like</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
  CASE
    WHEN event_name = 'event_1' THEN cd020
    WHEN event_name = 'event_2' THEN cd020
    WHEN event_name = 'event_3' THEN cd001
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN cd035
      WHEN event_name = 'event_2' THEN cd146
      WHEN event_name = 'event_3' THEN cd020
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN cd120
      WHEN event_name = 'event_2' THEN cd056
      WHEN event_name = 'event_3' THEN cd035
  END AS variable_3
FROM table_with_dirty_data
</code>```

would take me a looooong time and is very error-prone. What I am trying to do is to use SELECT statements that return the column name (cd###) from the table_with_dirty_data where the information is stored and the use a WHILE to loop over all different events. So, for example, with event_name = 'event_1' it would be something like this:

SELECT
  CASE
    WHEN event_name = 'event_1'
    THEN (SELECT variable_1 FROM matrix WHERE event_name = 'event_1')
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_2 FROM matrix WHERE event_name = 'event_1')
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_3 FROM matrix WHERE event_name = 'event_1')
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'
```
<p>The goal here is that I can then loop over an array with all the <code>event_name</code>s (something that can be easily achieved). Ultimately I need all events in one table, but I'm ok with having a table for curating each event, as long as it can be done programmatically (something I personally don't know if it's even possible in GBQ...would have to check on that).</p>
<p>The issue is that the <code>SELECT</code> statements I am using get evaluated to a string, so the result of the queries inside the <code>CASE</code> clause are string literals. For example, if I were to run it for event = 'event_1',</p>
<pre class="lang-sql prettyprint-override"><code>SELECT variable_1 FROM matrix WHERE event_name = 'event_1'
</code>```

evaluates to

'cd020'
```
<p>which then cause the outer query to become</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
  CASE
    WHEN event_name = 'event_1' THEN 'cd020'
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN 'cd035'
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN 'cd120'
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'
</code>```

which produces a table like this

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
```

instead of returning the value stored in columns cd020, cd035 or cd120 for each time the event 'event_1' is found.

Does anyone know a way to unquote the result of those inner queries so that when the outer query executes, they are transformed into column names (so 'cd020' becomes cd020)??

PS: I am also open to a totally different strategy if anyone knows one.

答:
I solved the problem using the EXECUTE IMMEDIATE clause as recommended by @shollyman. I did it for just one of the events but I believe this answers the original question (scaling it to other events is just a matter of writing a WHILE loop). I'll go step by step since I'm not using an actual repex.

Step one I declared a variable called event with the name of the event that the query needs to look for.

DECLARE event STRING DEFAULT 'event_1';
```
<p>Then I declared a variable that holds the column name where the query needs to look for the variable.</p>
<pre class="lang-sql prettyprint-override"><code>DECLARE variable_name STRING DEFAULT (SELECT variable_1 FROM matrix WHERE event_name = event);
</code>```

Then I wrote the query as I would normally do, but using the EXECUTE IMMEDIATE clause. I used triple double-quotes so that I could break it into several lines for readability).

EXECUTE IMMEDIATE CONCAT("""
  SELECT
    CASE WHEN event_name = '""", event, "' THEN ", variable_name, """ END AS variable_1
  FROM table_with_dirty_data
  WHERE event_name = '""", event, """'
""");
```

If others are going to use this, do take note of the lonely single quotes that I used before or after some triple double quotes. I did that because, for example, the declared variable event, even though it's a string, seems to get concatenated as event (no single quotes around it) and that breaks the query execution.

Body:
I have a large data set in Google BigQuery with millions of rows of dirty data (App tracking) that I am trying to clean up. One of my problems is that the same data got sent to different columns for different events triggered in the App. By this I mean that maybe the country was sent to custom dimension 1 for some events, but to custom dimension 147 for other events. I can't post actual data, but a SELECT * FROM table_with_dirty_data would produce something like this:

date | session | eventAction | cd001 | cd002    | cd004    | cd005
-----|---------|-------------|-------|----------|----------|-------
1    | 1       | 'event_1'   | '1'   | 'Pizza'  | null     | '21'
1    | 1       | 'event_2'   | '10'  | '25'     | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | '3.1' | null     | '15'     | 'France'
1    | 2       | 'event_1'   | '6'   | 'Burger' | null     | '21'
1    | 2       | 'event_2'   | '21'  | '25'     | 'Burger' | '12.6'

The ultimate goal here is to end up with a clean table that can be analyzed. Something like this:

date | session | eventAction | country  | vendor   | product  | price
-----|---------|-------------|----------|----------|----------|-------
1    | 1       | 'event_1'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_2'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 1       | 'event_3'   | 'France' | '1'      | 'Pizza'  | '14.56'
1    | 2       | 'event_1'   | 'Spain'  | '25'     | 'Burger' | '12.6'
1    | 2       | 'event_2'   | 'Spain'  | '25'     | 'Burger' | '12.6'

I am aware that some events will need some degree of statistical imputation and data type casting, but for now I am only concerned with getting every variable into its own column. So I've created an auxiliary table (let's call it matrix) that looks like this:

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_2'  | 'cd020'    | 'cd146'    | 'cd056'
'event_3'  | 'cd001'    | 'cd020'    | 'cd035'

and so on, where the value in each cell of column variable_# is the column name in the table_with_dirty_data where the information can be found. That is, variable_1 can be found in a column called cd020 for events with event_name 'event_1' and 'even_2', but in a column called cd001 for events with event_name 'event_3'. So basically what matrix does is to map to which custom dimension each variable was sent for each event.

I have hundreds of different events in table_with_dirty_data, and matrix holds all 200 GA custom dimensions, so doing something like

SELECT
  CASE
    WHEN event_name = 'event_1' THEN cd020
    WHEN event_name = 'event_2' THEN cd020
    WHEN event_name = 'event_3' THEN cd001
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN cd035
      WHEN event_name = 'event_2' THEN cd146
      WHEN event_name = 'event_3' THEN cd020
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN cd120
      WHEN event_name = 'event_2' THEN cd056
      WHEN event_name = 'event_3' THEN cd035
  END AS variable_3
FROM table_with_dirty_data

would take me a looooong time and is very error-prone. What I am trying to do is to use SELECT statements that return the column name (cd###) from the table_with_dirty_data where the information is stored and the use a WHILE to loop over all different events. So, for example, with event_name = 'event_1' it would be something like this:

SELECT
  CASE
    WHEN event_name = 'event_1'
    THEN (SELECT variable_1 FROM matrix WHERE event_name = 'event_1')
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_2 FROM matrix WHERE event_name = 'event_1')
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1'
      THEN (SELECT variable_3 FROM matrix WHERE event_name = 'event_1')
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'

The goal here is that I can then loop over an array with all the event_names (something that can be easily achieved). Ultimately I need all events in one table, but I'm ok with having a table for curating each event, as long as it can be done programmatically (something I personally don't know if it's even possible in GBQ...would have to check on that).

The issue is that the SELECT statements I am using get evaluated to a string, so the result of the queries inside the CASE clause are string literals. For example, if I were to run it for event = 'event_1',

SELECT variable_1 FROM matrix WHERE event_name = 'event_1'

evaluates to

'cd020'

which then cause the outer query to become

SELECT
  CASE
    WHEN event_name = 'event_1' THEN 'cd020'
  END AS variable_1
  , CASE
      WHEN event_name = 'event_1' THEN 'cd035'
    END AS variable_2
  , CASE
      WHEN event_name = 'event_1' THEN 'cd120'
    END AS variable_3
FROM table_with_dirty_data
WHERE event_name = 'event_1'

which produces a table like this

event_name | variable_1 | variable_2 | variable_3
-----------|------------|------------|----------
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'
'event_1'  | 'cd020'    | 'cd035'    | 'cd120'

instead of returning the value stored in columns cd020, cd035 or cd120 for each time the event 'event_1' is found.

Does anyone know a way to unquote the result of those inner queries so that when the outer query executes, they are transformed into column names (so 'cd020' becomes cd020)??

PS: I am also open to a totally different strategy if anyone knows one.

Body:
I solved the problem using the EXECUTE IMMEDIATE clause as recommended by @shollyman. I did it for just one of the events but I believe this answers the original question (scaling it to other events is just a matter of writing a WHILE loop). I'll go step by step since I'm not using an actual repex.

Step one I declared a variable called event with the name of the event that the query needs to look for.

DECLARE event STRING DEFAULT 'event_1';

Then I declared a variable that holds the column name where the query needs to look for the variable.

DECLARE variable_name STRING DEFAULT (SELECT variable_1 FROM matrix WHERE event_name = event);

Then I wrote the query as I would normally do, but using the EXECUTE IMMEDIATE clause. I used triple double-quotes so that I could break it into several lines for readability).

EXECUTE IMMEDIATE CONCAT("""
  SELECT
    CASE WHEN event_name = '""", event, "' THEN ", variable_name, """ END AS variable_1
  FROM table_with_dirty_data
  WHERE event_name = '""", event, """'
""");

If others are going to use this, do take note of the lonely single quotes that I used before or after some triple double quotes. I did that because, for example, the declared variable event, even though it's a string, seems to get concatenated as event (no single quotes around it) and that breaks the query execution.


问:
VueJs: How to use array in double braces {{}}?
How to use array in vue js

var myObject = new Vue({
  el: '#app',
  data: {message: ["Hello"],["Word"]}
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
  <h1>{{ message[0] }}</h1>
</div></code>```

I want to show "Hello" in H1 tag, anyidea, thank you very much

答:
Firstly, make sure that you initialise the data property properly.

```<code>data: {
 message: ["Hello", "Word"]
}
</code>```

Then you can do message[0] if you know exactly that "Hello" is at the index of 0.

You can also have an array of objects like so

```<code>data: {
  message: [{
  first: "Hello",
  second: "Word"
 }]
}
</code>```

then to access it you would write {{message[0].first}}

You can even write functions inside the {{}} like {{message.find(el => el == "Hello World")}}

I hope it helps.

Body:
How to use array in vue js

var myObject = new Vue({
  el: '#app',
  data: {message: ["Hello"],["Word"]}
})

{{ message[0] }}

I want to show "Hello" in H1 tag, anyidea, thank you very much

Body:
Firstly, make sure that you initialise the data property properly.

data: {
 message: ["Hello", "Word"]
}

Then you can do message[0] if you know exactly that "Hello" is at the index of 0.

You can also have an array of objects like so

data: {
  message: [{
  first: "Hello",
  second: "Word"
 }]
}

then to access it you would write {{message[0].first}}

You can even write functions inside the {{}} like {{message.find(el => el == "Hello World")}}

I hope it helps.


问:
Restricting css selectors to one class without repeating the class name
I am looking for some way to not repeat a class name within css. For example if I have

.class1 div { color: red }
.class1 h2 { color: blue }
.class1 p { color: yellow }
```

<p>is there some way I can group the 3 rules under the one class, something like</p>

<pre class="lang-css prettyprint-override"><code>.class1 {
    div { color: red }
    h2 { color: blue }
    p { color: yellow }
}
</code>```

答:
With SASS (or SCSS), you can write :

.class1 {
    & div { color: red }
    & h2 { color: blue }
    & p { color: yellow }
}
```

<p>Where the '&' sign means 'write what you are actually in' (here, it means 'write .class1'). With an SASS or SCSS compiler, this will output :</p>

<pre class="lang-css prettyprint-override"><code>.class1 div {
    color: red;
}

.class1 h2 {
    color: blue;
}

.class1 p {
    color: yellow;
}
</code>```

You can start using Online SCSS compiler to start learning it without installing it. You can use the the official Documentation , which is pretty good, or browse Youtube to find some good tutorials.

Hope it helped !

Body:
I am looking for some way to not repeat a class name within css. For example if I have

.class1 div { color: red }
.class1 h2 { color: blue }
.class1 p { color: yellow }

is there some way I can group the 3 rules under the one class, something like

.class1 {
    div { color: red }
    h2 { color: blue }
    p { color: yellow }
}

Body:
With SASS (or SCSS), you can write :

.class1 {
    & div { color: red }
    & h2 { color: blue }
    & p { color: yellow }
}

Where the '&' sign means 'write what you are actually in' (here, it means 'write .class1'). With an SASS or SCSS compiler, this will output :

.class1 div {
    color: red;
}

.class1 h2 {
    color: blue;
}

.class1 p {
    color: yellow;
}

You can start using Online SCSS compiler to start learning it without installing it. You can use the the official Documentation , which is pretty good, or browse Youtube to find some good tutorials.

Hope it helped !


问:
Check to make sure the host is up or that the database listener is running on that host
i have a problem when i try to install Oracle Interprise Manager Cloud Control 12c

I checked it is open enter image description here

What should i do now

答:
Check the network listener with "lsnrctl status" from the command line and make sure it is running (it will have its own service on Windows), and that the database has registered
a service name with it.

If the listener is up and running correctly, make sure there is no system firewall blocking access to port 1521.

Try using the IP address of the host instead of the hostname, or switch to "localhost" if everything is running on the same system.


问:
How to implement back button in angular 9
I'm implementing a small project with only two UIs.

1-The first UI is called Home which contains paginated users list the home component.

2-The second UI is called user details which contains user profile the user-details component

3- and of course the app component which contains the tool bar and router-outlet

let us suppose the following scenario

I'm in the home UI and in the second page of the paginated users list and I clicked on one of the users item then the user-details UI appeard and I'm now in the second UI and I now I want to navigate back to the home but when doing so the home UI is recreated and become the first page of the users list instead of the second page where we left it because this is my code of the back button

```<code><img
  routerLink = "/home" style="cursor: pointer;"
    width="40"
    alt="Angular Logo"
 />
  <span routerLink = "/home" style="cursor: pointer;">Users</span>
</code>```

my question is:
is there is any way to implement it in such a way it doesn't recreate the home page i.e. implement the correct behavior of back button?

答:
There's a couple ways that you can approach this.

If you're using a pagination library (such as ngx-pagination), then hopefully the pagination component takes an input for the current page. You'd then need to keep track of that page either through a service or in persistent storage.
Whenever you route back to the Home UI, get the page that you were on and load that back into the pagination component.

Another way can be to use router parameters. By modifying your urls a bit, they can take on the following form:

/home/1

/home/2

/home/3

Clicking on a user in page 2 can give the url: /home/2/user-id (just an example)

The path for your home component can look like:

```<code>const routes: Routes = [
  { path: "home/:pageNumber", component: HomeComponent }
];
</code>```

Upon loading the home component, you can get the get the router parameter as follows (I'm using the Router method but you can parse the URL manually as well):

```<code>export class HomeComponent implements OnInit {
  constructor(private router: Router) {
    const pageNumber = this.router.navigationExtras.params['pageNumber'];
  }
}

</code>```

You can then load this page number into your pagination component. Using this method doesn't require you to keep track of the previous pages.

There are probably better methods to do this, but this is just some suggestions :)

Body:
I'm implementing a small project with only two UIs.

1-The first UI is called Home which contains paginated users list the home component.

2-The second UI is called user details which contains user profile the user-details component

3- and of course the app component which contains the tool bar and router-outlet

let us suppose the following scenario

I'm in the home UI and in the second page of the paginated users list and I clicked on one of the users item then the user-details UI appeard and I'm now in the second UI and I now I want to navigate back to the home but when doing so the home UI is recreated and become the first page of the users list instead of the second page where we left it because this is my code of the back button

  Users

my question is:
is there is any way to implement it in such a way it doesn't recreate the home page i.e. implement the correct behavior of back button?

Body:
There's a couple ways that you can approach this.

If you're using a pagination library (such as ngx-pagination), then hopefully the pagination component takes an input for the current page. You'd then need to keep track of that page either through a service or in persistent storage.
Whenever you route back to the Home UI, get the page that you were on and load that back into the pagination component.

Another way can be to use router parameters. By modifying your urls a bit, they can take on the following form:

/home/1

/home/2

/home/3

Clicking on a user in page 2 can give the url: /home/2/user-id (just an example)

The path for your home component can look like:

const routes: Routes = [
  { path: "home/:pageNumber", component: HomeComponent }
];

Upon loading the home component, you can get the get the router parameter as follows (I'm using the Router method but you can parse the URL manually as well):

export class HomeComponent implements OnInit {
  constructor(private router: Router) {
    const pageNumber = this.router.navigationExtras.params['pageNumber'];
  }
}

You can then load this page number into your pagination component. Using this method doesn't require you to keep track of the previous pages.

There are probably better methods to do this, but this is just some suggestions :)


问:
Is it possible to create a word cloud by importing data from an Excel file?
I have no idea.

```<code>your_list=[]
workbook=openpyxl.load_workbook(filename='crawling.xlsx')
worksheet=workbook.get_sheet_by_name("Sheet")
for i in worksheet.rows:
    page=i[0].value
    your_list.append(page)
</code>```

I don't know what to do first. Is the library to use openpyxl or is it better to just read the document with open function?

I want WordCloud (). Generate (your_list) to be possible
Sorry for the messy code.

答:
I can use

from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_excel(r"Youtube04-Eminem.excel", encoding ="latin-1")

pandas lib to read excel file

Body:
I have no idea.

your_list=[]
workbook=openpyxl.load_workbook(filename='crawling.xlsx')
worksheet=workbook.get_sheet_by_name("Sheet")
for i in worksheet.rows:
    page=i[0].value
    your_list.append(page)

I don't know what to do first. Is the library to use openpyxl or is it better to just read the document with open function?

I want WordCloud (). Generate (your_list) to be possible
Sorry for the messy code.


问:
Delphi Listview move items up / down with buttons

Possible Duplicate:

  Delphi: Shift-Up and Shift-Down in the Listview

Hi
I have a list view and I want to be able to move the selected item / items up and down the list using buttons but cannot figure out how to do this, Could someone give me an example

many thanks

Colin

答:
```<code>procedure Tfrprodetile.ExchangeItems(lv: TListView; const i, j: Integer);
var
  tempLI: TListItem;
begin
  lv.Items.BeginUpdate;
  try
    tempLI := TListItem.Create(lv.Items);
    tempLI.Assign(lv.Items.Item[i]);
    lv.Items.Item[i].Assign(lv.Items.Item[j]);
    lv.Items.Item[j].Assign(tempLI);
    tempLI.Free;
  finally
    lv.Items.EndUpdate
  end;
end;
</code>```

and for use :

move down :

```<code>ExchangeItems(lst_detile,lst_detile.Selected.Index,lst_detile.Selected.Index+1);
</code>```

move up :

```<code>ExchangeItems(lst_detile,lst_detile.Selected.Index,lst_detile.Selected.Index-1);
</code>```

note that "lst_detile" is name of my listview

good day !

Body:
procedure Tfrprodetile.ExchangeItems(lv: TListView; const i, j: Integer);
var
  tempLI: TListItem;
begin
  lv.Items.BeginUpdate;
  try
    tempLI := TListItem.Create(lv.Items);
    tempLI.Assign(lv.Items.Item[i]);
    lv.Items.Item[i].Assign(lv.Items.Item[j]);
    lv.Items.Item[j].Assign(tempLI);
    tempLI.Free;
  finally
    lv.Items.EndUpdate
  end;
end;

and for use :

move down :

ExchangeItems(lst_detile,lst_detile.Selected.Index,lst_detile.Selected.Index+1);

move up :

ExchangeItems(lst_detile,lst_detile.Selected.Index,lst_detile.Selected.Index-1);

note that "lst_detile" is name of my listview

good day !


问:
How to fetch data from database before rendering in a function componment in React?
Below is my code:

```<code>function Profile() {
    const {userInfo} = useSelector(state => state.user);
    let user = {};

    useEffect(() => {
        const populateUserInfo = async () => {
            const {data} = await axios.get("api/users/" + userInfo._id);
            user = data

            // this line works if I comment out {user.shipping.address} in the "return" section.
            console.log(user.shipping.address)
        }
        populateUserInfo();
    }, [])

    return <div>{user.shipping.address}</div>
}
</code>```

I want to fetch data from DB and store it into user variable before rendering, but when the page renders, TypeError: Cannot read property 'address' of undefined occurred.

I guess the user variable is still empty when the page renders?
Could anyone teach me how to do it?

答:
As of right now, you are updating your user variable only inside the useEffect function which is local. You need it to get updated outside that function as well.

To do this, I would suggest to use useState instead.
Declare the user state outside the function as so:

const [user, setUser] = useState({});

Inside the profile function, replace:

let user = {};

With:

setUser({});

Then inside the useEffect function, replace:

user = data;

With:

setUser({data});

Body:
Below is my code:

function Profile() {
    const {userInfo} = useSelector(state => state.user);
    let user = {};

    useEffect(() => {
        const populateUserInfo = async () => {
            const {data} = await axios.get("api/users/" + userInfo._id);
            user = data

            // this line works if I comment out {user.shipping.address} in the "return" section.
            console.log(user.shipping.address)
        }
        populateUserInfo();
    }, [])

    return
{user.shipping.address}

}

I want to fetch data from DB and store it into user variable before rendering, but when the page renders, TypeError: Cannot read property 'address' of undefined occurred.

I guess the user variable is still empty when the page renders?
Could anyone teach me how to do it?


问:
Passport JS won't save new schema to DB?
I am trying to use passport.js with GoogleStrategy to authorize users for a web application I am building. I then want to store the users in MongoDB using mongoose.

```<code>// Use the GoogleStrategy within Passport.
//   Strategies in passport require a `verify` function, which accept
//   credentials (in this case, a token, tokenSecret, and Google profile), and
//   invoke a callback with a user object.
passport.use(
    new GoogleStrategy({
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        callbackURL: '/google/redirect'
    }, (accessToken, refreshToken, profile, done) => {
        console.log(profile);
        console.log(profile.displayName);
        console.log(profile.id);
        new Models.User({
            username: profile.displayName,
            googleID: profile.id,
            memberOf: null
            //console.log('got this far');
        }).save(console.log('got to the save')).then((newUser) => {
            console.log(newUser+'was created');
        });
        console.log('came down here');
    })
)
</code>```

That is my implementation of passport and mongoose. Once I get the profile from Google I am trying to store that user's displayName and googleID in my User schema which I want to save to my DB. I'm not sure what I'm doing wrong but when I run this program I see that all the console.log's output to the terminal **except** for the console.log(newUser+'was created'); in the .then() I was hoping someone could help me fix this issue.

答: Update: Try adding an error handler in your mongoose.connect() method so you can see if your application is successfully connecting to your DB or not. That was the issue in my case.

Body:
I am trying to use passport.js with GoogleStrategy to authorize users for a web application I am building. I then want to store the users in MongoDB using mongoose.

// Use the GoogleStrategy within Passport.
//   Strategies in passport require a `verify` function, which accept
//   credentials (in this case, a token, tokenSecret, and Google profile), and
//   invoke a callback with a user object.
passport.use(
    new GoogleStrategy({
        clientID: keys.google.clientID,
        clientSecret: keys.google.clientSecret,
        callbackURL: '/google/redirect'
    }, (accessToken, refreshToken, profile, done) => {
        console.log(profile);
        console.log(profile.displayName);
        console.log(profile.id);
        new Models.User({
            username: profile.displayName,
            googleID: profile.id,
            memberOf: null
            //console.log('got this far');
        }).save(console.log('got to the save')).then((newUser) => {
            console.log(newUser+'was created');
        });
        console.log('came down here');
    })
)

That is my implementation of passport and mongoose. Once I get the profile from Google I am trying to store that user's displayName and googleID in my User schema which I want to save to my DB. I'm not sure what I'm doing wrong but when I run this program I see that all the console.log's output to the terminal **except** for the console.log(newUser+'was created'); in the .then() I was hoping someone could help me fix this issue.


问:
Can I label the x-axis as \rho, the Greek letter in matplotlib?
I have used \alpha, \lambda e.t.c to label axes in matplotlib, but it seems that \rho is not allowed. Is it because not every Greek letter is allowed? Can I label the x-axis as \rho?</p>

```<code>import matplotlib.pyplot as plt
from np.random import normal

plt.figure()
plt.plot(np.linspace(0,10,100), normal(0,1,100), color="darkblue")
plt.xlabel("$\rho$")
plt.ylabel("Values")
plt.show()
</code>```

答:
You can do it and you must have been really close if you got alpha and lambda to display.

What you missed is the r in front of it. It should look like this:

plt.xlabel(r"$\rho$")

Here is the documentation

Body:
I have used \alpha, \lambda e.t.c to label axes in matplotlib, but it seems that \rho is not allowed. Is it because not every Greek letter is allowed? Can I label the x-axis as \rho?

import matplotlib.pyplot as plt
from np.random import normal

plt.figure()
plt.plot(np.linspace(0,10,100), normal(0,1,100), color="darkblue")
plt.xlabel("$\rho$")
plt.ylabel("Values")
plt.show()


问:
How can I get this quadratic fit to plateau?
I have two variables, x and y, that are random variables. I want to fit a curve to them that plateaus. I've been able to do this using an exponential fit but I'd like to do so with a quadratic fit as well.

How can I get the fit to flatten out at the top? FWIW, the y data were generated such that no value goes above: 4300. So probably in the new curve it should have this requirement.

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

x = np.asarray([70,37,39,42,35,35,44,40,42,51,65,32,56,51,33,47,33,42,33,44,46,38,53,38,54,54,51,46,50,51,48,48,50,32,54,60,41,40,50,49,58,35,53,66,41,48,43,54,51])
y = np.asarray([3781,3036,3270,3366,2919,2966,3326,2812,3053,3496,3875,1823,3510,3615,2987,3589,2791,2819,1885,3570,3431,3095,3678,2297,3636,3569,3547,3553,3463,3422,3516,3538,3671,1888,3680,3775,2720,3450,3563,3345,3731,2145,3364,3928,2720,3621,3425,3687,3630])

def polyfit(x, y, degree):
    results = {}
    coeffs = np.polyfit(x, y, degree)

     # Polynomial Coefficients
    results['polynomial'] = coeffs.tolist()

    # r-squared, fit values, and average
    p = np.poly1d(coeffs)
    yhat = p(x)
    ybar = np.sum(y)/len(y)
    ssreg = np.sum((yhat-ybar)**2)
    sstot = np.sum((y - ybar)**2)
    results['determination'] = ssreg / sstot

    return results, yhat, ybar

def plot_polyfit(x=None, y=None, degree=None):
    # degree = degree of the fitting polynomial
    xmin = min(x)
    xmax = max(x)
    fig, ax = plt.subplots(figsize=(5,4))
    p = np.poly1d(np.polyfit(x, y, degree))
    t = np.linspace(xmin, xmax, len(x))

    ax.plot(x, y, 'ok', t, p(t), '-', markersize=3, alpha=0.6, linewidth=2.5)

    results, yhat, ybar = polyfit(x,y,degree)
    R_squared = results['determination']
    textstr = r'$r^2=%.2f$' % (R_squared, )
    props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)

    fig.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=12,
            verticalalignment='top', bbox=props)

    results['polynomial'][0]

plot_polyfit(x=x, y=y, degree=2)
```

<p><img src="https://i.stack.imgur.com/9IFmu.png" alt="enter image description here"></p>

<p>In contrast, I can use the same functions and get the curve to plateau better when the data are so:</p>

<pre class="lang-py prettyprint-override"><code>x2 = np.asarray([0, 1, 2,  3,  4,  5,  6,  7,  8,  9,  10, 12])
y2 = np.asarray([2, 4, 8, 12, 14, 18, 20, 21, 22, 23,  24, 24])

plot_polyfit(x=x2, y=y2, degree=2)
</code>```

Edits suggested by @tstanisl:

def plot_newfit(xdat, ydat):
    x,y = xdat, ydat
    xmax = 4300
    def new_fit(A,x,B):
        return A*(x - xmax)**2+B # testing this out

    fig, axs = plt.subplots(figsize=(5,4))

    # Find best fit.
    popt, pcov = curve_fit(new_fit, x, y)

    # Top plot
    # Plot data and best fit curve.
    axs.plot(x, y,'ok', alpha=0.6)
    axs.plot(np.sort(x), new_fit(np.sort(x), *popt),'-')

    #r2
    residuals = y - new_fit(x, *popt)
    ss_res = np.sum(residuals**2)
    ss_tot = np.sum((y-np.mean(y))**2)
    r_squared = 1 - (ss_res / ss_tot)
    r_squared

    # Add text
    textstr = r'$r^2=%.2f$' % (r_squared, )
    props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
    fig.text(0.05, 0.95, textstr, transform=axs.transAxes, fontsize=12,
            verticalalignment='top', bbox=props)

plot_newfit(x,y)
```

答:
I'm not too familiar with scipy.optimise but, if you find the Euclidian distance between the point that contains x-max and the one that contains your y-max, divide it in half and do some trig, you could use that coord to either force your quadratic through it, or use it in your array. (again not too familiar with scipy.optimise so I'm not sure if that first option is possible, but the second should lessen the downwards curve)

I can provide the proof if you don't understand.

Body:
I have two variables, x and y, that are random variables. I want to fit a curve to them that plateaus. I've been able to do this using an exponential fit but I'd like to do so with a quadratic fit as well.

How can I get the fit to flatten out at the top? FWIW, the y data were generated such that no value goes above: 4300. So probably in the new curve it should have this requirement.

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

x = np.asarray([70,37,39,42,35,35,44,40,42,51,65,32,56,51,33,47,33,42,33,44,46,38,53,38,54,54,51,46,50,51,48,48,50,32,54,60,41,40,50,49,58,35,53,66,41,48,43,54,51])
y = np.asarray([3781,3036,3270,3366,2919,2966,3326,2812,3053,3496,3875,1823,3510,3615,2987,3589,2791,2819,1885,3570,3431,3095,3678,2297,3636,3569,3547,3553,3463,3422,3516,3538,3671,1888,3680,3775,2720,3450,3563,3345,3731,2145,3364,3928,2720,3621,3425,3687,3630])

def polyfit(x, y, degree):
    results = {}
    coeffs = np.polyfit(x, y, degree)

     # Polynomial Coefficients
    results['polynomial'] = coeffs.tolist()

    # r-squared, fit values, and average
    p = np.poly1d(coeffs)
    yhat = p(x)
    ybar = np.sum(y)/len(y)
    ssreg = np.sum((yhat-ybar)**2)
    sstot = np.sum((y - ybar)**2)
    results['determination'] = ssreg / sstot

    return results, yhat, ybar

def plot_polyfit(x=None, y=None, degree=None):
    # degree = degree of the fitting polynomial
    xmin = min(x)
    xmax = max(x)
    fig, ax = plt.subplots(figsize=(5,4))
    p = np.poly1d(np.polyfit(x, y, degree))
    t = np.linspace(xmin, xmax, len(x))

    ax.plot(x, y, 'ok', t, p(t), '-', markersize=3, alpha=0.6, linewidth=2.5)

    results, yhat, ybar = polyfit(x,y,degree)
    R_squared = results['determination']
    textstr = r'$r^2=%.2f$' % (R_squared, )
    props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)

    fig.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=12,
            verticalalignment='top', bbox=props)

    results['polynomial'][0]

plot_polyfit(x=x, y=y, degree=2)

In contrast, I can use the same functions and get the curve to plateau better when the data are so:

x2 = np.asarray([0, 1, 2,  3,  4,  5,  6,  7,  8,  9,  10, 12])
y2 = np.asarray([2, 4, 8, 12, 14, 18, 20, 21, 22, 23,  24, 24])

plot_polyfit(x=x2, y=y2, degree=2)

Edits suggested by @tstanisl:

def plot_newfit(xdat, ydat):
    x,y = xdat, ydat
    xmax = 4300
    def new_fit(A,x,B):
        return A*(x - xmax)**2+B # testing this out

    fig, axs = plt.subplots(figsize=(5,4))

    # Find best fit.
    popt, pcov = curve_fit(new_fit, x, y)

    # Top plot
    # Plot data and best fit curve.
    axs.plot(x, y,'ok', alpha=0.6)
    axs.plot(np.sort(x), new_fit(np.sort(x), *popt),'-')

    #r2
    residuals = y - new_fit(x, *popt)
    ss_res = np.sum(residuals**2)
    ss_tot = np.sum((y-np.mean(y))**2)
    r_squared = 1 - (ss_res / ss_tot)
    r_squared

    # Add text
    textstr = r'$r^2=%.2f$' % (r_squared, )
    props = dict(boxstyle='square', facecolor='lightgray', alpha=0.5)
    fig.text(0.05, 0.95, textstr, transform=axs.transAxes, fontsize=12,
            verticalalignment='top', bbox=props)

plot_newfit(x,y)


问:
Why can't I post from my Xamarin Frorms app to my .net core web api
I have a post method that sends json to my api.

My endpoint works in postman so my problem is in my xamarin post request:

```<code>    async void RegisterUser(object sender, System.EventArgs e)
    {
        string URL = "http://blablahblah:51001/register";

        HttpClient client = new HttpClient();

        var model = new RegisterViewModel
        {
            Email = EntryEmail.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text,
            Password = EntryPasswrd.Text

        };

        var content = JsonConvert.SerializeObject(model);

        await client.PostAsync(URL, new StringContent(content));

    }
</code>```

after it hits the await client.PostAsync(URL, new StringContent(content)); line, the application just stops dead. no error messages or anything like that.

Any ideas?

EDIT:

My register method in my API solution:

```<code>    [Route("register")]
    [HttpPost]
    public async Task<ActionResult> InsertUser([FromBody] RegisterViewModel model)
    {
        var user = new IdentityUser
        {
            Email = model.Email,
            UserName = model.Email,
            SecurityStamp = Guid.NewGuid().ToString()
        };

        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var newUser = new User
            {
                Username = model.Email,
                FirstName = model.FirstName,
                LastName = model.LastName
            };

            _dbContext.Users.Add(newUser);
            await _dbContext.SaveChangesAsync();

        }
        return Ok(new { Username = user.UserName });
    }
</code>```

and my view model i am passing the data through:

```<code>public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    public string Password { get; set; }
}
</code>```

I have since rewrote my post method using the below suggestions, its still not returning any errors inside my catch block:

```<code>    public async Task<string> Registered(object details)
    {
        string URL = "http://blahblah:51001/register";

        HttpClient client = new HttpClient();

        var model = new RegisterViewModel
        {
            Email = EntryEmail.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text,
            Password = EntryPasswrd.Text

        };

        var content = JsonConvert.SerializeObject(model);

        try
        {
            await client.PostAsync(URL, new StringContent(content));
        }
        catch (Exception ex)
        {

            throw new Exception(ex.Message);
        }

        return "Registration Successful";
    }
</code>```

答:
Please test the Web Api with some REST testing tool like POSTMAN, to verify that it works with your JSON data firstly.

If your webapi have no problems, please take a look the following code, I can post data to asp.net core webapi successfully, and return value.

```<code> private async void btnpost_Clicked(object sender, EventArgs e)
    {
        ContactModel cm = new ContactModel() {ID=1,Name="cherry",Age=12 };

        var httpClient = new HttpClient();
        var content = JsonConvert.SerializeObject(cm);
        HttpContent httpContent = new StringContent(content, Encoding.UTF8);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var uri = new Uri("http://xxx.xx.xx.xx:8088/api/Contact");
        HttpResponseMessage response = await httpClient.PostAsync(uri, httpContent);
        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();

            string ss = data;
        }

    }
</code>```

Please note: Adding android:usesCleartextTraffic="true" in Mainfeast.xml,because starting with Android 9 (API level 28), cleartext support is disabled by default. if not, you may have Cleartext HTTP traffic not permitted error.

Body:
I have a post method that sends json to my api.

My endpoint works in postman so my problem is in my xamarin post request:

    async void RegisterUser(object sender, System.EventArgs e)
    {
        string URL = "http://blablahblah:51001/register";

        HttpClient client = new HttpClient();

        var model = new RegisterViewModel
        {
            Email = EntryEmail.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text,
            Password = EntryPasswrd.Text

        };

        var content = JsonConvert.SerializeObject(model);

        await client.PostAsync(URL, new StringContent(content));

    }

after it hits the await client.PostAsync(URL, new StringContent(content)); line, the application just stops dead. no error messages or anything like that.

Any ideas?

EDIT:

My register method in my API solution:

    [Route("register")]
    [HttpPost]
    public async Task<ActionResult> InsertUser([FromBody] RegisterViewModel model)
    {
        var user = new IdentityUser
        {
            Email = model.Email,
            UserName = model.Email,
            SecurityStamp = Guid.NewGuid().ToString()
        };

        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var newUser = new User
            {
                Username = model.Email,
                FirstName = model.FirstName,
                LastName = model.LastName
            };

            _dbContext.Users.Add(newUser);
            await _dbContext.SaveChangesAsync();

        }
        return Ok(new { Username = user.UserName });
    }

and my view model i am passing the data through:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    public string Password { get; set; }
}

I have since rewrote my post method using the below suggestions, its still not returning any errors inside my catch block:

    public async Task<string> Registered(object details)
    {
        string URL = "http://blahblah:51001/register";

        HttpClient client = new HttpClient();

        var model = new RegisterViewModel
        {
            Email = EntryEmail.Text,
            FirstName = FirstName.Text,
            LastName = LastName.Text,
            Password = EntryPasswrd.Text

        };

        var content = JsonConvert.SerializeObject(model);

        try
        {
            await client.PostAsync(URL, new StringContent(content));
        }
        catch (Exception ex)
        {

            throw new Exception(ex.Message);
        }

        return "Registration Successful";
    }

Body:
Please test the Web Api with some REST testing tool like POSTMAN, to verify that it works with your JSON data firstly.

If your webapi have no problems, please take a look the following code, I can post data to asp.net core webapi successfully, and return value.

 private async void btnpost_Clicked(object sender, EventArgs e)
    {
        ContactModel cm = new ContactModel() {ID=1,Name="cherry",Age=12 };

        var httpClient = new HttpClient();
        var content = JsonConvert.SerializeObject(cm);
        HttpContent httpContent = new StringContent(content, Encoding.UTF8);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        var uri = new Uri("http://xxx.xx.xx.xx:8088/api/Contact");
        HttpResponseMessage response = await httpClient.PostAsync(uri, httpContent);
        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();

            string ss = data;
        }

    }

Please note: Adding android:usesCleartextTraffic="true" in Mainfeast.xml,because starting with Android 9 (API level 28), cleartext support is disabled by default. if not, you may have Cleartext HTTP traffic not permitted error.


答:
Make user a state and do conditional render.

Initially, user is not set.

```<code>const [user, setUser] = useState(); // null

useEffect(
  () => {
    const populateUserInfo = async () => {
      const {data} = await axios.get("api/users/" + userInfo._id);
      setUser(data);
    }

    populateUserInfo();
  }
  , []
)

return (
  user ? (
    <div>{user.shipping.address}</div>
    : null
  );
);
</code>```

Title: How to fetch data from database before rendering in a function componment in React?

Body:
Make user a state and do conditional render.

Initially, user is not set.

const [user, setUser] = useState(); // null

useEffect(
  () => {
    const populateUserInfo = async () => {
      const {data} = await axios.get("api/users/" + userInfo._id);
      setUser(data);
    }

    populateUserInfo();
  }
  , []
)

return (
  user ? (
    <div>{user.shipping.address}</div>
    : null
  );
);