问:
Qt Qml connect to a signal of a QObject property of a Context Property
So this may seem like a strange setup. I have a C++ object that inherits from QObject called "MasterGuiLogic" for simplicity. It is created with a pointer to another object called "MainEventBroker" which as you might guess handles all of my applications events. The MasterGuiLogic object is registered with qml as a context property so that it's properties can be used anywhere in my qml. So main.cpp looks like this:

```<code>int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    MasterEventBroker *MainEventBroker = new MasterEventBroker();
    MasterGuiLogic *MainGuiLogic = new MasterGuiLogic(*MainEventBroker);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;
    QQmlContext* context = engine.rootContext();

    context->setContextProperty("MasterGuiLogic", &(*MainGuiLogic));

    engine.load(QUrl(QLatin1String("qrc:/QmlGui/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
</code>```

MasterGuiLogic creates an instance of another class called SerialCom, which is set as a Q_PROPERTY so that it's properties and public slots can be reached in qml through the MasterGuiLogic property.

MasterGuiLogic.h:

```<code>class MasterGuiLogic : public QObject
{
    Q_OBJECT
    Q_PROPERTY(GuiLogic_SerialCom* serialCom READ serialCom CONSTANT)
public:
    MasterEventBroker *eventBroker;

    explicit MasterGuiLogic(MasterEventBroker &ev, QObject *parent = nullptr);

    GuiLogic_SerialCom* serialCom() const {
        return Gui_SerialCom;
    }

private:

    GuiLogic_SerialCom *Gui_SerialCom;
</code>```

MasterGuiLogic.cpp:

```<code>MasterGuiLogic::MasterGuiLogic(MasterEventBroker &ev, QObject *parent) : QObject(parent)
{
    this->eventBroker = &ev;
    this->Gui_SerialCom = new GuiLogic_SerialCom(this);
}
</code>```

SerialCom.h:

```<code>//Forward Declare our parent
class MasterGuiLogic;

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QStringList portNames READ portNames NOTIFY portNamesChanged)
    Q_PROPERTY(bool connectedToPort READ connectedToPort NOTIFY connectedToPortChanged)
public:

    MasterGuiLogic *parent;
    explicit GuiLogic_SerialCom(MasterGuiLogic *parent = nullptr);

    std::map<QString, QSerialPortInfo> portsMap;

    QStringList portNames() {
        return _portNames;
    }

    bool connectedToPort() {
        return _connectedToPort;
    }

private:

    QStringList _portNames;
    bool _connectedToPort = false;

signals:

    void portNamesChanged(const QStringList &);
    void connectedToPortChanged(const bool &);

public slots:

    void connectToPort(const QString portName);
    void disconnectFromPort(const QString portName);

};
</code>```

SerialCom.cpp:

```<code>GuiLogic_SerialCom::GuiLogic_SerialCom(MasterGuiLogic *parent) : QObject(qobject_cast<QObject *>(parent))
{
    this->parent = parent;

    QList<QSerialPortInfo> allPorts = QSerialPortInfo::availablePorts();

    for (int i = 0; i < allPorts.size(); ++i) {
        this->_portNames.append(allPorts.at(i).portName());
        this->portsMap[allPorts.at(i).portName()] = allPorts.at(i);
    }

    emit portNamesChanged(_portNames);

}

void GuiLogic_SerialCom::connectToPort(const QString portName) {
    //TODO: Connect To Port Logic Here;

    //Set Connected
    this->_connectedToPort = true;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

void GuiLogic_SerialCom::disconnectFromPort(const QString portName) {
    //TODO: DisConnect To Port Logic Here;

    //Set DisConnected
    this->_connectedToPort = false;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}
</code>```

So from qml it's pretty easy to read any of these properties and even send signals from qml to c++

For example, this works just fine:

```<code>connectCom.onClicked: {
        if (MasterGuiLogic.serialCom.connectedToPort === false) {
            MasterGuiLogic.serialCom.connectToPort(comPort.currentText);
        } else {
            MasterGuiLogic.serialCom.disconnectFromPort(comPort.currentText);
        }
    }
</code>```

The problem is, I can't seem to find a way to connect to signals that are emitted from SerialCom. I thought I would be able to do something like this:

```<code>Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            if (MasterGuiLogic.serialCom.connectedToPort === false) {
                connectCom.text = "Disconnect";
                comPort.enabled = false;
            } else {
                connectCom.text = "Connect";
                comPort.enabled = true;
            }
        }
    }
</code>```

This should listen to the boolean property on SerialCom to change, but I get the following error:

```<code>QQmlApplicationEngine failed to load component
qrc:/QmlGui/main.qml:21 Type Page1 unavailable
qrc:/QmlGui/Page1.qml:49 Invalid attached object assignment
</code>```

This just means that I can't "connect" using the target line above. Is there any other way I can connect to signals from a Q_PROPERTY of type QObject inside a ContextProperty?

答:
First of all what should &(*MainGuiLogic) mean?
You are dereferencing and referencing again the MainGuiLogic? Why?

context->setContextProperty("MasterGuiLogic", MainGuiLogic); will be enought.

But registering MasterGuiLogic as Type and adding the Object named MasterGuiLogic can overide themself in QML world.

Set it like context->setContextProperty("MyGuiLogic", MainGuiLogic); to eleminate this behavior.

Also don't pass references between C++ and QML worlds like:

void connectedToPortChanged(**const bool &**);.

Just use atomic type and values (const bool);
and give it a name, to be able to use it as named value in QML:

void connectedToPortChanged(bool connected)

Here is an example with the structure like yours, which works. Just click in window and look in output console.

test.h:

```<code>#ifndef TEST_H
#define TEST_H

#include <QObject>

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
public:
    GuiLogic_SerialCom(){}

signals:
    void connectedToPortChanged(bool connected);

public slots:
    void connectToPort(const QString & portName);
};

class MasterGuiLogic : public QObject
{
    Q_OBJECT
public:
    MasterGuiLogic();

    Q_PROPERTY(GuiLogic_SerialCom * serialCom READ serialCom CONSTANT)
    GuiLogic_SerialCom* serialCom() const {return test;}

    Q_INVOKABLE void generate_signal();

private:
    GuiLogic_SerialCom * test;
};

#endif // TEST_H
</code>```

test.cpp:

```<code>#include "test.h"
#include <QDebug>

MasterGuiLogic::MasterGuiLogic()
{
    this->test = new GuiLogic_SerialCom();
}

void MasterGuiLogic::generate_signal()
{
    qDebug() << __FUNCTION__ << "Calling serialcom to gen signal";
    this->test->connectToPort("88");
}

void GuiLogic_SerialCom::connectToPort(const QString &portName)
{
    qDebug() << __FUNCTION__ << "got signal" << portName;
    emit this->connectedToPortChanged(true);
}
</code>```

main.cpp:

```<code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty(QStringLiteral("Test"), new MasterGuiLogic());

    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}
</code>```

main.qml:

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

import GrblCom 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            Test.generate_signal();
        }
    }

    Connections
    {
        target: Test.serialCom
        onConnectedToPortChanged:
        {
            console.log("Got signal from SerialCom in QML. passed bool value is: " + connected);
        }
    }
}
</code>```

Body:
So this may seem like a strange setup. I have a C++ object that inherits from QObject called "MasterGuiLogic" for simplicity. It is created with a pointer to another object called "MainEventBroker" which as you might guess handles all of my applications events. The MasterGuiLogic object is registered with qml as a context property so that it's properties can be used anywhere in my qml. So main.cpp looks like this:

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    MasterEventBroker *MainEventBroker = new MasterEventBroker();
    MasterGuiLogic *MainGuiLogic = new MasterGuiLogic(*MainEventBroker);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;
    QQmlContext* context = engine.rootContext();

    context->setContextProperty("MasterGuiLogic", &(*MainGuiLogic));

    engine.load(QUrl(QLatin1String("qrc:/QmlGui/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

MasterGuiLogic creates an instance of another class called SerialCom, which is set as a Q_PROPERTY so that it's properties and public slots can be reached in qml through the MasterGuiLogic property.

MasterGuiLogic.h:

class MasterGuiLogic : public QObject
{
    Q_OBJECT
    Q_PROPERTY(GuiLogic_SerialCom* serialCom READ serialCom CONSTANT)
public:
    MasterEventBroker *eventBroker;

    explicit MasterGuiLogic(MasterEventBroker &ev, QObject *parent = nullptr);

    GuiLogic_SerialCom* serialCom() const {
        return Gui_SerialCom;
    }

private:

    GuiLogic_SerialCom *Gui_SerialCom;

MasterGuiLogic.cpp:

MasterGuiLogic::MasterGuiLogic(MasterEventBroker &ev, QObject *parent) : QObject(parent)
{
    this->eventBroker = &ev;
    this->Gui_SerialCom = new GuiLogic_SerialCom(this);
}

SerialCom.h:

//Forward Declare our parent
class MasterGuiLogic;

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QStringList portNames READ portNames NOTIFY portNamesChanged)
    Q_PROPERTY(bool connectedToPort READ connectedToPort NOTIFY connectedToPortChanged)
public:

    MasterGuiLogic *parent;
    explicit GuiLogic_SerialCom(MasterGuiLogic *parent = nullptr);

    std::map<QString, QSerialPortInfo> portsMap;

    QStringList portNames() {
        return _portNames;
    }

    bool connectedToPort() {
        return _connectedToPort;
    }

private:

    QStringList _portNames;
    bool _connectedToPort = false;

signals:

    void portNamesChanged(const QStringList &);
    void connectedToPortChanged(const bool &);

public slots:

    void connectToPort(const QString portName);
    void disconnectFromPort(const QString portName);

};

SerialCom.cpp:

GuiLogic_SerialCom::GuiLogic_SerialCom(MasterGuiLogic *parent) : QObject(qobject_cast<QObject *>(parent))
{
    this->parent = parent;

    QList<QSerialPortInfo> allPorts = QSerialPortInfo::availablePorts();

    for (int i = 0; i < allPorts.size(); ++i) {
        this->_portNames.append(allPorts.at(i).portName());
        this->portsMap[allPorts.at(i).portName()] = allPorts.at(i);
    }

    emit portNamesChanged(_portNames);

}

void GuiLogic_SerialCom::connectToPort(const QString portName) {
    //TODO: Connect To Port Logic Here;

    //Set Connected
    this->_connectedToPort = true;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

void GuiLogic_SerialCom::disconnectFromPort(const QString portName) {
    //TODO: DisConnect To Port Logic Here;

    //Set DisConnected
    this->_connectedToPort = false;
    emit connectedToPortChanged(this->_connectedToPort);

    qDebug() << portName;
}

So from qml it's pretty easy to read any of these properties and even send signals from qml to c++

For example, this works just fine:

connectCom.onClicked: {
        if (MasterGuiLogic.serialCom.connectedToPort === false) {
            MasterGuiLogic.serialCom.connectToPort(comPort.currentText);
        } else {
            MasterGuiLogic.serialCom.disconnectFromPort(comPort.currentText);
        }
    }

The problem is, I can't seem to find a way to connect to signals that are emitted from SerialCom. I thought I would be able to do something like this:

Connections: {
        target: MasterGuiLogic.serialCom;
        onConnectedToPortChanged: {
            if (MasterGuiLogic.serialCom.connectedToPort === false) {
                connectCom.text = "Disconnect";
                comPort.enabled = false;
            } else {
                connectCom.text = "Connect";
                comPort.enabled = true;
            }
        }
    }

This should listen to the boolean property on SerialCom to change, but I get the following error:

QQmlApplicationEngine failed to load component
qrc:/QmlGui/main.qml:21 Type Page1 unavailable
qrc:/QmlGui/Page1.qml:49 Invalid attached object assignment

This just means that I can't "connect" using the target line above. Is there any other way I can connect to signals from a Q_PROPERTY of type QObject inside a ContextProperty?

Body:
First of all what should &(*MainGuiLogic) mean?
You are dereferencing and referencing again the MainGuiLogic? Why?

context->setContextProperty("MasterGuiLogic", MainGuiLogic); will be enought.

But registering MasterGuiLogic as Type and adding the Object named MasterGuiLogic can overide themself in QML world.

Set it like context->setContextProperty("MyGuiLogic", MainGuiLogic); to eleminate this behavior.

Also don't pass references between C++ and QML worlds like:

void connectedToPortChanged(**const bool &**);.

Just use atomic type and values (const bool);
and give it a name, to be able to use it as named value in QML:

void connectedToPortChanged(bool connected)

Here is an example with the structure like yours, which works. Just click in window and look in output console.

test.h:

#ifndef TEST_H
#define TEST_H

#include <QObject>

class GuiLogic_SerialCom : public QObject
{
    Q_OBJECT
public:
    GuiLogic_SerialCom(){}

signals:
    void connectedToPortChanged(bool connected);

public slots:
    void connectToPort(const QString & portName);
};

class MasterGuiLogic : public QObject
{
    Q_OBJECT
public:
    MasterGuiLogic();

    Q_PROPERTY(GuiLogic_SerialCom * serialCom READ serialCom CONSTANT)
    GuiLogic_SerialCom* serialCom() const {return test;}

    Q_INVOKABLE void generate_signal();

private:
    GuiLogic_SerialCom * test;
};

#endif // TEST_H

test.cpp:

#include "test.h"
#include <QDebug>

MasterGuiLogic::MasterGuiLogic()
{
    this->test = new GuiLogic_SerialCom();
}

void MasterGuiLogic::generate_signal()
{
    qDebug() << __FUNCTION__ << "Calling serialcom to gen signal";
    this->test->connectToPort("88");
}

void GuiLogic_SerialCom::connectToPort(const QString &portName)
{
    qDebug() << __FUNCTION__ << "got signal" << portName;
    emit this->connectedToPortChanged(true);
}

main.cpp:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "test.h"

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);

    qmlRegisterUncreatableType<MasterGuiLogic>("GrblCom", 1, 0, "MasterGuiLogic", "");
    qmlRegisterUncreatableType<GuiLogic_SerialCom>("GrblCom", 1, 0, "GuiLogic_SerialCom", "");

    QQmlApplicationEngine engine;

    engine.rootContext()->setContextProperty(QStringLiteral("Test"), new MasterGuiLogic());

    engine.load(QUrl(QLatin1String("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml:

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3

import GrblCom 1.0

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea
    {
        anchors.fill: parent
        onClicked:
        {
            Test.generate_signal();
        }
    }

    Connections
    {
        target: Test.serialCom
        onConnectedToPortChanged:
        {
            console.log("Got signal from SerialCom in QML. passed bool value is: " + connected);
        }
    }
}


来源: stackexchange

问:
is it a proper way to do php update?
here with the updated core. Is it a proper way to do it?
I try to do Prepared Statements by following the tutorial from the web, but not working well.

```<code>$Enrolsql = "Select * FROM Enrol WHERE ActivityID=$activityid AND UserPhone=$userPhone AND UseUp=1";

$Enrolresult = $conn->query($Enrolsql);
if ($Enrolresult->num_rows > 0) {

    $ssql = "UPDATE Enrol SET UseUp=0 WHERE ActivityID=$activityid";
    if (mysqli_query($conn, $ssql)) {
        echo "+1+"; //successfully Used.
    } else {
        echo "+2+"; // System Error.
    }
} else {
    echo "+0+"; // Coupon is not Vaild
}

$conn->close();
</code>```

Database Table info:

答:
According to http://php.net/manual/en/mysqli.query.php,

mysqli_query Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Given that you are running an UPDATE, and assuming the update didn't fail (just had no effect) you will be getting back TRUE hence you are printing +1+

ContentLicense: CC BY-SA 3.0

Title: is it a proper way to do php update?

Body:
here with the updated core. Is it a proper way to do it?
I try to do Prepared Statements by following the tutorial from the web, but not working well.

$Enrolsql = "Select * FROM Enrol WHERE ActivityID=$activityid AND UserPhone=$userPhone AND UseUp=1";

$Enrolresult = $conn->query($Enrolsql);
if ($Enrolresult->num_rows > 0) {

    $ssql = "UPDATE Enrol SET UseUp=0 WHERE ActivityID=$activityid";
    if (mysqli_query($conn, $ssql)) {
        echo "+1+"; //successfully Used.
    } else {
        echo "+2+"; // System Error.
    }
} else {
    echo "+0+"; // Coupon is not Vaild
}

$conn->close();

Database Table info:


问:
How to verify that an object transfer is complete
I want to send a message (a serializable object) from a java instance to another instance over a network. I would like to verify that the whole object has been sent correctly.

I suppose my first step is to calculate the checksum of the object. Then I include that checksum in the object OR build a container object for the message and its checksum.

Then my second step should be to verify the checksum against the object on the other side.

My third step would be for the receiver to send a confirmation message saying that the object in question was received and that the checksum has passed (or not). If I receive a failed checksum warning, I try to resend it a few times.

After a little while, if I never received a confirmation, I try to resend it a few times as well.

Questions :

Does my protocol sounds right to verify that an object was transferred correctly ?

I would also like to know how am I supposed to implement this in java ? Do I use the CRC32 class to generate the checksum ?

Bonus question : If I were to compress each message, do I generate the checksum before of after the compression, and how do I compress an object in java ?

答:
I agree with your steps, with one addition (this is what I do, over ObjectIO streams) -
[1] Read the incoming stuff as Object, find its class with "instanceof". If it is not the expected class, time to debug what is coming in.

In some other situations, I also send out Strings that contain info about the contents of the object to arrive next. Parse this string, read the object, typecast it, make sure it has what the info in the String said, and write out the confirmation :)

ContentLicense: CC BY-SA 2.5


问:
Binding 4 Radio buttons using @html.RadioButtonFor MVC4 ASP.Net
Here is my ENUM:

```<code>public enum ValidityTypes : int
{
    [Description("Not Set")]
    None = 0,
    [Description("Zero Validity")]
    ZeroValidity = 1,
    [Description("Life Time Validity")]
    LifeTimeValidity = 2,
    [Description("N Months")]
    NMonths = 3,
    [Description("Rehire Validity in Months")]
    RehireValidity = 4
}
</code>```

Here I set the Model property:

```<code>public ValidityTypes ValidityType { get; set; }
</code>```

Here is my View:

```<code><label><b>Zero Validity:</b></label>
@if (Model.ValidityType == Constant.ValidityTypes.ZeroValidity)
{
    @Html.RadioButtonFor(x => x.ValidityType, "1", new { @id = "validity1", style = "width:50px", @checked = "true" , onClick = "ValidityEnableDisable(this);" })
}
else
{
    @Html.RadioButtonFor(x => x.ValidityType, "1", new { @id = "validity1", style = "width:50px", @checked = "false" , onClick = "ValidityEnableDisable(this);" })
}
<label><b>Life Time Validity: </b></label>
@if (Model.ValidityType == OneC.BGV.BE.Constant.ValidityTypes.LifeTimeValidity)
{
    @Html.RadioButtonFor(x => x.ValidityType, "2", new { @id = "validity2", style = "width:50px", @checked = "true" , onClick = "ValidityEnableDisable(this);" })
}
else
{
    @Html.RadioButtonFor(x => x.ValidityType, "2", new { @id = "validity2", style = "width:50px", @checked = "false" , onClick = "ValidityEnableDisable(this);" })
}
<label><b>'N' Months:</label>
@if (Model.ValidityType == OneC.BGV.BE.Constant.ValidityTypes.NMonths)
{
    @Html.RadioButtonFor(x => x.ValidityType, "3", new { @id = "validity3", style = "width:50px", @checked = "true", onClick = "Validity3EnableDisable(this);" ,  autocomplete="off" })
    @Html.TextBoxFor(x => x.ValidityValue, new { id = "NmonthTextbox", style = "width:50px" })
}
else
{
    @Html.RadioButtonFor(x => x.ValidityType, "3", new { @id = "validity3", style = "width:50px", @checked = "false" , onClick = "Validity3EnableDisable(this);" ,  autocomplete="off"})
    @Html.TextBoxFor(x => x.ValidityValue, new { id = "NmonthTextbox", style = "width:50px", disabled = "true" })
}
</code>```

Now when I am loading this view I am getting model.Validitytype as ZeroValidity which is same as in the Database and satisfying the first if condition. But on complete view load the N months radio button is coming checked.

Why I am not able to show correct radio button selected?
Is it my @checked property of the control is not working?

答:
checked="true" or checked="false" or checked="anythingAtAll" all mean the same thing - the radio button will be checked. The checked attribute is a boolean attribute which means its the presence of it that determines if its checked. In your case the last one is always checked because that is the last one that is rendered (the attribute is removed from the previous ones because only one is allowed to be checked).

You should never set the checked attribute because the RadioButtonFor() method does that based on the value of the model you binding to (that is how model binding works). Remove all your if/else blocks and change the code to simply be

```<code><label>
    @Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.ZeroValidity, new { id = "", @class = "validity" })
    <span>Zero Validity</span>
</label>
<label>
    @Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.LifeTimeValidity, new { id = "", @class = "validity" })
    <span>Life Time Validity</span>
</label>
// labels below omitted for brevity
@Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.NMonths, new { id = "", @class = "validity" })
@Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.RehireValidity, new { id = "", @class = "validity" })
</code>```

Then use css to style your elements rather than inline styles, e.g.

```<code>.validity {
    width: 50px;
}
</code>```

and use Unobtrusive JavaScript to handle your events

```<code>$('.validity').click(function() {
    ....
});
</code>```

Body:
Here is my ENUM:

public enum ValidityTypes : int
{
    [Description("Not Set")]
    None = 0,
    [Description("Zero Validity")]
    ZeroValidity = 1,
    [Description("Life Time Validity")]
    LifeTimeValidity = 2,
    [Description("N Months")]
    NMonths = 3,
    [Description("Rehire Validity in Months")]
    RehireValidity = 4
}

Here I set the Model property:

public ValidityTypes ValidityType { get; set; }

Here is my View:

Zero Validity:
@if (Model.ValidityType == Constant.ValidityTypes.ZeroValidity)
{
    @Html.RadioButtonFor(x => x.ValidityType, "1", new { @id = "validity1", style = "width:50px", @checked = "true" , onClick = "ValidityEnableDisable(this);" })
}
else
{
    @Html.RadioButtonFor(x => x.ValidityType, "1", new { @id = "validity1", style = "width:50px", @checked = "false" , onClick = "ValidityEnableDisable(this);" })
}
Life Time Validity:
@if (Model.ValidityType == OneC.BGV.BE.Constant.ValidityTypes.LifeTimeValidity)
{
    @Html.RadioButtonFor(x => x.ValidityType, "2", new { @id = "validity2", style = "width:50px", @checked = "true" , onClick = "ValidityEnableDisable(this);" })
}
else
{
    @Html.RadioButtonFor(x => x.ValidityType, "2", new { @id = "validity2", style = "width:50px", @checked = "false" , onClick = "ValidityEnableDisable(this);" })
}
'N' Months:
@if (Model.ValidityType == OneC.BGV.BE.Constant.ValidityTypes.NMonths)
{
    @Html.RadioButtonFor(x => x.ValidityType, "3", new { @id = "validity3", style = "width:50px", @checked = "true", onClick = "Validity3EnableDisable(this);" ,  autocomplete="off" })
    @Html.TextBoxFor(x => x.ValidityValue, new { id = "NmonthTextbox", style = "width:50px" })
}
else
{
    @Html.RadioButtonFor(x => x.ValidityType, "3", new { @id = "validity3", style = "width:50px", @checked = "false" , onClick = "Validity3EnableDisable(this);" ,  autocomplete="off"})
    @Html.TextBoxFor(x => x.ValidityValue, new { id = "NmonthTextbox", style = "width:50px", disabled = "true" })
}

Now when I am loading this view I am getting model.Validitytype as ZeroValidity which is same as in the Database and satisfying the first if condition. But on complete view load the N months radio button is coming checked.

Why I am not able to show correct radio button selected?
Is it my @checked property of the control is not working?

Body:
checked="true" or checked="false" or checked="anythingAtAll" all mean the same thing - the radio button will be checked. The checked attribute is a boolean attribute which means its the presence of it that determines if its checked. In your case the last one is always checked because that is the last one that is rendered (the attribute is removed from the previous ones because only one is allowed to be checked).

You should never set the checked attribute because the RadioButtonFor() method does that based on the value of the model you binding to (that is how model binding works). Remove all your if/else blocks and change the code to simply be

<label>
    @Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.ZeroValidity, new { id = "", @class = "validity" })
    <span>Zero Validity</span>
</label>
<label>
    @Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.LifeTimeValidity, new { id = "", @class = "validity" })
    <span>Life Time Validity</span>
</label>
// labels below omitted for brevity
@Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.NMonths, new { id = "", @class = "validity" })
@Html.RadioButtonFor(x => x.ValidityType, ValidityTypes.RehireValidity, new { id = "", @class = "validity" })

Then use css to style your elements rather than inline styles, e.g.

.validity {
    width: 50px;
}

and use Unobtrusive JavaScript to handle your events

$('.validity').click(function() {
    ....
});


问:
Can I pass headers to an image source?
My image-source is secured, so ideally I would like to do the following:

```<code><Image source={{uri: "http://path/to/image",
                headers: {Authorization: 'Bearer ' + this.props.bearerToken}}}/>
</code>```

Is there anyway I can approximate that, short of loading the image into Javascript and rendering the image from there?

答:
React Native supports adding header or body in requesting image. UPDATED: See this.</p>
```<code> <Image source={{
      uri: 'https://facebook.github.io/react/img/logo_og.png',
      method: 'POST',
      headers: {
        Pragma: 'no-cache'
      },
      body: 'Your Body goes here'
    }}
    style={{width: 400, height: 400}} />
</code>```

Title: Can I pass headers to an image source?

Body:
My image-source is secured, so ideally I would like to do the following:

<Image source={{uri: "http://path/to/image",
                headers: {Authorization: 'Bearer ' + this.props.bearerToken}}}/>

Is there anyway I can approximate that, short of loading the image into Javascript and rendering the image from there?

Body:
React Native supports adding header or body in requesting image. UPDATED: See this.

 <Image source={{
      uri: 'https://facebook.github.io/react/img/logo_og.png',
      method: 'POST',
      headers: {
        Pragma: 'no-cache'
      },
      body: 'Your Body goes here'
    }}
    style={{width: 400, height: 400}} />

ContentLicense: CC BY-SA 4.0


问:
each function not working as expected
So what I try to do is the following:

I got some items in 3 columns and default positioning (position:static).
And I'm trying to transition them to top:0; left:0 of the page.
Transitions between different positions (absolute and static) are not possible in CSS3, so I tried a jQuery workaround:

```<code>$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});
</code>```

What this is supposed to do, is to take every item with class item and "duplicate" it at the exisiting position with position:absolute
This is working perfectly for one item. But as soon as I got multiple items, it simply stacks them at the position of the  first item...

Here's a fiddle:

$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}</code>```

1

2

3

4

4

```

My desired result is that jQuery takes every item, gets its position on the page, and replaces the CSS, so it's at the same position as before, just with position:absolute, so I can transition it to top:0;left:0; afterwards.

答:
It will always the same position if you use absolute ! Because you loop each item then apply it immediately so first div is changed to absolute and take it old position with top,left value .Then second div is not still change as absolute so it will also take first div position and duplicate with first div .This will continuing happen till loop end . So it all will have the same top,left value .

So my solution is not to apply css property immediately , store value in one helper object and applied that all property after finished loop .

var beforeApply = {}
$(".item").each(function(){
  var items = $(this);
  beforeApply[$(this).index()] = {
      'width': items.width(),
      'height': items.height(),
      'position':'absolute',
      'top': items.offset().top,
      'left': items.offset().left,
      'text':items.text()
  };
});

for(var j in beforeApply) {
     var index = parseInt(j) + 1;
     var text = beforeApply[j].text;
    $("#items div:nth-child("+index+")").css(beforeApply[j]).text(text + "Changed position");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}</code>```

1

2

3

4

4

```

Title: each function not working as expected

Body:
So what I try to do is the following:

I got some items in 3 columns and default positioning (position:static).
And I'm trying to transition them to top:0; left:0 of the page.
Transitions between different positions (absolute and static) are not possible in CSS3, so I tried a jQuery workaround:

$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});

What this is supposed to do, is to take every item with class item and "duplicate" it at the exisiting position with position:absolute
This is working perfectly for one item. But as soon as I got multiple items, it simply stacks them at the position of the  first item...

Here's a fiddle:

$(".item").each(function(){
  var items = $(this);
  $(this).css({
      'width': items.width(),
      'height': items.height(),
      'position': 'absolute',
      'top': items.offset().top,
      'left': items.offset().left
  });
});

#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}

1

2

3

4

4

My desired result is that jQuery takes every item, gets its position on the page, and replaces the CSS, so it's at the same position as before, just with position:absolute, so I can transition it to top:0;left:0; afterwards.

Body:
It will always the same position if you use absolute ! Because you loop each item then apply it immediately so first div is changed to absolute and take it old position with top,left value .Then second div is not still change as absolute so it will also take first div position and duplicate with first div .This will continuing happen till loop end . So it all will have the same top,left value .

So my solution is not to apply css property immediately , store value in one helper object and applied that all property after finished loop .

var beforeApply = {}
$(".item").each(function(){
  var items = $(this);
  beforeApply[$(this).index()] = {
      'width': items.width(),
      'height': items.height(),
      'position':'absolute',
      'top': items.offset().top,
      'left': items.offset().left,
      'text':items.text()
  };
});

for(var j in beforeApply) {
     var index = parseInt(j) + 1;
     var text = beforeApply[j].text;
    $("#items div:nth-child("+index+")").css(beforeApply[j]).text(text + "Changed position");
}

#items{
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    column-count: 3;
    column-gap: 10px;
}
.item{
    width:100%;
    height:20px;
    text-align:center;
    overflow:hidden;
    margin:0 0 10px 0;
    border:1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="items">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">4</div>
</div>


问:
Comma Separated selector in Jquery
I came across the following code in JQuery which I'm not familiar with

```<code>$('*[name=\'' + child.Name + '\'],[id=\'' + child.ID + '\']');
</code>```

I have two different divs(different IDs) containing two input elements with same name. When I pass the name and ID to the above query, I get both the input elements.

I found this on Stack Overflow, but if what is mentioned there is correct, I should be getting the element with in the div which I pass.

I want to know how this would work:

```<code>$('[name=""],[id=""]');
</code>```

Thanks in Advance.

答:
This is described in the jQuery documentation on Multiple Selector:

Multiple Selector (“selector1, selector2, selectorN”)

  Description: Selects the combined results of all the specified selectors.

The other question you linked to is about the syntax:

```<code>$("selector1", "selector2")
</code>```

That's an example of the jQuery(selector, context) syntax described here, which is equivalent to jQuery(context).find(selector).

Title: Comma Separated selector in Jquery

Body:
I came across the following code in JQuery which I'm not familiar with

$('*[name=\'' + child.Name + '\'],[id=\'' + child.ID + '\']');

I have two different divs(different IDs) containing two input elements with same name. When I pass the name and ID to the above query, I get both the input elements.

I found this on Stack Overflow, but if what is mentioned there is correct, I should be getting the element with in the div which I pass.

I want to know how this would work:

$('[name=""],[id=""]');

Thanks in Advance.

Body:
This is described in the jQuery documentation on Multiple Selector:

Multiple Selector (“selector1, selector2, selectorN”)

  Description: Selects the combined results of all the specified selectors.

The other question you linked to is about the syntax:

$("selector1", "selector2")

That's an example of the jQuery(selector, context) syntax described here, which is equivalent to jQuery(context).find(selector).


问:
Finding a function definition using a call in C++
I'm trying to understand the source code of a fairly large C++ project.  The source wasn't written with an IDE, so I don't have a "goto" button to go straight to the function definition.

For example:

```<code>srand();
</code>```

I want to find out exactly where the function srand() is defined.

The only method I can come up with is manually checking all the header includes to recursively find the declaration and the corresponding file for the definition.

This is a linux environment and the source is compiled with g++ (using cmake).

答:
Look into the ctags program.

ctags generates a file with information on the locations in the code where each identifier is used. It is then possible to use a plugin for your editor of choice that will allow you to jump to the definition of any identifier. (very mature ctags plugins exist for Vim and Emacs, and probably for most other popular editors as well.)

Body:
I'm trying to understand the source code of a fairly large C++ project.  The source wasn't written with an IDE, so I don't have a "goto" button to go straight to the function definition.

For example:

srand();

I want to find out exactly where the function srand() is defined.

The only method I can come up with is manually checking all the header includes to recursively find the declaration and the corresponding file for the definition.

This is a linux environment and the source is compiled with g++ (using cmake).


问:
Create new column to identify the first value >0 across different columns
I have the following data frame

```<code>df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col2 = c(1,0,0,3))
</code>```

How can I identify the the first value of each value which is greater than 0.
The expected output is like this

```<code>df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col3 = c(1,0,0,3),col4 = c(1,0,1,1))
</code>```

And I have tried the followings

```<code>for (i in 1:3){
  df$col4 <- apply(df[,c(0:i)],1,sum)
  if (df$col4>0)
    break
  }
</code>```

答:
Here is another idea using mapply,

```<code>unlist(mapply(`[`, split(df, 1:nrow(df)), max.col(df>0, ties.method = 'first')))
#1.col2 2.col1 3.col1 4.col1
#     1      0      1      1
</code>```

Depending on what you need by 'count backward', you can either change ties.method to 'last', i.e.

```<code>unlist(mapply(`[`, split(df, 1:nrow(df)), max.col(df>0, ties.method = 'last')))
#1.col2.1 2.col2.1   3.col1 4.col2.1
#       1        0        1        3
</code>```

Or reverse the data frame and leave ties.method to 'first', i.e.

```<code>unlist(mapply(`[`, split(rev(df), 1:nrow(df)), max.col(df>0, ties.method = 'first')))
#  1.col2 2.col2.1 3.col2.1 4.col2.1
#       1        0        0        3
</code>```

Body:
I have the following data frame

df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col2 = c(1,0,0,3))

How can I identify the the first value of each value which is greater than 0.
The expected output is like this

df <- data.frame(col1 = c(0,0,1,1),col2 = c(1,0,0,3),col3 = c(1,0,0,3),col4 = c(1,0,1,1))

And I have tried the followings

for (i in 1:3){
  df$col4 <- apply(df[,c(0:i)],1,sum)
  if (df$col4>0)
    break
  }

Body:
Here is another idea using mapply,

unlist(mapply(`[`, split(df, 1:nrow(df)), max.col(df>0, ties.method = 'first')))
#1.col2 2.col1 3.col1 4.col1
#     1      0      1      1

Depending on what you need by 'count backward', you can either change ties.method to 'last', i.e.

unlist(mapply(`[`, split(df, 1:nrow(df)), max.col(df>0, ties.method = 'last')))
#1.col2.1 2.col2.1   3.col1 4.col2.1
#       1        0        1        3

Or reverse the data frame and leave ties.method to 'first', i.e.

unlist(mapply(`[`, split(rev(df), 1:nrow(df)), max.col(df>0, ties.method = 'first')))
#  1.col2 2.col2.1 3.col2.1 4.col2.1
#       1        0        0        3


问:
How to apply combination fields validation using jquery
I my requirement form is generated dynamically. there are number of fields

```<code><tr>
    <td >Coding Guidelines</td>
    <td align="center">
     <select name="SELECT_TASK_1" id="SELECT_TASK_1">
       <option value="">Select</option>
       <option value="Y">Yes</option>
       <option value="N">No</option>
     </select>
   </td>
   <td align="center"><input type="text" size="10" name="COMP_DATE_1"></td>
  <td align="left"> <textarea name="COMMENT_TASK_1" id="COMMENT_TASK_1"
             cols="45" rows="4"></textarea><span id="COMMENT_ERROR_1" > </span>
   </td>
</tr>
</code>```

there are number of TR generated base on DB rows. I want apply jquery validation on the combination of select No value and Comment field.

That means if select is No then comment is mandatory field.

Please help how to apply validation using Jquery validation plugin

答:
Here is a solution (though not very optimised):</p>

```<code><table>
    <tr>
        <td>
            <select>
                <option value="0">select</option>
                <option value="1">yes</option>
                <option value="2">no</option>
            </select>
        </td>
        <td>
            <textarea cols="10" rows="3"></textarea>
            <span id="COMMENT_ERROR_1"></span>
        </td>
    </tr>
    <tr>
        <td>
            <select>
                <option value="0">select</option>
                <option value="1">yes</option>
                <option value="2">no</option>
            </select>
        </td>
        <td>
            <textarea cols="10" rows="3"></textarea>
            <span id="COMMENT_ERROR_1"></span>
        </td>
    </tr>
</table>
<input type="button" id="validate" value="validate"/>

<script type="text/javascript">
$(function(){
    $("#validate").click(function(){
        $.each($("select"),function(){
            var n=$("option:selected",this).text();
            if(n=="no")
            {
                var $txt=$("textarea",$(this).closest("tr"));
                if($txt.text()=="")
                {
                    var $sp=$txt.parent().find("span");
                    $sp.text("Enter comment");
                }
                else
                {
                    var $sp=$txt.parent().find("span");
                    $sp.text("Enter comment");
                }
            }
        });
    });
});
</script>
</code>```

Body:
I my requirement form is generated dynamically. there are number of fields

    Coding Guidelines

     <select name="SELECT_TASK_1" id="SELECT_TASK_1">
       <option value="">Select</option>
       <option value="Y">Yes</option>
       <option value="N">No</option>
     </select>

   <input type="text" size="10" name="COMP_DATE_1">
   <textarea name="COMMENT_TASK_1" id="COMMENT_TASK_1"
             cols="45" rows="4"></textarea>

there are number of TR generated base on DB rows. I want apply jquery validation on the combination of select No value and Comment field.

That means if select is No then comment is mandatory field.

Please help how to apply validation using Jquery validation plugin

Body:
Here is a solution (though not very optimised):

<table>
    <tr>
        <td>
            <select>
                <option value="0">select</option>
                <option value="1">yes</option>
                <option value="2">no</option>
            </select>
        </td>
        <td>
            <textarea cols="10" rows="3"></textarea>
            <span id="COMMENT_ERROR_1"></span>
        </td>
    </tr>
    <tr>
        <td>
            <select>
                <option value="0">select</option>
                <option value="1">yes</option>
                <option value="2">no</option>
            </select>
        </td>
        <td>
            <textarea cols="10" rows="3"></textarea>
            <span id="COMMENT_ERROR_1"></span>
        </td>
    </tr>
</table>
<input type="button" id="validate" value="validate"/>

<script type="text/javascript">
$(function(){
    $("#validate").click(function(){
        $.each($("select"),function(){
            var n=$("option:selected",this).text();
            if(n=="no")
            {
                var $txt=$("textarea",$(this).closest("tr"));
                if($txt.text()=="")
                {
                    var $sp=$txt.parent().find("span");
                    $sp.text("Enter comment");
                }
                else
                {
                    var $sp=$txt.parent().find("span");
                    $sp.text("Enter comment");
                }
            }
        });
    });
});
</script>


问:
Is there a Java utility which will convert a String path to use the correct File separator char?
I have developed a number of classes which manipulate files in Java. I am working on a Linux box, and have been blissfully typing new File("path/to/some/file");. When it came time to commit I realised some of the other developers on the project are using Windows. I would now like to call a method which can take in a String of the form "/path/to/some/file" and, depending on the OS, return a correctly separated path.

For example:

"path/to/some/file" becomes "path\\to\\some\\file" on Windows.

On Linux it just returns the given String.

I realise it wouldn't take long to knock up a regular expression that could do this, but I'm not looking to reinvent the wheel, and would prefer a properly tested solution. It would be nice if it was built in to the JDK, but if it's part of some small F/OSS library that's fine too.

So is there a Java utility which will convert a String path to use the correct File separator char?

答:
```<code>String fileName = Paths.get(fileName).toString();
</code>```

Works perfectly with Windows at least even with mixed paths, for example

c:\users\username/myproject\myfiles/myfolder

becomes

```<code>c:\users\username\myproject\myfiles\myfolder
</code>```

Sorry haven't check what Linux would make of the above but there again Linux file structure is different so you wouldn't search for such a directory

Body:
String fileName = Paths.get(fileName).toString();

Works perfectly with Windows at least even with mixed paths, for example

c:\users\username/myproject\myfiles/myfolder

becomes

c:\users\username\myproject\myfiles\myfolder

Sorry haven't check what Linux would make of the above but there again Linux file structure is different so you wouldn't search for such a directory


问:
AttributeError: module 'matplotlib' has no attribute 'plot'
I am using python 3.6 and a learner.  Below is a simple code of a sin wave.

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10 , 10, 100)
y = np.sin(x)
plt.plot(x, y, marker="x")
</code>```

I am receiving the error "AttributeError: module 'matplotlib' has no attribute 'plot'"  Any help would be appreciated.

答:
Have you installed matplotlib properly? I added an extra line to your code to show the plot. This code works properly in Visual Studio after installing the matplotlib library.</p>

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10 , 10, 100)
y = np.sin(x)
plt.plot(x, y, marker="x")
plt.show()
</code>```

Body:
I am using python 3.6 and a learner.  Below is a simple code of a sin wave.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10 , 10, 100)
y = np.sin(x)
plt.plot(x, y, marker="x")

I am receiving the error "AttributeError: module 'matplotlib' has no attribute 'plot'"  Any help would be appreciated.

Body:
Have you installed matplotlib properly? I added an extra line to your code to show the plot. This code works properly in Visual Studio after installing the matplotlib library.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-10 , 10, 100)
y = np.sin(x)
plt.plot(x, y, marker="x")
plt.show()


问:
How can I remove tailing white space while loading data from CSV file into an Postgres Table?
I want to remove the trailing whitespaces from CSV file.

Sample CSV file Data:(Delimitor=";")

X ;Y;Z

X1  ; Y1;Z1

X2;Y2; Z2

I would have gone for something like SED or GREP but the file size is huge so it may impact the performance because of preprocessing.

I am looking for a way to remove these whites spaces at the time of loading only.

答:
COPY command does not support preprocessing - you can't do it "at the time of loading "

https://www.postgresql.org/docs/current/static/sql-copy.html

In CSV format, all characters are significant. A quoted value
  surrounded by white space, or any characters other than DELIMITER,
  will include those characters. This can cause errors if you import
  data from a system that pads CSV lines with white space out to some
  fixed width. If such a situation arises you might need to preprocess
  the CSV file to remove the trailing white space, before importing the
  data into PostgreSQL.

I think here the best solution would be importing data with spaces and then

```<code>update t set attr = rtim(attr);
</code>```

Body:
COPY command does not support preprocessing - you can't do it "at the time of loading "

https://www.postgresql.org/docs/current/static/sql-copy.html

In CSV format, all characters are significant. A quoted value
  surrounded by white space, or any characters other than DELIMITER,
  will include those characters. This can cause errors if you import
  data from a system that pads CSV lines with white space out to some
  fixed width. If such a situation arises you might need to preprocess
  the CSV file to remove the trailing white space, before importing the
  data into PostgreSQL.

I think here the best solution would be importing data with spaces and then

update t set attr = rtim(attr);


问:
Is C++11 is faster than C++03 in terms of efficiency?
I work in trading firm and here latency matters a lot. The project assigns to me is developed using a mix of c and c++98 parts, But I believe we can make same project using C++11 without losing efficiency. As discussed with my seniors, they say you should stick with C and c++03 as they are efficient compare to C++11 at micro level.
Can anyone highlight me If I go with C++11, will I get better results?</p>

答:
This is mostly wrong.

Firstly, if you give C++03 compliant source to a compiler like GCC, it is very unlikely that the generated machine code will be any different if you specify --std=c++03 compared to --std=c++11.

Secondly, using features like auto and "range based for" will be neutral for efficiency.  (There may be a few cases where Range-based-for will allow the compiler to optimize the evaluation of the termination condition more efficiently than a naive loop, but these will be rare.)

Thirdly, there are some features (like move semantics) which are actively beneficial for efficiency.

Finally, there are a few cases where naively written C++11 will be less efficient than the equivalent C++03 code.  For example:

```<code>std::vector<std::vector<big_struct>> big_2d_array;
for (auto v : big_2d_array)
    do_stuff(v);
</code>```

This will copy v and will be expensive.  It needs to be:

```<code>for (auto &v : big_2d_array)
    do_stuff(v);
</code>```

Note the reference.  (I would also recommend const, but that's a separate issue).

Body:
This is mostly wrong.

Firstly, if you give C++03 compliant source to a compiler like GCC, it is very unlikely that the generated machine code will be any different if you specify --std=c++03 compared to --std=c++11.

Secondly, using features like auto and "range based for" will be neutral for efficiency.  (There may be a few cases where Range-based-for will allow the compiler to optimize the evaluation of the termination condition more efficiently than a naive loop, but these will be rare.)

Thirdly, there are some features (like move semantics) which are actively beneficial for efficiency.

Finally, there are a few cases where naively written C++11 will be less efficient than the equivalent C++03 code.  For example:

std::vector<std::vector<big_struct>> big_2d_array;
for (auto v : big_2d_array)
    do_stuff(v);

This will copy v and will be expensive.  It needs to be:

for (auto &v : big_2d_array)
    do_stuff(v);

Note the reference.  (I would also recommend const, but that's a separate issue).


问:
How to transform an xml file by searching for some nodes and replacing the values
This is the input xml -

```<code><payload id="001">
    <termsheet>
          <format>PDF</format>
          <city>New York</city>
    </termsheet>
</payload>
</code>```

We are using Xalan for most of our xml transformations and we are on XSLT 1.0
I want to write a XSLT template which would convert the input to the below output  -

```<code><payload id="001">
    <termsheet>
          <format>pdf</format>
          <city>Mr. ABC</city>
    </termsheet>
</payload>
</code>```

I tried lot of answers on SO, but can't get around this problem.

Apologies for not being clear, toLower was an over simplification. I want to use the city name and invoke a java method which will return a business contact from that city. I have updated the original question

答:
I think that the simplest way is to use java extension with Xalan, you can write a simple java class  that implements the business logic you need, and then call it from your xslt. The stylesheet is quite simple

```<code> <xsl:stylesheet version="1.0"
    xmlns:java="http://xml.apache.org/xalan/java"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="java">

    <xsl:template match='node() | @*'>
        <xsl:copy>
            <xsl:apply-templates select ='node()|@*'></xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="termsheet/city">
        <xsl:copy>
            <xsl:value-of select='java:org.example.Card.getName(.)'/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>
</code>```

you also neeed to write the java class invoked

```<code>package org.example

public class Card {

  public static String getName(String id) {
     // put here your code to get what you need
     return "Mr. ABC"
  }
}
</code>```

there are other ways to do that and you should really give an eye to the documentation about xalan extensions

Body:
This is the input xml -

<payload id="001">
    <termsheet>
          <format>PDF</format>
          <city>New York</city>
    </termsheet>
</payload>

We are using Xalan for most of our xml transformations and we are on XSLT 1.0
I want to write a XSLT template which would convert the input to the below output  -

<payload id="001">
    <termsheet>
          <format>pdf</format>
          <city>Mr. ABC</city>
    </termsheet>
</payload>

I tried lot of answers on SO, but can't get around this problem.

Apologies for not being clear, toLower was an over simplification. I want to use the city name and invoke a java method which will return a business contact from that city. I have updated the original question

Body:
I think that the simplest way is to use java extension with Xalan, you can write a simple java class  that implements the business logic you need, and then call it from your xslt. The stylesheet is quite simple

 <xsl:stylesheet version="1.0"
    xmlns:java="http://xml.apache.org/xalan/java"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="java">

    <xsl:template match='node() | @*'>
        <xsl:copy>
            <xsl:apply-templates select ='node()|@*'></xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="termsheet/city">
        <xsl:copy>
            <xsl:value-of select='java:org.example.Card.getName(.)'/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

you also neeed to write the java class invoked

package org.example

public class Card {

  public static String getName(String id) {
     // put here your code to get what you need
     return "Mr. ABC"
  }
}

there are other ways to do that and you should really give an eye to the documentation about xalan extensions


问:
setting font for a project
currently practicing making an application using android studio.
I have this customized font and saved into res/font directory for the later use.
Inside the activity, i am trying to call getfont(R.font.my_customized_font) with the typeface object. ex) Typeface font = getResources().getfont(R.font.mycustomizedfont)

However, when i try to run the project with the actual device which has the API level 24, it won't activate since the getfont() method requires the min sdk level with 26.

I know that you can set the font of text view in the xml file by doing android:fontfamily but i am using the textswitcher instead of textview.

Emulator works fine by setting up min sdk with 26 but I would like to figure this out by using the actual device.

I found the solution by reading through the developer's website
I just added Typeface font = ResourcesCompat.getfont(context, R.font.mycustomizedfont)

答:
I use a Min API of 21 and this works for me:

```<code>Typeface type = Typeface.createFromAsset(getAssets(),"fonts/mycustomizedfont");
</code>```

Then, to set the font to a the child TextViews:

```<code>text_view.setTypeface(type);
</code>```

Hope this helps!

Title: setting font for a project

Body:
I use a Min API of 21 and this works for me:

Typeface type = Typeface.createFromAsset(getAssets(),"fonts/mycustomizedfont");

Then, to set the font to a the child TextViews:

text_view.setTypeface(type);

Hope this helps!


问:
How to stretch the table to fill all available space
This question might be simple, but I cannot find an answer.

I have the following html:

```<code><div>
  some text
  <div>
    <table>
        <tr><td>
            Test
        </tr>
    </table>
  </div>
</div>
</code>```

and css:

```<code>body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}

table {
    height: 100%;
    margin: 0 auto;
    background: red;
}
</code>```

How can I stretch the table vertically without change of the height property of div? I want the table to have height: 100% but it does not work because the outer containers do not have a fixed height (as I understand).

http://jsfiddle.net/8qedxug9/

答:
To change height property to always have 100% of window height you should use view height CSS unit like this:

body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}

table {
    height: 95vh;
    margin: 0 auto;
    background: red;
    width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  some text
  <div>
    <table>
        <tr><td>
            Test
        </tr>
    </table>
  </div>
</div></code>```

Body:
This question might be simple, but I cannot find an answer.

I have the following html:

  some text

            Test

and css:

body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}

table {
    height: 100%;
    margin: 0 auto;
    background: red;
}

How can I stretch the table vertically without change of the height property of div? I want the table to have height: 100% but it does not work because the outer containers do not have a fixed height (as I understand).

http://jsfiddle.net/8qedxug9/

Body:
To change height property to always have 100% of window height you should use view height CSS unit like this:

body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}

table {
    height: 95vh;
    margin: 0 auto;
    background: red;
    width: 100%;
}

<div>
  some text
  <div>
    <table>
        <tr><td>
            Test
        </tr>
    </table>
  </div>
</div>


问:
Upload form field file using redux saga call
I am uploading a file in the body as form-data. Using ajax it works fine but when I try to do the same in redux-saga, it does not work and fails. What am I doing wrong?

In ajax,

```<code>let upload = ajax.post(PathHelper.apiPath + '/create/text').field('file', file);
    upload.end((err, response) => {
      if (err) {
        console.log('Error Encountered', err);
      }
      if (response) {
        const imageResponse = response.body;
        console.log('imageresponse: ', imageResponse);
      }
    });
</code>```

Here is my saga code:

```<code>export function* fetchText(text) {
const formData = new FormData();
  formData.append('file', text.data);
  console.log('formData: ', formData);
  try {
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formData
    };
    const response = yield call(fetchJson, PathHelper.apiPath + '/create/text', options);
    console.log('response: ', response);

  } catch (err) {
    console.log('Error saving your image', err);
  }
 }
</code>```

答:
when I try to do the same in redux-saga, it does not work and fails

Redux-saga itself is about perform asynchronous action, fired on some redux event, so firstly, maybe put action is omitted - usually saga intercepts request-like action and creates success action after operation is completed. In that case, there should be redux-reducer, which will accept API call result and apply it somethere on UI component.

Secondly, uploading files requires live HTML form with enctype="multipart/form-data", and FormData object should be attached to original form. See details here: http://researchhubs.com/post/computing/javascript/upload-files-with-ajax.html

Body:
I am uploading a file in the body as form-data. Using ajax it works fine but when I try to do the same in redux-saga, it does not work and fails. What am I doing wrong?

In ajax,

let upload = ajax.post(PathHelper.apiPath + '/create/text').field('file', file);
    upload.end((err, response) => {
      if (err) {
        console.log('Error Encountered', err);
      }
      if (response) {
        const imageResponse = response.body;
        console.log('imageresponse: ', imageResponse);
      }
    });

Here is my saga code:

export function* fetchText(text) {
const formData = new FormData();
  formData.append('file', text.data);
  console.log('formData: ', formData);
  try {
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formData
    };
    const response = yield call(fetchJson, PathHelper.apiPath + '/create/text', options);
    console.log('response: ', response);

  } catch (err) {
    console.log('Error saving your image', err);
  }
 }


问:
How to get all HTML elements 500px below viewport using Javascript
I am trying to get all the HTML elements(div with particular id) which are there 500px below viewport on the page. I want to have this on scroll event.

```<code>    var windowHeight = window.outerHeight;
    var gridTop = windowHeight + 500;
    var elements = document.getElementsByClassName('test');
    window.addEventListener('scroll', function () {
        for (let i = 0; i < elements.length; i++) {
            var thisTop = elements[i].offsetTop - document.body.scrollTop;
            if (thisTop >= gridTop) {
                console.log('hi');
            }
        }
    });
</code>```

I need help on finding elements 500px below viewport.

EDIT:
I want to do it with pure JavaScript and I am using above code. But every time I am getting thisTop as 0. Please let me know the approach to do this.

答:
Check following solution, here I put parent div which is scrollable.

Note- I have put offset of 50px, in order to support the example.

var parent = document.documentElement

var elements = document.getElementsByClassName('test');
var gridTop = parent.clientHeight + 50;

window.addEventListener('scroll', function() {
   var printStr = "";
  for (let i = 0; i < elements.length; i++) {
    var thisTop = elements[i].offsetTop - parent.scrollTop;

    if (thisTop >= gridTop) {
      printStr += " "+elements[i].id
    }
  }
  console.clear();
  console.log('selected ', printStr);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container div {
  width: 40px;
  height: 70px;
  margin: 5px;
  background-color: red;
  text-align: center;
}</code>```

1

2

3

4

5

6

7

8

9

10

11

12

```

Body:
I am trying to get all the HTML elements(div with particular id) which are there 500px below viewport on the page. I want to have this on scroll event.

    var windowHeight = window.outerHeight;
    var gridTop = windowHeight + 500;
    var elements = document.getElementsByClassName('test');
    window.addEventListener('scroll', function () {
        for (let i = 0; i < elements.length; i++) {
            var thisTop = elements[i].offsetTop - document.body.scrollTop;
            if (thisTop >= gridTop) {
                console.log('hi');
            }
        }
    });

I need help on finding elements 500px below viewport.

EDIT:
I want to do it with pure JavaScript and I am using above code. But every time I am getting thisTop as 0. Please let me know the approach to do this.

Body:
Check following solution, here I put parent div which is scrollable.

Note- I have put offset of 50px, in order to support the example.

var parent = document.documentElement

var elements = document.getElementsByClassName('test');
var gridTop = parent.clientHeight + 50;

window.addEventListener('scroll', function() {
   var printStr = "";
  for (let i = 0; i < elements.length; i++) {
    var thisTop = elements[i].offsetTop - parent.scrollTop;

    if (thisTop >= gridTop) {
      printStr += " "+elements[i].id
    }
  }
  console.clear();
  console.log('selected ', printStr);
});

.container div {
  width: 40px;
  height: 70px;
  margin: 5px;
  background-color: red;
  text-align: center;
}

<div class="container">
  <div class="test" id="1">1</div>
  <div class="test" id="2">2</div>
  <div class="test" id="3">3</div>
  <div class="test" id="4">4</div>
  <div class="test" id="5">5</div>
  <div class="test" id="6">6</div>
  <div class="test" id="7">7</div>
  <div class="test" id="8">8</div>
  <div class="test" id="9">9</div>
  <div class="test" id="10">10</div>
  <div class="test" id="11">11</div>
  <div class="test" id="12">12</div>
</div>


问:
Building new website on old domain name. How should I redirect the old site?
I recently moved a website to another domain, but I am keeping the original domain for a future website. The recently moved website is permanently moved, but I only want traffic to be redirected temporarily to the other domain.

I have read countless 301 vs 302 posts, articles, etc. and have failed to find any that address this particular situation. And no one answered this similar question:

Moving to a new domain and using the old one for a new website - how to handle 301 redirects?

But the difference with my question is: I don't even know that I should be using a 301 redirect for this. What's the best way to handle this situation in general?

答: Here's a link that you may find helpful. You can also redirect with 308 status code also as @István Rábel suggested</p>


问:
Fade In With data on AngularJS
I want to show my post->id with fade in, I was try to search but I can't find it. Please Help me!!!

*forgive me if I have bad language

答:
In Angularjs, You wanna start working with basic animation stuff, you can know the Animation.

Basic fade out Example:

HTML:

```<code><div ng-controller="myCtrl">
<button ng-click="hideStuff()">Click me!</button>
<div class="default" ng-hide="hidden" ng-class="{fade:
    startFade}">This will get hidden!</div>
</div>
</code>```

CSS:

```<code>.default{
    opacity: 1;
}

 .fade{
      -webkit-transition: opacity 2s; /* For Safari 3.1 to 6.0 */
       transition: opacity 2s;
       opacity: 0;
 }
</code>```

Angular:

```<code>var myApp = angular.module('myApp',[]);

myApp.controller("myCtrl", function($scope, $timeout){
    $scope.hideStuff = function () {
        $scope.startFade = true;
        $timeout(function(){
            $scope.hidden = true;
        }, 2000);

    };

});
</code>```

Title: Fade In With data on AngularJS

Body:
In Angularjs, You wanna start working with basic animation stuff, you can know the Animation.

Basic fade out Example:

HTML:

<div ng-controller="myCtrl">
<button ng-click="hideStuff()">Click me!</button>
<div class="default" ng-hide="hidden" ng-class="{fade:
    startFade}">This will get hidden!</div>
</div>

CSS:

.default{
    opacity: 1;
}

 .fade{
      -webkit-transition: opacity 2s; /* For Safari 3.1 to 6.0 */
       transition: opacity 2s;
       opacity: 0;
 }

Angular:

var myApp = angular.module('myApp',[]);

myApp.controller("myCtrl", function($scope, $timeout){
    $scope.hideStuff = function () {
        $scope.startFade = true;
        $timeout(function(){
            $scope.hidden = true;
        }, 2000);

    };

});


问:
Can I use aggregate expressions using SQLAlchemy?
PostgreSQL have aggregate expressions, e.g. count(*) FILTER (WHERE state = 'success').  How can I generate such expressions using SQLAlchemy?

答:
Suppose I have a model Machine with a boolean field active, and would like to filter the count by active = true

Using func.count(...).filter(...)

```<code>from models import db, Machine
from sqlalchemy.sql import func

query = db.session.query(
    func.count(Machine.id).filter(Machine.active == True)
    .label('active_machines')
)
</code>```

We can look at the generated SQL query:

```<code>>>> print(query)
SELECT count(machine.id) FILTER (WHERE machine.active = true) AS active_machines
FROM machine
</code>```

This should work the same for the other aggregate functions like func.avg, func.sum, etc

Longer syntax using funcfilter(count(...), filter)

func.count(Machine.id).filter(Machine.active == True) is short hand for:

```<code>from sqlalchemy import funcfilter

funcfilter(func.count(Machine.id), Machine.active == True)
</code>```

Body:
Suppose I have a model Machine with a boolean field active, and would like to filter the count by active = true

Using func.count(...).filter(...)

from models import db, Machine
from sqlalchemy.sql import func

query = db.session.query(
    func.count(Machine.id).filter(Machine.active == True)
    .label('active_machines')
)

We can look at the generated SQL query:

>>> print(query)
SELECT count(machine.id) FILTER (WHERE machine.active = true) AS active_machines
FROM machine

This should work the same for the other aggregate functions like func.avg, func.sum, etc

Longer syntax using funcfilter(count(...), filter)

func.count(Machine.id).filter(Machine.active == True) is short hand for:

from sqlalchemy import funcfilter

funcfilter(func.count(Machine.id), Machine.active == True)


问:
Displaying data into HTML Tables
I am able to display my data from db. I want to display in a table under tabs but then my data appears crooked. The rows are not straight. why is that happening to the table?

it is arranged kind of this way.

the updated code below doesn't provide the right format for the table
Table

```<code>  id  name
     1    James
    4   Michel
   2  Jonathan
</code>```

HTML

```<code><div class="row">
    <div class="col-md-7">

        <div class="nav-tabs-custom">
            <ul class="nav nav-tabs">
                @foreach($items as $item)
                    <li><a href="#tab_{{ $item->id }}" data-toggle="tab" >{!!$item->name!!}</a></li>
                @endforeach
            </ul>
            <div class="tab-content">
                @foreach($items as $item)
                    <div class="tab-pane active" id="tab_{{ $item->id }}">
                        @foreach($item->products as $product)
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>No#</th>
                                        <th>Name</th>
                                        <th>Action</th>
                                    </tr>
                               </thead>
                               <tbody>
                                    <tr>
                                        <td>{{$product->id }}</td>
                                        <td>{{ $product->name}}</td>
                                    </tr>
                                </tbody>
                            </table>
                        @endforeach
                    </div>
                @endforeach
            </div>
        </div>
    </div>
</code>```

Updated Code

Update

```<code><div class="row">
    <div class="col-md-7">

        <div class="nav-tabs-custom">
            <ul class="nav nav-tabs">
                @foreach($items as $item)
                    <li><a href="#tab_{{ $item->id }}" data-toggle="tab" >{!!$item->name!!}</a></li>
                @endforeach
            </ul>
            <div class="tab-content">
                @foreach($items as $item)
                    <div class="tab-pane active" id="tab_{{ $item->id }}">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>No#</th>
                                        <th>Name</th>
                                        <th>Action</th>
                                    </tr>
                               </thead>
                               <tbody>
                        @foreach($item->products as $product)

                                    <tr>
                                        <td>{{$product->id }}</td>
                                        <td>{{ $product->name}}</td>
                                    </tr>
                        @endforeach

                                </tbody>
                            </table>
                    </div>
                @endforeach
            </div>
        </div>
    </div>
</code>```

答:
The start of your foreach products is before the
 start tag.

You are, however, trying to generate one row per product, so it should be immediately before the
 start tag.

The matching endforeach should likewise be moved to just after the
 end tag.

Title: Displaying data into HTML Tables

Body:
I am able to display my data from db. I want to display in a table under tabs but then my data appears crooked. The rows are not straight. why is that happening to the table?

it is arranged kind of this way.

the updated code below doesn't provide the right format for the table
Table

  id  name
     1    James
    4   Michel
   2  Jonathan

HTML

                @foreach($items as $item)

id }}" data-toggle="tab" >{!!$item->name!!}

                @endforeach

                @foreach($items as $item)

id }}">
                        @foreach($item->products as $product)

                                        No#
                                        Name
                                        Action

                                        {{$product->id }}
                                        {{ $product->name}}

                        @endforeach

                @endforeach

Updated Code

Update

                @foreach($items as $item)

id }}" data-toggle="tab" >{!!$item->name!!}

                @endforeach

                @foreach($items as $item)

id }}">

                                        No#
                                        Name
                                        Action

                        @foreach($item->products as $product)

                                        {{$product->id }}
                                        {{ $product->name}}

                        @endforeach

                @endforeach

Body:
The start of your foreach products is before the <table> start tag.

You are, however, trying to generate one row per product, so it should be immediately before the <tr> start tag.

The matching endforeach should likewise be moved to just after the </tr> end tag.


问:
Writing to a specific range/Column with Pandas
I'm attempting to copy from column Range AP:AR of workbook 1 to Range A:C of workbook 2 through Pandas data frames.

I have successfully read the data frame below in workbook 1, I then want to write this into workbook 2 of the specified range.  So AP:AR to AQ:AS.

I have tried:

```<code>#df.to_excel(writer, 'AP')
</code>```

I have also tried the following:

```<code> #df = pd.write_excel(filename, skiprows = 2, parse_cols = 'AP:AR')
pd.writer = pd.ExcelWriter('output.xlsx', columns = 'AP:AR')
pd.writer.save()
</code>```

For example:

```<code>filename ='C:/ workbook 1.xlsx'
df = pd.read_excel(filename, skiprows = 2, parse_cols = 'A:C')

import pandas as pd
writer = pd.ExcelWriter('C:/DRAX/ workbook 2.xlsx')
df.to_excel(writer, 'AQ')
writer.save()
print(df)
</code>```

It reads correctly, but writes to Cell column ‘B’ instead of AQ.

答:
You have to specify the starting column you want to write the dataframe with the parameter startcol, which is an integer starting from 0:

So you should change the line

```<code>df.to_excel(writer, 'AQ')
</code>```

to

```<code>df.to_excel(writer, startcol=42) # AQ has the index of 42
</code>```

Results:

Body:
I'm attempting to copy from column Range AP:AR of workbook 1 to Range A:C of workbook 2 through Pandas data frames.

I have successfully read the data frame below in workbook 1, I then want to write this into workbook 2 of the specified range.  So AP:AR to AQ:AS.

I have tried:

#df.to_excel(writer, 'AP')

I have also tried the following:

 #df = pd.write_excel(filename, skiprows = 2, parse_cols = 'AP:AR')
pd.writer = pd.ExcelWriter('output.xlsx', columns = 'AP:AR')
pd.writer.save()

For example:

filename ='C:/ workbook 1.xlsx'
df = pd.read_excel(filename, skiprows = 2, parse_cols = 'A:C')

import pandas as pd
writer = pd.ExcelWriter('C:/DRAX/ workbook 2.xlsx')
df.to_excel(writer, 'AQ')
writer.save()
print(df)

It reads correctly, but writes to Cell column ‘B’ instead of AQ.

Body:
You have to specify the starting column you want to write the dataframe with the parameter startcol, which is an integer starting from 0:

So you should change the line

df.to_excel(writer, 'AQ')

to

df.to_excel(writer, startcol=42) # AQ has the index of 42

Results:


问:
angular2-jwt: AuthHttp causes an error 'Expected 0 type arguments, but got 1.'
when I use AuthHttp from angular2-jwt in code below, I see error:

"Expected 0 type arguments, but got 1."

```<code>public getData(): Observable<User[]>{
const url = environment.apiUrl + "users";

return this.authHttp
  .get<User[]>(url)
  .map((res: User[]) => res);
  }
</code>```

If I use http: HttpClient, code works well.

What to change in this code to run it with AuthHttp?

答:
Are you sure you're using it correctly ?

I'd expect it to look like this:

```<code>this.http.get(url)
      .map( (res) => res.json())
      .subscribe(
        data => this.thing = data,
        err => console.log(error),
        () => console.log('Request Complete')
      );
</code>```

Body:
when I use AuthHttp from angular2-jwt in code below, I see error:

"Expected 0 type arguments, but got 1."

public getData(): Observable<User[]>{
const url = environment.apiUrl + "users";

return this.authHttp
  .get<User[]>(url)
  .map((res: User[]) => res);
  }

If I use http: HttpClient, code works well.

What to change in this code to run it with AuthHttp?

Body:
Are you sure you're using it correctly ?

I'd expect it to look like this:

this.http.get(url)
      .map( (res) => res.json())
      .subscribe(
        data => this.thing = data,
        err => console.log(error),
        () => console.log('Request Complete')
      );


问:
How to configure SSO for Azure AD B2C?
As per Azure AD B2C documentation we can configure SSO for Azure AD B2C application. We want our user to do self-registration for the application thus opted for AD B2C.

However after creating B2C tenant account and configuring all the policies. I am unable to find option to configure SSO. Since after 30th Nov 2017, Active Directory will only be available in new portal. Kindly provide reference wrt new portal.

. Any help will be appreciated.

Thanks in advance.

答:
As the document in the your question said,if you have multiple applications and policies in your B2C tenant, you can manage user interactions across them using the Single sign-on configuration property. You can also add external identity provider like Google, Facebook and etc.

If you want to know how it works and how to configure SSO in Azure AD B2C, you can refer to this document.

Also, If you want to configure SSO for applications in your B2C tenant(the Directory).

Go to Azure portal > Enterprise applications> Add Non-gallery applications or in  applications in  Gallery.

After adding apps in Enterprise applications, you can select your app and enable SSO for it.

Hope this helps!

Update

Adding custom applications requires Azure AD Premium.

You can also active Azure Active Directory Premium free for one month.

Now, you can add your own custom applications in Enterprise Applications and then configure SSO for it:

Title: How to configure SSO for Azure AD B2C?


问:
What are these controller parameters in controller file?
I am turning over my head to understand AngularJS. I am unable to make sense of this. Online guides are only basic as far as I have seen.

app.register.controller("viewTests", [
  "$scope",
  "$modal",
  "$http",
  "$route",
  "pinesNotifications",
  "$location",
  "$route",
  "$routeParams",
  "$timeout",
  "$modal",
  function (
    $scope,
    $modal,
    $http,
    $route,
    pinesNotifications,
    $location,
    $routeParams,
    $timeout
  ){
```

Please explain to me:

How do they work and interact?

Is the parameter order important?

答:
These are injections, like your scope or the http service for http actions. you will find most of them well documented, because they are part of AngularJS. for example: $http

Order is not important inside the array (I assume you forgot the closing bracket) but the parameter order of the controller is important.

Body:
I am turning over my head to understand AngularJS. I am unable to make sense of this. Online guides are only basic as far as I have seen.

app.register.controller("viewTests", [
  "$scope",
  "$modal",
  "$http",
  "$route",
  "pinesNotifications",
  "$location",
  "$route",
  "$routeParams",
  "$timeout",
  "$modal",
  function (
    $scope,
    $modal,
    $http,
    $route,
    pinesNotifications,
    $location,
    $routeParams,
    $timeout
  ){

Please explain to me:

How do they work and interact?

Is the parameter order important?


问:
CakePHP fetching data from form
I am trying to get the value of input data in a cakephp form so that I can use it in a sql query to auto fill other data. Currently i'm trying to use $this->request->data but it's not showing any results when I change my customer. I want it to display the customer that is selected but currently it's just blank. Not sure if i'm trying to get the data correctly or displaying it incorrectly.

My add.ctp

```<code><div class="invoices form large-9 medium-8 columns content">
    <?= $this->Form->create($invoice) ?>
    <fieldset>
        <legend><?= __('Add Invoice') ?></legend>
        <?php

            echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);        ?>

    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>

<script>
            document.getElementById('customers').addEventListener('change',function(){
                alert(<?php echo $this->request->data('customers');
                ?>)
                });

            </script>
</code>```

答:
Replace your code with this</p>

```<code>document.getElementById('customers').addEventListener('change',function(){
       alert(this.value);
 });
</code>```

Title: CakePHP fetching data from form

Body:
I am trying to get the value of input data in a cakephp form so that I can use it in a sql query to auto fill other data. Currently i'm trying to use $this->request->data but it's not showing any results when I change my customer. I want it to display the customer that is selected but currently it's just blank. Not sure if i'm trying to get the data correctly or displaying it incorrectly.

My add.ctp

    <?= $this->Form->create($invoice) ?>
    <fieldset>
        <legend><?= __('Add Invoice') ?></legend>
        <?php

            echo $this->Form->input('customer_id', ['options' => $customers, 'empty' => true,'id'=>'customers']);        ?>

    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>

Body:
Replace your code with this

document.getElementById('customers').addEventListener('change',function(){
       alert(this.value);
 });


问:
Does Blueprint replace Activator class when implementing a OSGi bundle?
I'm new to Opendaylight and I'm currently trying to develop an app to get packet-in, analyse them and then dispatch them to other app.
Does the blueprint replace the need for creating an Activator class to register the component with the OSGi framework? Or do we still need the activator to instantiate and set the dependencies?
As far as I can tell, the blueprint already does that, am I correct?

Any help would be extremely appreciated!

答:
Yes, Blueprint takes care of the OSGi registration and discovery for you, as long as you declare the appropriate elements in the Blueprint descriptor: <reference/> to find a service, <service/> to expose one. The Using Blueprint page on the ODL wiki covers Blueprint usage in some detail, including OSGi integration and MD-SAL integration.

In many cases, if you’re using the ODL parent POMs you can take advantage of Blueprint autowiring, using @Singleton and @Inject annotations instead of writing an XML file.

(You can ignore all the Config Sub-System sections, that’s deprecated.)


问:
smarty not working on new server PHP Version 5.2.6
Warning: preg_match() [function.preg-match]: Compilation failed: repeated subpattern is too long at offset 18454 in /Smarty_Compiler.class.php on line 454

Fatal error: Smarty error: [in login.tpl line 1]: syntax error: unrecognized tag: php (Smarty_Compiler.class.php, line 455)

this message coming.. it was working perfect on dev server but on live server its not working.

Dev php version was  5.2.14
new server has PHP Version 5.2.6

is this the problem?

答:
Which version you are using ?

Use the latest version of smarty it might solve your problem.