text:
/**
   @author Shin'ichiro Nakaoka
*/

#include "MessageView.h"
#include "MainWindow.h"
#include "ViewManager.h"
#include "InfoBar.h"
#include "Item.h"
#include "TextEdit.h"
#include <QBoxLayout>
#include <QMessageBox>
#include <QCoreApplication>
#include <QThread>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <stack>
#include <iostream>
#include "gettext.h"

using namespace std;
using namespace cnoid;
namespace iostreams = boost::iostreams;

namespace {

MessageView* messageView = 0;

const bool PUT_COUT_TOO = false;

class TextSink : public iostreams::sink
{
public:
    TextSink(MessageViewImpl* messageViewImpl, bool doFlush);
    std::streamsize write(const char* s, std::streamsize n);

    MessageViewImpl* messageViewImpl;
    QTextEdit& textEdit;
    bool doFlush;
};

struct StdioInfo {
    streambuf* cout;
    streambuf* cerr;
};

enum MvCommand { MV_PUT, MV_CLEAR };

class MessageViewEvent : public QEvent
{
public:
    MessageViewEvent(const QString& message, bool doLF, bool doNotify, bool doFlush)
        : QEvent(QEvent::User),
          command(MV_PUT),
          message(message),
          doLF(doLF),
          doNotify(doNotify),
          doFlush(doFlush) {
    }

    MessageViewEvent(MvCommand command)
        : QEvent(QEvent::User),
          command(command) {

    }

    MvCommand command;
    QString message;
    bool doLF;
    bool doNotify;
    bool doFlush;
};

int flushingRef = 0;
Signal<void()> sigFlushFinished_;

class TextEditEx : public TextEdit
{
public:
    MessageViewImpl* viewImpl;
    TextEditEx(MessageViewImpl* viewImpl) : viewImpl(viewImpl) { }
    virtual void keyPressEvent(QKeyEvent* event);
    virtual void resizeEvent(QResizeEvent* event);
    bool isLatestMessageVisible();
};

}

namespace cnoid {

class MessageViewImpl
{
public:
    MessageView* self;

    Qt::HANDLE mainThreadId;

    TextEditEx textEdit;
    QTextCursor cursor;
    QTextCharFormat orgCharFormat;
    QTextCharFormat currentCharFormat;
    QColor orgForeColor;
    QColor orgBackColor;

    TextSink textSink;
    iostreams::stream_buffer<TextSink> sbuf;
    std::ostream os;

    TextSink textSink_flush;
    iostreams::stream_buffer<TextSink> sbuf_flush;
    std::ostream os_flush;

    std::stack<StdioInfo> stdios;
    bool exitEventLoopRequested;

    Signal<void(const std::string& text)> sigMessage;

    MessageViewImpl(MessageView* self);

    void put(const QString& message, bool doLF, bool doNotify, bool doFlush);
    void put(int type, const QString& message, bool doLF, bool doNotify, bool doFlush);
    void doPut(const QString& message, bool doLF, bool doNotify, bool doFlush);
    void handleMessageViewEvent(MessageViewEvent* event);
    void flush();
    void doClear();
    void clear();

    void insertPlainText(const QString& message, bool doLF);
    bool paramtoInt(const QString& txt, vector<int>& n);
    int setdefault1(const vector<int>& n);
    int setdefault0(const vector<int>& n);
    void inttoColor(int n, QColor& col);
    void textProperties(const vector<int>& n);
    void escapeSequence(QString& txt);
};

}

TextSink::TextSink(MessageViewImpl* messageViewImpl, bool doFlush)
    : messageViewImpl(messageViewImpl),
      textEdit(messageViewImpl->textEdit),
      doFlush(doFlush)
{

}

std::streamsize TextSink::write(const char* s, std::streamsize n)
{
    messageViewImpl->put(QString::fromLocal8Bit(s, n), false, false, doFlush);
    //messageViewImpl->put(QString::fromUtf8(s, n), false, false, doFlush);
    return n;
}

void TextEditEx::keyPressEvent(QKeyEvent* event)
{
    if ((event->modifiers().testFlag(Qt::ControlModifier))){
        switch(event->key()){
        case Qt::Key_C:
        case Qt::Key_A:
            TextEdit::keyPressEvent(event);
            break;
        }
    }
    switch(event->key()){
    case Qt::Key_Return:
        moveCursor(QTextCursor::End);
        insertPlainText("\n");
        ensureCursorVisible();
        break;
    default:
        break;
        //TextEdit::keyPressEvent(event);
    }
}

void TextEditEx::resizeEvent(QResizeEvent* event)
{
    bool isLatest = isLatestMessageVisible();
    TextEdit::resizeEvent(event);
    if(isLatest){
        moveCursor(QTextCursor::End);
    }
}

bool TextEditEx::isLatestMessageVisible()
{
    int scrollPos = getScrollPos();
    return (scrollPos > maxScrollPos() - 3 * scrollSingleStep());
}

void MessageView::initializeClass(ExtensionManager* ext)
{
    messageView = ext->viewManager().registerClass<MessageView>(
        "MessageView", N_("Message"), ViewManager::SINGLE_DEFAULT);
}

/**
   @return The main instance of MessageView.
*/
MessageView* MessageView::instance()
{
    return messageView;
}

/**
   Obsolete. Please use MessageView::instance().
*/
MessageView* MessageView::mainInstance()
{
    return messageView;
}

MessageView::MessageView()
{
    impl = new MessageViewImpl(this);
}

MessageViewImpl::MessageViewImpl(MessageView* self) :
    self(self),
    mainThreadId(QThread::currentThreadId()),
    textEdit(this),
    textSink(this, false),
    sbuf(textSink),
    os(&sbuf),
    textSink_flush(this, true),
    sbuf_flush(textSink_flush),
    os_flush(&sbuf_flush)
{
    self->setDefaultLayoutArea(View::BOTTOM);

    textEdit.setObjectName("TextEdit");
    textEdit.setFrameShape(QFrame::NoFrame);
    //textEdit.setReadOnly(true);
    textEdit.setTextInteractionFlags(
        Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
    textEdit.setWordWrapMode(QTextOption::WrapAnywhere);
    textEdit.setSizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored);

    QHBoxLayout* layout = new QHBoxLayout();
    layout->addWidget(&textEdit);
    self->setLayout(layout);

    textEdit.moveCursor(QTextCursor::End);
    cursor = textEdit.textCursor();

    QFont font("monospace");
    font.setStyleHint(QFont::TypeWriter);
    textEdit.setFont(font);

    orgForeColor = textEdit.palette().color(QPalette::Text);
    orgBackColor = textEdit.palette().color(QPalette::Base);

    currentCharFormat = cursor.charFormat();
    orgCharFormat = currentCharFormat;
    orgCharFormat.setForeground(orgForeColor);
    orgCharFormat.setBackground(orgBackColor);
}

MessageView::~MessageView()
{
    delete impl;
}

std::ostream& MessageView::cout(bool doFlush)
{
    return doFlush ? impl->os_flush : impl->os;
}

void MessageView::beginStdioRedirect()
{
    /*
    StdioInfo info;
    info.cout = std::cout.rdbuf();
    info.cerr = std::cerr.rdbuf();
    impl->stdios.push(info);
    std::cout.rdbuf(impl->os.rdbuf());
    std::cerr.rdbuf(impl->os.rdbuf());
    */
}

void MessageView::endStdioRedirect()
{
    /*
    if(!impl->stdios.empty()){
        StdioInfo& info = impl->stdios.top();
        std::cout.rdbuf(info.cout);
        std::cerr.rdbuf(info.cerr);
        impl->stdios.pop();
    }
    */
}

void MessageView::put(const char* message, int type)
{
    impl->put(type, message, false, false, false);
}

void MessageView::put(const std::string& message, int type)
{
    impl->put(type, message.c_str(), false, false, false);
}

void MessageView::put(const boost::format& message, int type)
{
    impl->put(type, message.str().c_str(), false, false, false);
}

void MessageView::put(const QString& message, int type)
{
    impl->put(type, message, false, false, false);
}

void MessageView::putln()
{
    impl->put(QString(), true, false, false);
}

void MessageView::putln(const std::string& message, int type)
{
    impl->put(type, message.c_str(), true, false, false);
}

void MessageView::putln(const boost::format& message, int type)
{
    impl->put(type, message.str().c_str(), true, false, false);
}

void MessageView::putln(const char* message, int type)
{
    impl->put(type, message, true, false, false);
}

void MessageView::putln(const QString& message, int type)
{
    impl->put(type, message, true, false, false);
}

void MessageView::notify(const std::string& message, int type)
{
    impl->put(type, message.c_str(), true, true, false);
}

void MessageView::notify(const boost::format& message, int type)
{
    impl->put(type, message.str().c_str(), true, true, false);
}

void MessageView::notify(const char* message, int type)
{
    impl->put(type, message, true, true, false);
}

void MessageView::notify(const QString& message, int type)
{
    impl->put(type, message, true, true, false);
}

//! \deprecated
void MessageView::put(int type, const char* message)
{
    impl->put(type, message, false, false, false);
}

//! \deprecated
void MessageView::put(int type, const std::string& message)
{
    impl->put(type, message.c_str(), false, false, false);
}

//! \deprecated
void MessageView::put(int type, const boost::format& message)
{
    impl->put(type, message.str().c_str(), false, false, false);
}

//! \deprecated
void MessageView::put(int type, const QString& message)
{
    impl->put(type, message, false, false, false);
}

//! \deprecated
void MessageView::putln(int type, const char* message)
{
    impl->put(type, message, true, false, false);
}

//! \deprecated
void MessageView::putln(int type, const std::string& message)
{
    impl->put(type, message.c_str(), true, false, false);
}

//! \deprecated
void MessageView::putln(int type, const boost::format& message)
{
    impl->put(type, message.str().c_str(), true, false, false);
}

//! \deprecated
void MessageView::putln(int type, const QString& message)
{
    impl->put(type, message, true, false, false);
}

void MessageViewImpl::put(const QString& message, bool doLF, bool doNotify, bool doFlush)
{
    if(QThread::currentThreadId() == mainThreadId){
        doPut(message, doLF, doNotify, doFlush);
    } else {
        MessageViewEvent* event = new MessageViewEvent(message, doLF, doNotify, doFlush);
        QCoreApplication::postEvent(self, event, Qt::NormalEventPriority);
    }
}

void MessageViewImpl::put(int type, const QString& message, bool doLF, bool doNotify, bool doFlush)
{
    if(type == MessageView::NORMAL){
        put(message, doLF, doNotify, doFlush);
    } else {
        // add the escape sequence to make the text red
        QString highlighted("\033[31m");
        if(type == MessageView::ERROR){
            highlighted.append("Error: ");
        } else if(type == MessageView::WARNING){
            highlighted.append("Warning: ");
        }
        highlighted.append(message);
        highlighted.append("\033[0m");

        put(highlighted, doLF, doNotify, doFlush);
    }
}

void MessageViewImpl::doPut(const QString& message, bool doLF, bool doNotify, bool doFlush)
{
    bool isLatestMessageVisible = textEdit.isLatestMessageVisible();
    if(isLatestMessageVisible){
        textEdit.moveCursor(QTextCursor::End);
    }

    QString txt(message);
    while(true){
        int i = txt.indexOf("\x1b");
        if(i < 0){
            break;
        }
        if(i > 0){
            insertPlainText(txt.left(i), false);
        }
        txt = txt.mid(++i);
        escapeSequence(txt);
    }
    insertPlainText(txt, doLF);

    if(isLatestMessageVisible){
        textEdit.ensureCursorVisible();
    }

    if(PUT_COUT_TOO){
        cout << message.toStdString();
        if(doLF){
            cout << endl;
        }
    }

    if(!sigMessage.empty()){
        std::string text(message.toStdString());
        if(doLF){
            text += "\n";
        }
        sigMessage(boost::ref(text));
    }

    if(doNotify){
        InfoBar::instance()->notify(message);
    }
    if(doFlush){
        flush();
    }
}

bool MessageView::event(QEvent* e)
{
    MessageViewEvent* event = dynamic_cast<MessageViewEvent*>(e);
    if(event){
        impl->handleMessageViewEvent(event);
        return true;
    }
    return false;
}

void MessageViewImpl::handleMessageViewEvent(MessageViewEvent* event)
{
    switch(event->command){
    case MV_PUT:
        doPut(event->message, event->doLF, event->doNotify, event->doFlush);
        break;
    case MV_CLEAR:
        doClear();
        break;
    default:
        break;
    }
}

int MessageView::currentColumn()
{
    QTextCursor cursor = impl->textEdit.textCursor();
    cursor.movePosition(QTextCursor::End);
    return cursor.columnNumber();
}

/**
   @note Don't call this function from an expose event handler
   because it may cause a hangup of rendering.
*/
void MessageView::flush()
{
    impl->flush();
}

void MessageViewImpl::flush()
{
    if(QThread::currentThreadId() == mainThreadId){
        ++flushingRef;
        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents|QEventLoop::ExcludeSocketNotifiers, 1.0);
        --flushingRef;
        if(flushingRef == 0){
            sigFlushFinished_();
        }
    }
}

SignalProxy<void(const std::string& text)> MessageView::sigMessage()
{
    return impl->sigMessage;
}

bool MessageView::isFlushing()
{
    return (flushingRef > 0);
}

SignalProxy<void()> MessageView::sigFlushFinished()
{
    return sigFlushFinished_;
}

void MessageViewImpl::doClear()
{
    textEdit.clear();
}

void MessageView::clear()
{
    impl->clear();
}

void MessageViewImpl::clear()
{
    if(QThread::currentThreadId() == mainThreadId){
        doClear();
    } else {
        QCoreApplication::postEvent(self, new MessageViewEvent(MV_CLEAR), Qt::NormalEventPriority);
    }
}

void MessageViewImpl::insertPlainText(const QString& message, bool doLF)
{
    if(!doLF){
        cursor.insertText(message);
    } else {
        cursor.insertText(message + "\n");
    }
}

bool MessageViewImpl::paramtoInt(const QString& txt, vector<int>& n)
{
    QStringList stringlist = txt.split(';');
    for(int j=0; j<stringlist.size(); j++){
        bool ret;
        int n0 = stringlist[j].toInt(&ret);
        if(ret){
            n.push_back(n0);
        } else {
            return false;
        }
    }
    return true;
}

int MessageViewImpl::setdefault1(const vector<int>& n)
{
    if(n.size()){
        return n[0];
    } else {
        return 1;
    }
}

int MessageViewImpl::setdefault0(const vector<int>& n)
{
    if(n.size()){
        return n[0];
    } else {
        return 0;
    }
}

void MessageViewImpl::inttoColor(int n, QColor& col)
{
    switch(n){
    case 0:
        col = QColor("black");
        return;
    case 1:
        col = QColor("red");
        return;
    case 2:
        col = QColor("green");
        return;
    case 3:
        col = QColor("yellow");
        return;
    case 4:
        col = QColor("blue");
        return;
    case 5:
        col = QColor("magenta");
        return;
    case 6:
        col = QColor("cyan");
        return;
    case 7:
        col = QColor("white");
        return;
    case 8:
        col = QColor("gray");
        return;
    case 9:
        col = QColor("darkRed");
        return;
    case 10:
        col = QColor("darkGreen");
        return;
    case 11:
        col = QColor("darkYellow");
        return;
    case 12:
        col = QColor("darkBlue");
        return;
    case 13:
        col = QColor("darkMagenta");
        return;
    case 14:
        col = QColor("darkCyan");
        return;
    case 15:
        col = QColor("darkGray");
        return;
    }
}

void MessageViewImpl::textProperties(const vector<int>& n)
{
    QColor col;
    for(size_t i=0; i < n.size(); i++){
        switch(n[i]){
        case 0:  // Reset all
            currentCharFormat = orgCharFormat;
            break;
        case 1:  // Bold text
            currentCharFormat.setFontWeight(QFont::Bold);
            break;
        case 4:  // Underline
            currentCharFormat.setFontUnderline(true);
            break;
        case 5:  // Blinking
            break;
        case 7:  // Flipping
        case 27: // Clear flipping
        {
            QColor fore = currentCharFormat.foreground().color();
            QColor back = currentCharFormat.background().color();
            currentCharFormat.setForeground(back);
            currentCharFormat.setBackground(fore);
            break;
        }
        case 22:  // Clear bold
            currentCharFormat.setFontWeight(QFont::Normal);
            break;
        case 24:  // Clear underline
            currentCharFormat.setFontUnderline(false);
            break;
        case 25:  // Clear blinking
            break;
        case 30:  // Black
        case 31:  // Red
        case 32:  // Green
        case 33:  // Yellow
        case 34:  // Blue
        case 35:  // Magenda
        case 36:  // Cyan
        case 37:  // White
            inttoColor(n[i]-30, col);
            currentCharFormat.setForeground(col);
            break;
        case 38:
        {
            size_t j = i + 1;
            if(j < n.size()){
                if(n[j] == 2){  // RGB color specification
                    if(j + 3 < n.size()){
                        col = QColor(n[j+1], n[j+2], n[j+3]);
                        currentCharFormat.setForeground(col);
                        i += 4;
                    }
                }else if(n[j] == 5){  // Color id specification
                    if(j + 1 < n.size()){
                        inttoColor(n[j+1], col);
                        currentCharFormat.setForeground(col);
                        i += 2;
                    }
                }
            }
            break;
        }
        case 39:  // Normal color
            currentCharFormat.setForeground(orgForeColor);
            break;
        case 40:  // Black background
        case 41:  // Red background
        case 42:  // Green background
        case 43:  // Yellow background
        case 44:  // Blue background
        case 45:  // Magenda background
        case 46:  // Cyan background
        case 47:  // White background
            inttoColor(n[i]-40, col);
            currentCharFormat.setBackground(col);
            break;
        case 48:
        {
            size_t j = i + 1;
            if(j < n.size()){
                if(n[j] == 2){  // Background color specified by RGB
                    if(j + 3 <n.size()){
                        col = QColor(n[j+1], n[j+2], n[j+3]);
                        currentCharFormat.setBackground(col);
                        i += 4;
                    }
                }else if(n[j] == 5){  // Background color specified by id
                    if(j + 1 <n.size()){
                        inttoColor(n[j+1], col);
                        currentCharFormat.setBackground(col);
                        i += 2;
                    }
                }
            }
            break;
        }
        case 49:  // Normal background color
            currentCharFormat.setBackground(orgBackColor);
            break;
        case 90:
        case 91:
        case 92:
        case 93:
        case 94:
        case 95:
        case 96:
        case 97:
            inttoColor(n[i]-82, col);
            currentCharFormat.setForeground(col);
            break;
        case 100:
        case 101:
        case 102:
        case 103:
        case 104:
        case 105:
        case 106:
        case 107:
            inttoColor(n[i]-92, col);
            currentCharFormat.setBackground(col);
            break;
        }
    }
    cursor.setCharFormat(currentCharFormat);
    textEdit.setTextCursor(cursor);
}

void MessageViewImpl::escapeSequence(QString& txt)
{
    if(!txt.startsWith("[")){
        return;
    }

    int i = txt.indexOf(QRegExp("[@A-z`]"), 1);
    if(i < 0){
        return;
    }
    QChar c = txt.at(i);
    vector<int> n;
    if(i > 1){
        if(!paramtoInt(txt.mid(1, i-1), n)){
            return;
        }
    }

    if(c=='@'){  // Space insertion
        int nn=setdefault1(n);
        QString sp(nn,' ');
        insertPlainText(sp, false);
    }else if(c=='A' || c=='k'){  // Cursor up
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::Up, QTextCursor::MoveAnchor, nn);
        textEdit.setTextCursor(cursor);
    }else if(c=='B' || c=='e'){  // Cursor down
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, nn);
        textEdit.setTextCursor(cursor);
    }else if(c=='C' || c=='a'){  // Cursor right
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, nn);
        textEdit.setTextCursor(cursor);
    }else if(c=='D'  || c=='j'){  // Cursor left
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, nn);
        textEdit.setTextCursor(cursor);
    }else if(c=='E'){  // Move the cursor to the first column of the next line
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, nn);
        cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
        textEdit.setTextCursor(cursor);
    }else if(c=='F'){  // Move the cursor the the first column of the previous line
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::Up, QTextCursor::MoveAnchor, nn);
        cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
        textEdit.setTextCursor(cursor);
    }else if(c=='G'){  // Cursor right by nn
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
        cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, nn-1);
        textEdit.setTextCursor(cursor);
    }else if(c=='H' || c=='f'){  // Cursor down by nn0 and right by nn1
        int nn0, nn1;
        switch(n.size()){
        case 0:
            nn0 = nn1 = 1;
            break;
        case 1:
            nn0 = n[0];
            nn1 = 1;
            break;
        case 2 :
        default :
            nn0 = n[0];
            nn1 = n[1];
        }
        cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
        cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, nn0-1);
        cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
        cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, nn1-1);
        textEdit.setTextCursor(cursor);
    }else if(c=='J'){
        int nn=setdefault0(n);
        switch(nn){
        case 0:  // Erase from the cursor position to the end
            cursor.clearSelection();
            cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
            cursor.removeSelectedText();
            break;
        case 1:  // Erase from the beginning to the cursor position
            cursor.clearSelection();
            cursor.movePosition(QTextCursor::Start, QTextCursor::KeepAnchor);
            cursor.removeSelectedText();
            break;
        case 2:  // Erase all
            textEdit.clear();
            break;
        default:
            break;
        }
    }else if(c=='K'){
        int nn=setdefault0(n);
        switch(nn){
        case 0:  // Erase from the cursor position to the end of the line
            cursor.clearSelection();
            cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
            cursor.removeSelectedText();
            break;
        case 1:  // Erase from the start of the line to the cursor position
            cursor.clearSelection();
            cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
            cursor.removeSelectedText();
            break;
        case 2:  // Erase a line
            cursor.clearSelection();
            cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
            cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
            cursor.removeSelectedText();
            break;
        default:
            break;
        }
    }else if(c=='L'){  // Insert empty line
        int nn=setdefault1(n);
        cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
        for(int i=0; i<nn; i++)
            textEdit.insertPlainText("\n");
    }else if(c=='M'){  // Erase nn lines
        int nn=setdefault1(n);
        cursor.clearSelection();
        cursor.movePosition(QTextCursor::StartOfLine, QTextCursor::MoveAnchor);
        cursor.movePosition(QTextCursor::Down, QTextCursor::KeepAnchor, nn);
        cursor.removeSelectedText();
    }else if(c=='P'){  // Delete nn characters
        int nn=setdefault1(n);
        cursor.clearSelection();
        cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, nn);
        cursor.removeSelectedText();
        //}else if(c=='S'){  // Scroll up nn lines
        //	int nn=setdefault1(n);
        //}else if(c=='T'){  // Scroll down nn lines
        //	int nn=setdefault1(n);
    }else if(c=='X'){  // Make nn characters blank
        int nn=setdefault1(n);
        cursor.clearSelection();
        cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, nn);
        QString sp(nn,' ');
        cursor.insertText(sp);
        //}else if(c=='Z'){  // Move the cursor to nn previous tab stop
        //	int nn=setdefault1(n);
        //}else if(c=='a'){   // Same as 'C'
        //}else if(c=='c'){  // Terminal characteristics
        //	int nn=setdefault0(n);
    }else if(c=='d'){  // Move the cursor to the nn line without changing the current column
        int nn=setdefault1(n);
        int i = cursor.columnNumber();
        cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
        cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, nn-1);
        cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, i);
        textEdit.setTextCursor(cursor);
        //}else if(c=='e'){  // Same as 'B'
        //}else if(c=='f'){  // Same as 'H'
        //}else if(c=='g'){  // Delete tab stop
        //	int nn=setdefault1(0);
        //	switch(nn){
        //	case 0:  // Delete one
        //		break;
        //	case 3:  // Delete all
        //		break;
        //	}
        //}else if(c=='h'){  // Set mode
        //}else if(c=='i'){  // Print mode
        //}else if(c=='j'){  // Same as 'D'
        //}else if(c=='k'){  // Same as 'A'
        //}else if(c=='l'){  // Mode release
    }else if(c=='m'){  // Set character attribute
        if(!n.size()){
            currentCharFormat = orgCharFormat;
            cout << "!n.size()" << endl;
            textEdit.setCurrentCharFormat(currentCharFormat);
            return;
        }else{
            textProperties(n);
        }
        //}else if(c=='n'){  // State of the terminal
        //}else if(c=='r'){  // Set up and down margin
        //}else if(c=='s'){  // Save cursor position
        //}else if(c=='t'){  // Window operation
        //}else if(c=='u'){  // Restore saved cursor position
    }
    txt = txt.mid(++i);
}

std::ostream& cnoid::mvout(bool doFlush)
{
    return MessageView::instance()->cout(doFlush);
}

void cnoid::showMessageBox(const QString& message)
{
    QMessageBox::information(MainWindow::instance(), _("Message"), message);
}

void cnoid::showMessageBox(const char* message)
{
    showMessageBox(QString(message));
}

void cnoid::showMessageBox(const std::string& message)
{
    showMessageBox(QString(message.c_str()));
}

void cnoid::showMessageBox(const boost::format& message)
{
    showMessageBox(QString(message.str().c_str()));
}

void cnoid::showWarningDialog(const QString& message)
{
    QMessageBox::warning(MainWindow::instance(), _("Warning"), message);
}

void cnoid::showWarningDialog(const char* message)
{
    showWarningDialog(QString(message));
}

void cnoid::showWarningDialog(const std::string& message)
{
    showWarningDialog(QString(message.c_str()));
}

void cnoid::showWarningDialog(const boost::format& message)
{
    showWarningDialog(QString(message.str().c_str()));
}

bool cnoid::showConfirmDialog(const QString& caption, const QString& message)
{
    QMessageBox::StandardButton clicked =
        QMessageBox::question(MainWindow::instance(), caption, message,
                              QMessageBox::Ok | QMessageBox::Cancel);
    return (clicked == QMessageBox::Ok);
}

bool cnoid::showConfirmDialog(const std::string& caption, const std::string& message)
{
    return showConfirmDialog(QString(caption.c_str()), QString(message.c_str()));
}

bool cnoid::showConfirmDialog(const char* caption, const char* message)
{
    return showConfirmDialog(QString(caption), QString(message));
}

max_stars_repo_name: rafaelxero/choreonoid

max_issues_repo_name: rafaelxero/choreonoid

max_forks_repo_name: rafaelxero/choreonoid


text:
/*
// Copyright (c) 2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#pragma once
#include <boost/asio/strand.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>

namespace crow
{

enum class ConnState
{
    initializing,
    connected,
    closed
};

class HttpClient : public std::enable_shared_from_this<HttpClient>
{
  private:
    boost::beast::tcp_stream conn;
    boost::beast::flat_buffer buffer;
    boost::beast::http::request<boost::beast::http::string_body> req;
    boost::beast::http::response<boost::beast::http::string_body> res;
    boost::asio::ip::tcp::resolver::results_type endpoint;
    std::vector<std::pair<std::string, std::string>> headers;
    ConnState state;
    std::string host;
    std::string port;

    void sendMessage()
    {
        if (state != ConnState::connected)
        {
            BMCWEB_LOG_DEBUG << "Not connected to: " << host;
            return;
        }

        // Set a timeout on the operation
        conn.expires_after(std::chrono::seconds(30));

        // Send the HTTP request to the remote host
        boost::beast::http::async_write(
            conn, req,
            [this,
             self(shared_from_this())](const boost::beast::error_code& ec,
                                       const std::size_t& bytesTransferred) {
                if (ec)
                {
                    BMCWEB_LOG_ERROR << "sendMessage() failed: "
                                     << ec.message();
                    this->doClose();
                    return;
                }
                BMCWEB_LOG_DEBUG << "sendMessage() bytes transferred: "
                                 << bytesTransferred;
                boost::ignore_unused(bytesTransferred);

                this->recvMessage();
            });
    }

    void recvMessage()
    {
        if (state != ConnState::connected)
        {
            BMCWEB_LOG_DEBUG << "Not connected to: " << host;
            return;
        }

        // Receive the HTTP response
        boost::beast::http::async_read(
            conn, buffer, res,
            [this,
             self(shared_from_this())](const boost::beast::error_code& ec,
                                       const std::size_t& bytesTransferred) {
                if (ec)
                {
                    BMCWEB_LOG_ERROR << "recvMessage() failed: "
                                     << ec.message();
                    this->doClose();
                    return;
                }
                BMCWEB_LOG_DEBUG << "recvMessage() bytes transferred: "
                                 << bytesTransferred;
                boost::ignore_unused(bytesTransferred);

                // Discard received data. We are not interested.
                BMCWEB_LOG_DEBUG << "recvMessage() data: " << res;

                this->doClose();
            });
    }

    void doClose()
    {
        boost::beast::error_code ec;
        conn.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);

        state = ConnState::closed;
        // not_connected happens sometimes so don't bother reporting it.
        if (ec && ec != boost::beast::errc::not_connected)
        {
            BMCWEB_LOG_ERROR << "shutdown failed: " << ec.message();
            return;
        }
        BMCWEB_LOG_DEBUG << "Connection closed gracefully";
    }

    ConnState getState()
    {
        return state;
    }

  public:
    explicit HttpClient(boost::asio::io_context& ioc, const std::string& destIP,
                        const std::string& destPort) :
        conn(ioc),
        host(destIP), port(destPort)
    {
        boost::asio::ip::tcp::resolver resolver(ioc);
        endpoint = resolver.resolve(host, port);
        state = ConnState::initializing;
    }

    void doConnectAndSend(const std::string& path, const std::string& data)
    {
        BMCWEB_LOG_DEBUG << "doConnectAndSend " << host << ":" << port;

        req.version(static_cast<int>(11)); // HTTP 1.1
        req.target(path);
        req.method(boost::beast::http::verb::post);

        // Set headers
        for (const auto& [key, value] : headers)
        {
            req.set(key, value);
        }
        req.set(boost::beast::http::field::host, host);
        req.keep_alive(true);

        req.body() = data;
        req.prepare_payload();

        // Set a timeout on the operation
        conn.expires_after(std::chrono::seconds(30));
        conn.async_connect(endpoint, [this, self(shared_from_this())](
                                         const boost::beast::error_code& ec,
                                         const boost::asio::ip::tcp::resolver::
                                             results_type::endpoint_type& ep) {
            if (ec)
            {
                BMCWEB_LOG_ERROR << "Connect " << ep
                                 << " failed: " << ec.message();
                return;
            }
            state = ConnState::connected;
            BMCWEB_LOG_DEBUG << "Connected to: " << ep;

            sendMessage();
        });
    }

    void setHeaders(
        const std::vector<std::pair<std::string, std::string>>& httpHeaders)
    {
        headers = httpHeaders;
    }
};

} // namespace crow

ext: hpp

max_stars_repo_name: xyzwarrior/bmcweb

max_issues_repo_name: xyzwarrior/bmcweb

max_forks_repo_name: xyzwarrior/bmcweb


text:
/* This file is part of VoltDB.
 * Copyright (C) 2008-2020 VoltDB Inc.
 *
 * This file contains original code and/or modifications of original code.
 * Any modifications made by VoltDB Inc. are licensed under the following
 * terms and conditions:
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
/* Copyright (C) 2008 by H-Store Project
 * Brown University
 * Massachusetts Institute of Technology
 * Yale University
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <time.h>
#include <queue>
#include <boost/scoped_array.hpp>

#include "harness.h"
#include "json/json.h"

#include "expressions/abstractexpression.h"
#include "expressions/expressions.h"
#include "common/types.h"
#include "common/ValuePeeker.hpp"
#include "common/PlannerDomValue.h"

using namespace std;
using namespace voltdb;
//using namespace boost;

/*
   Description of test:

   1. This test defines a data structure for each expression type with
   unique fields.

   2. The test includes a helper to convert a std::queue of these structures
   into a tree of AbstractExpressions, using the expression factory via a
   json serialization.

   3. Using this utilities, the test defines several expressions (in
   std::queue) formats and asserts on the expected result.

   TODO: Unfortunately, the json_spirit serialization asserts when trying
   to read an int field from a value serialized as a string; need to figure
   out what's going on here .. and what the proper serialization method is.
*/

/*
 *  abstract expression mock object
 */
class AE {
  public:
    AE(ExpressionType et, ValueType vt, int vs) :
        m_type(et), m_valueType(vt), m_valueSize(vs) , left(NULL), right(NULL) {}

    virtual ~AE() {
        delete left;
        delete right;
    }

    virtual Json::Value serializeValue() {
        Json::Value json;
        serialize(json);
        return json;
    }

    /* this is how java serializes.. note derived class data follows
       the serialization of children */
    virtual void serialize(Json::Value &json) {
        json["TYPE"] = static_cast<int>(m_type);
        json["VALUE_TYPE"] = static_cast<int>(m_valueType);
        json["VALUE_SIZE"] = m_valueSize;

        if (left)
            json["LEFT"] = left->serializeValue();
        if (right)
            json["RIGHT"] = right->serializeValue();
    }

    ExpressionType m_type;  // TYPE
    ValueType m_valueType;  // VALUE_TYPE
    int m_valueSize;        // VALUE_SIZE

    // to build a tree
    AE *left;
    AE *right;
};

/*
 * constant value expression mock object
 */
class CV : public AE {
  public:
    CV(ExpressionType et, ValueType vt, int vs, int64_t v) :
        AE(et, vt, vs), m_jsontype (1), m_intValue(v)
    {
        m_stringValue = NULL;
        m_doubleValue = 0.0;
    }

    CV(ExpressionType et, ValueType vt, int vs, char * v) :
        AE(et, vt, vs), m_jsontype (1), m_stringValue(strdup(v))
    {
        m_intValue = 0;
        m_doubleValue = 0.0;
    }

    CV(ExpressionType et, ValueType vt, int vs, double v) :
        AE(et, vt, vs), m_jsontype (1), m_doubleValue(v)
    {
        m_stringValue = NULL;
        m_intValue = 0;
    }

    ~CV() {
    }

    virtual void serialize(Json::Value &json) {
        AE::serialize(json);
        if (m_jsontype == 0)
            json["VALUE"] = m_stringValue;
        else if (m_jsontype == 1)
            json["VALUE"] = static_cast<Json::Int64>(m_intValue);
        else if (m_jsontype == 2)
            json["VALUE"] = m_doubleValue;
        json["ISNULL"] = false;
    }

    int m_jsontype;  // 0 = string, 1 = int64_t, 2 = double

    int64_t  m_intValue;     // VALUE
    char    *m_stringValue;  // VALUE
    double   m_doubleValue;  // VALUE
};

/*
 * parameter value expression mock object
 */
class PV : public AE {
  public:
    PV(ExpressionType et, ValueType vt, int vs, int pi) :
        AE(et, vt, vs), m_paramIdx(pi) {}

    virtual void serialize(Json::Value &json) {
        AE::serialize(json);
        json["PARAM_IDX"] = m_paramIdx;
    }

    int m_paramIdx;  // PARAM_IDX
};

/*
 * tuple value expression mock object
 */
class TV  : public AE {
  public:
    TV(ExpressionType et, ValueType vt, int vs, int ci,
       const char *tn, const char *cn, const char *ca) :
        AE(et, vt, vs), m_columnIdx(ci), m_tableName(strdup(tn)),
        m_colName(strdup(cn)), m_colAlias(strdup(ca)) {}

    ~TV() {
        delete m_tableName;
        delete m_colName;
        delete m_colAlias;
    }

    virtual void serialize(Json::Value &json) {
        AE::serialize(json);
        json["COLUMN_IDX"] = m_columnIdx;
        json["TABLE_NAME"] = m_tableName;
        json["COLUMN_NAME"] = m_colName;
        json["COLUMN_ALIAS"] = m_colAlias;
    }

    int m_columnIdx;      // COLUMN_IDX
    char * m_tableName;   // TABLE_NAME
    char * m_colName;     // COLUMN_NAME
    char * m_colAlias;    // COLUMN_ALIAS
};

/*
 * Hash range expression mock object
 */
class HR : public AE {
public:
    HR(int hashColumn, int32_t ranges[][2], int numRanges) :
        AE(EXPRESSION_TYPE_HASH_RANGE, ValueType::tBIGINT, 8),
        m_hashColumn(hashColumn),
        m_ranges(ranges),
        m_numRanges(numRanges) {

    }

    virtual void serialize(Json::Value &json) {
        AE::serialize(json);
        json["HASH_COLUMN"] = m_hashColumn;
        Json::Value array;
        for (int ii = 0; ii < m_numRanges; ii++) {
            Json::Value range;
            range["RANGE_START"] = static_cast<Json::Int64>(m_ranges[ii][0]);
            range["RANGE_END"] = static_cast<Json::Int64>(m_ranges[ii][1]);
            array.append(range);
        }
        json["RANGES"] = array;
    }

    const int m_hashColumn;
    const int32_t (*m_ranges)[2];
    const int m_numRanges;
};

/*
   helpers to build trivial left-associative trees
   that is (a, *, b, +, c) returns (a * b) + c
   and (a, +, b, * c) returns (a + b) * c
*/

AE * join(AE *op, AE *left, AE *right) {
    op->left = left;
    op->right = right;
    return op;
}

AE * makeTree(AE *tree, queue<AE*> &q) {
    if (!q.empty()) {
        AE *left, *right, *op;
        if (tree) {
            left = tree;
        }
        else {
            left = q.front();
            q.pop();
        }

        op = q.front();
        q.pop();
        right = q.front();
        q.pop();

        tree = makeTree(join(op, left, right), q);
    }
    return tree;
}

/* boilerplate to turn the queue into a real AbstractExpression tree;
   return the generated AE tree by reference to allow deletion (the queue
   is emptied by the tree building process) */
AbstractExpression * convertToExpression(queue<AE*> &e) {
    AE *tree = makeTree(NULL, e);
    Json::Value json = tree->serializeValue();
    Json::FastWriter writer;
    std::string jsonText = writer.write(json);

    PlannerDomRoot domRoot(jsonText.c_str());

    AbstractExpression * exp = AbstractExpression::buildExpressionTree(domRoot());
    delete tree;
    return exp;
}

class ExpressionTest : public Test {
    public:
        ExpressionTest() {
        }
};

/*
 * Show that simple addition works with the framework
 */
TEST_F(ExpressionTest, SimpleAddition) {
    queue<AE*> e;
    TableTuple junk;

    // 1 + 4
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)1));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, ValueType::tTINYINT, 1));
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)4));
    boost::scoped_ptr<AbstractExpression> testexp(convertToExpression(e));

    NValue result = testexp->eval(&junk,NULL);
    ASSERT_EQ(ValuePeeker::peekAsBigInt(result), 5LL);
}

/*
 * Show that unary minus works with the framework
 */
TEST_F(ExpressionTest, SimpleUnaryMinus) {
    queue<AE*> e;
    TableTuple junk;

    // -5
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)5));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_UNARY_MINUS, ValueType::tTINYINT, 1));
    // dummy right expression to prevent segmentation fault
    // since unary minus is the only arithmetic operator with one operand
    e.push(NULL);

    boost::scoped_ptr<AbstractExpression> testexp1(convertToExpression(e));
    NValue r1 = testexp1->eval(&junk,NULL);
    ASSERT_EQ(ValuePeeker::peekAsBigInt(r1), -5LL);

    // -(-3)
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)3));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_UNARY_MINUS, ValueType::tTINYINT, 1));
    // dummy right expression to prevent segmentation fault
    e.push(NULL);
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_UNARY_MINUS, ValueType::tTINYINT, 1));
    // dummy right expression to prevent segmentation fault
    e.push(NULL);

    boost::scoped_ptr<AbstractExpression> testexp2(convertToExpression(e));
    NValue r2 = testexp2->eval(&junk,NULL);
    ASSERT_EQ(ValuePeeker::peekAsBigInt(r2), 3LL);
}

/*
 * Show that the associative property is as expected
 */
TEST_F(ExpressionTest, SimpleMultiplication) {
    queue<AE*> e;
    TableTuple junk;

    // (1 + 4) * 5
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)1));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, ValueType::tTINYINT, 1));
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)4));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_MULTIPLY, ValueType::tTINYINT, 1));
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)5));

    boost::scoped_ptr<AbstractExpression> e1(convertToExpression(e));
    NValue r1 = e1->eval(&junk,NULL);
    ASSERT_EQ(ValuePeeker::peekAsBigInt(r1), 25LL);

    // (2 * 5) + 3
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)2));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_MULTIPLY, ValueType::tTINYINT, 1));
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)5));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, ValueType::tTINYINT, 1));
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)3));

    boost::scoped_ptr<AbstractExpression> e2(convertToExpression(e));
    NValue r2 = e2->eval(&junk,NULL);
    ASSERT_EQ(ValuePeeker::peekAsBigInt(r2), 13LL);

    // -(1 + 4) * 5
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)1));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_PLUS, ValueType::tTINYINT, 1));
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)4));
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_UNARY_MINUS, ValueType::tTINYINT, 1));
    // dummy right expression to prevent segmentation fault
    e.push(NULL);
    e.push(new AE(EXPRESSION_TYPE_OPERATOR_MULTIPLY, ValueType::tTINYINT, 1));
    e.push(new CV(EXPRESSION_TYPE_VALUE_CONSTANT, ValueType::tTINYINT, 1, (int64_t)5));

    boost::scoped_ptr<AbstractExpression> testexp3(convertToExpression(e));
    NValue r3 = testexp3->eval(&junk,NULL);
    ASSERT_EQ(ValuePeeker::peekAsBigInt(r3), -25LL);
}

/*
 * Show that the hash range expression correctly selects (or doesn't) rows in ranges
 */
TEST_F(ExpressionTest, HashRange) {
    queue<AE*> e;

    const int32_t range1Max = -(numeric_limits<int32_t>::max() / 2);
    const int32_t range1Min = numeric_limits<int32_t>::min() - (range1Max / 2);
    const int32_t range2Min = 0;
    const int32_t range2Max = numeric_limits<int32_t>::max() / 2;
    const int32_t range3Min = range2Max + (range2Max / 2);
    const int32_t range3Max = numeric_limits<int32_t>::max();

    int32_t ranges[][2] = {
            { range1Min, range1Max},
            { range2Min, range2Max},
            { range3Min, range3Max}
    };

    boost::scoped_ptr<AE> ae(new HR(1, ranges, 3));
    Json::Value json = ae->serializeValue();
    Json::FastWriter writer;
    std::string jsonText = writer.write(json);
    PlannerDomRoot domRoot(jsonText.c_str());
    boost::scoped_ptr<AbstractExpression> e1(AbstractExpression::buildExpressionTree(domRoot()));

    vector<std::string> columnNames;
    columnNames.push_back("foo");
    columnNames.push_back("bar");

    vector<int32_t> columnSizes;
    columnSizes.push_back(8);
    columnSizes.push_back(4);

    vector<bool> allowNull;
    allowNull.push_back(true);
    allowNull.push_back(false);

    vector<voltdb::ValueType> types;
    types.push_back(voltdb::ValueType::tBIGINT);
    types.push_back(voltdb::ValueType::tINTEGER);

    TupleSchema *schema = TupleSchema::createTupleSchemaForTest(types,columnSizes,allowNull);

    boost::scoped_array<char> tupleStorage(new char[schema->tupleLength() + TUPLE_HEADER_SIZE]);

    TableTuple t(tupleStorage.get(), schema);
    const time_t seed = time(NULL);
    std::cout << "Seed " << seed << std::endl;
    srand(static_cast<unsigned int>(seed));

    for (int ii = 0; ii < 100000; ii++) {
        NValue val = ValueFactory::getIntegerValue(rand());
        const int32_t hash = val.murmurHash3();
        t.setNValue(1, val);
        NValue inrange = e1->eval( &t );
        if ((hash >= range1Min && hash <= range1Max) ||
             (hash >= range2Min && hash <= range2Max) ||
             (hash >= range3Min && hash <= range3Max)) {
             //We no longer allow wrapping so this condition isn't true
             //(hash >= range3Min || hash < range3Max)) {
            ASSERT_TRUE(inrange.isTrue());
        } else {
            ASSERT_FALSE(inrange.isTrue());
        }
    }
    TupleSchema::freeTupleSchema(schema);
}

TEST_F(ExpressionTest, Timestamp) {
    int64_t epoch_micros = -8881540068000000; // timestamp from "1688-07-21 09:32:12"
    boost::posix_time::ptime input_ptime = EPOCH + boost::posix_time::microseconds(epoch_micros);
    boost::gregorian::date as_date = input_ptime.date();
    ASSERT_EQ(as_date.year(), 1688);
    ASSERT_EQ(as_date.month(), 7);
    ASSERT_EQ(as_date.day(), 21);
    boost::posix_time::time_duration as_time = input_ptime.time_of_day();
    ASSERT_EQ(as_time.hours(), 9);
    ASSERT_EQ(as_time.minutes(), 32);
    ASSERT_EQ(as_time.seconds(), 12);

    // test loweset timestamp to support
    epoch_micros = GREGORIAN_EPOCH;
    input_ptime = EPOCH + boost::posix_time::microseconds(epoch_micros);
    as_date = input_ptime.date();
    ASSERT_EQ(as_date.year(), 1583);
    ASSERT_EQ(as_date.month(), 1);
    ASSERT_EQ(as_date.day(), 1);
    as_time = input_ptime.time_of_day();
    ASSERT_EQ(as_time.hours(), 0);
    ASSERT_EQ(as_time.minutes(), 0);
    ASSERT_EQ(as_time.seconds(), 0);

}

int main() {
     return TestSuite::globalInstance()->runAll();
}

ext: cpp

max_stars_repo_name: OpenMPDK/SMDK


text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2012, 2013 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include <BeastConfig.h>
#include <boost/algorithm/string.hpp>
#include <ripple/app/tx/impl/PaymentCT.h>
#include <ripple/app/main/Application.h>
#include <ripple/app/misc/NetworkOPs.h>
#include <ripple/protocol/Indexes.h>

#include <secp256k1.h>
#include <secp256k1_rangeproof.h>

namespace ripple {

TER
PaymentCT::preflight (PreflightContext const& ctx)
{
    // check vbc only
    STAmount amount = ctx.tx.getFieldAmount(sfAmount);
    if(!isVBC(amount)){
        return temBAD_AMOUNT;
    }
    return tesSUCCESS;
}

TER
DepositCT::preclaim(PreclaimContext const& ctx){
    return tesSUCCESS;

}

TER
DepositCT::doApply()
{
    auto& app = ctx_.app;
    const uint32_t curLgrSeq = view().info().seq;

    STAmount const saAmount (ctx_.tx.getFieldAmount (sfAmount));
    uint256 const txPubKey(ctx_.tx.getFieldU256(sfTxPublicKey)); // tx_private_key(random)
    STArray const commits (ctx_.tx.getFieldArray (sfCommitments));

    static secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY | SECP256K1_CONTEXT_SIGN);

    for(auto const commit : commits){
        if(commit.getFieldU8(sfCommitType) == CommitType::paymentCommit){
            //paymentCommit
        }
        uint256 blind = commit.getFieldU256(sfMaskCT);
        uint256 commitment = commit.getFieldU256(sfCommitment);
        uint64_t shieldValue = commit.getFieldU64(sfShieldValue);
        Blob proof = commit.getFieldVL(sfProof);

        // verify
        uint64_t minv = 0;
        uint64_t maxv = MAX_UINT64 - 1;
        int len = sizeof(proof);
        if(secp256k1_rangeproof_verify(ctx, &minv, &maxv, &commitment, proof, len, NULL, 0, secp256k1_generator_h) == 0){
            JLOG(j.error) << "Rangeproof verify error";
            return tefNO_AUTH_REQUIRED;
        }
    }

    // set account ctsle to change mask/value

    // create dst sle
    auto k = keylet::ct(commit, curLgrSeq)
    auto dstSle = view()->peek(k);
    if(dstSle){
        JLOG(j.error) << "commitment sle exists";
        return tefINTERNAL;
    }else{
        auto sle = std::make_shared<SLE>(k);
        sle->setFieldU256(sfMaskCT, );
        sle->setFieldU256(sfShieldValue);
    }

    return tesSUCCESS;
}

}// ripple

max_stars_repo_name: radrbiz/radard


text:
/*
 * Copyright 2016 Applied Research Center for Computer Networks
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/** @file */

#pragma once

#include <boost/lexical_cast.hpp>
#include "Common.hh"
#include "json11.hpp"
#include "Controller.hh"
#include "Switch.hh"

// This module contains string-oriented stuff used in RestMultipart and ReatFlowMod

//******************************PART 1: FUNCTIONS******************************
/// use instead of lexical_cast when need to interpret (u)int8_t as num, not a char (symbol code)
template<typename T>
inline std::string toString_cast(const T &value, bool toHex=false)
{
    std::stringstream ss;
    if (toHex) {
        ss << "0x" << std::uppercase << std::setfill('0') << std::setw(4) << std::hex;
    }
    ss << value;
    return ss.str();
}

/// works on "0xffffffff" and interpret char as int instead of boost one
template<typename T>
inline T string_cast(const std::string &val)
{
    using LargestType = uint64_t;
    std::stringstream ss;
    if (val[0] == '0' && val[1] == 'x') {
        ss << std::hex;
    }
    ss << val;
    LargestType no_overflow;
    ss >> no_overflow;
    auto ans = static_cast<T>(no_overflow);
    // overflow check
    if (ans != no_overflow) {
        throw std::overflow_error{"Overflow. Check maximal supported values."};
    }
    return ans;
}

template<typename T>
inline T json_cast(const json11::Json &value)
{
    return string_cast<T>(value.string_value());
}

// toJson implementations -- per one for each of above-mentioned variable
// note: methods get non-const parameters because of json11 library issue
json11::Json toJson(std::vector<of13::FlowStats> &stats);
json11::Json toJson(std::vector<of13::PortStats> &stats);
json11::Json toJson(fluid_msg::SwitchDesc &stat);
json11::Json toJson(of13::MultipartReplyAggregate &stat);
json11::Json toJson(std::vector<of13::TableStats> &stats);
json11::Json toJson(std::vector<of13::Port> &stats);
json11::Json toJson(std::vector<of13::QueueStats> &stats);

std::map<std::string, json11::Json> processMatch(of13::Match match);
std::map<std::string, json11::Json> processInstructions(of13::InstructionSet instructionSet);
std::vector<json11::Json> processActions(ActionList actions);
json11::Json::object processSetField(of13::OXMTLV *field);

of13::OXMTLV *doSwitch(const std::string &field,
                       const std::string &value);

template<typename T>
T chooseValue(json11::Json::object filter,
              const std::string &field,
              T alternative)
{
    auto res = filter.find(field);
    if (res != filter.end()) {
        return json_cast<T>(res->second);
    } else {
        DVLOG(20) << "Using alternative for field " << field;
        return alternative;
    }
}

/// getting body of the request in Json format
json11::Json::object parse(const std::string &body);

/// checks request for fields that can not be omitted and it's values. If check fails, it throws std::string with description.
void validateRequest(const json11::Json::object &req,
                     const std::string &mode,
                     Controller *ctrl,
                     SwitchManager *sw_m);

//******************************PART 2: NAMESPACES******************************
/// By careful in use: using can override some symbols
/// note: implemented by typedefs instead of defines, because can't specify order of macro substitution
namespace fluid_fix
{
    namespace matches
    {
        typedef of13::InPort in_port;
        typedef of13::InPhyPort in_phy_port;
        typedef of13::Metadata metadata;
        typedef of13::EthDst eth_dst;
        typedef of13::EthSrc eth_src;
        typedef of13::EthType eth_type;
        typedef of13::VLANVid vlan_vid;
        typedef of13::VLANPcp vlan_pcp;
        typedef of13::IPDSCP ip_dscp;
        typedef of13::IPECN ip_ecn;
        typedef of13::IPProto ip_proto;
        typedef of13::IPv4Src ipv4_src;
        typedef of13::IPv4Dst ipv4_dst;
        typedef of13::TCPSrc tcp_src;
        typedef of13::TCPDst tcp_dst;
        typedef of13::UDPSrc udp_src;
        typedef of13::UDPDst udp_dst;
        typedef of13::SCTPSrc sctp_src;
        typedef of13::SCTPDst sctp_dst;
        typedef of13::ICMPv4Type icmpv4_type;
        typedef of13::ICMPv4Code icmpv4_code;
        typedef of13::ARPOp arp_op;
        typedef of13::ARPSPA arp_spa;
        typedef of13::ARPTPA arp_tpa;
        typedef of13::ARPSHA arp_sha;
        typedef of13::ARPTHA arp_tha;
        typedef of13::IPv6Src ipv6_src;
        typedef of13::IPv6Dst ipv6_dst;
        typedef of13::IPV6Flabel ipv6_flabel;
        typedef of13::ICMPv6Type icmpv6_type;
        typedef of13::ICMPv6Code icmpv6_code;
        typedef of13::MPLSTC mpls_tc;
        typedef of13::MPLSBOS mpls_bos;
        typedef of13::PBBIsid pbb_isid;
        typedef of13::TUNNELId tunnel_id;
        typedef of13::IPv6Exthdr ipv6_exthdr;
        typedef of13::MPLSLabel mpls_label;
    }  // end of nested namespace matches

    namespace actions
    {
        typedef of13::OutputAction OUTPUT;
        typedef of13::CopyTTLOutAction COPY_TTL_OUT;
        typedef of13::CopyTTLInAction COPY_TTL_IN;
        typedef of13::SetMPLSTTLAction SET_MPLS_TTL;
        typedef of13::DecMPLSTTLAction DEC_MPLS_TTL;
        typedef of13::PushVLANAction PUSH_VLAN;
        typedef of13::PopVLANAction POP_VLAN;
        typedef of13::PushMPLSAction PUSH_MPLS;
        typedef of13::PopMPLSAction POP_MPLS;
        typedef of13::SetQueueAction SET_QUEUE;
        typedef of13::GroupAction GROUP;
        typedef of13::SetNWTTLAction SET_NW_TTL;
        typedef of13::DecNWTTLAction DEC_NW_TTL;
        typedef of13::SetFieldAction SET_FIELD;
        typedef of13::PushPBBAction PUSH_PBB;
        typedef of13::PopPBBAction POP_PBB;
        typedef of13::ExperimenterAction EXPERIMENTER;
        // todo: not implemented:
//            COPY_FIELD
//    METER
//
//    GOTO_TABLE
//            WRITE_METADATA
//    METER
//            WRITE_ACTIONS
//    CLEAR_ACTIONS
    }  // end of namespace actions
}  // end of namespace fluid_fix

// ************************************PART 3: MACROS*********************************************
// macros for path construction
#define DPID_ "[0-9]+"
#define DPID_ALL_ "(all|[0-9]+)"
#define PORTNUMBER_ "[0-9]+"
#define PORTNUMBER_ALL_ "(all|[0-9]+)"
#define QUEUEID_ALL_ "(all|[0-9]+)"

ext: hh

max_stars_repo_name: Alexey-Ershov/runos

max_issues_repo_name: Alexey-Ershov/runos

max_forks_repo_name: Alexey-Ershov/runos


text:
//  Copyright (c) 2007-2017 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#if !defined(HPX_TRAITS_FUTURE_ACCESS_JUN_24_2015_0930AM)
#define HPX_TRAITS_FUTURE_ACCESS_JUN_24_2015_0930AM

#include <hpx/config.hpp>
#include <hpx/traits/future_traits.hpp>

#include <boost/intrusive_ptr.hpp>

#include <type_traits>
#include <utility>
#include <vector>

namespace hpx { namespace lcos
{
    template <typename R> class future;
    template <typename R> class shared_future;

    namespace detail
    {
        template <typename Result> struct future_data_base;
    }
}}

namespace hpx { namespace traits
{
    ///////////////////////////////////////////////////////////////////////////
    namespace detail
    {
        struct future_data_void {};

        template <typename Result>
        struct shared_state_ptr_result
        {
            typedef Result type;
        };

        template <typename Result>
        struct shared_state_ptr_result<Result&>
        {
            typedef Result& type;
        };

        template <>
        struct shared_state_ptr_result<void>
        {
            typedef future_data_void type;
        };

        template <typename R>
        struct shared_state_ptr
        {
            typedef typename shared_state_ptr_result<R>::type result_type;
            typedef boost::intrusive_ptr<
                lcos::detail::future_data_base<result_type>>
                type;
        };

        template <typename Future, typename Enable = void>
        struct shared_state_ptr_for
          : shared_state_ptr<typename traits::future_traits<Future>::type>
        {};

        template <typename Future>
        struct shared_state_ptr_for<Future const>
          : shared_state_ptr_for<Future>
        {};

        template <typename Future>
        struct shared_state_ptr_for<Future&>
          : shared_state_ptr_for<Future>
        {};

        template <typename Future>
        struct shared_state_ptr_for<Future &&>
          : shared_state_ptr_for<Future>
        {};

        template <typename Future>
        struct shared_state_ptr_for<std::vector<Future> >
        {
            typedef std::vector<
                    typename shared_state_ptr_for<Future>::type
                > type;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename SharedState, typename Allocator>
        struct shared_state_allocator;
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename T, typename Enable = void>
    struct is_shared_state
      : std::false_type
    {};

    template <typename R>
    struct is_shared_state<
            boost::intrusive_ptr<lcos::detail::future_data_base<R> > >
      : std::true_type
    {};

    ///////////////////////////////////////////////////////////////////////////
    namespace detail
    {
        template <typename T, typename Enable = void>
        struct future_access_customization_point;
    }

    template <typename T>
    struct future_access
      : detail::future_access_customization_point<T>
    {};

    template <typename R>
    struct future_access<lcos::future<R> >
    {
        template <typename SharedState>
        static lcos::future<R>
        create(boost::intrusive_ptr<SharedState> const& shared_state)
        {
            return lcos::future<R>(shared_state);
        }

        template <typename T = void>
        static lcos::future<R>
        create(typename detail::shared_state_ptr_for<
            lcos::future<lcos::future<R>>>::type const& shared_state)
        {
            return lcos::future<lcos::future<R>>(shared_state);
        }

        template <typename SharedState>
        static lcos::future<R> create(
            boost::intrusive_ptr<SharedState>&& shared_state)
        {
            return lcos::future<R>(std::move(shared_state));
        }

        template <typename T = void>
        static lcos::future<R> create(typename detail::shared_state_ptr_for<
            lcos::future<lcos::future<R>>>::type&& shared_state)
        {
            return lcos::future<lcos::future<R>>(std::move(shared_state));
        }

        template <typename SharedState>
        static lcos::future<R>
        create(SharedState* shared_state)
        {
            return lcos::future<R>(
                boost::intrusive_ptr<SharedState>(shared_state));
        }

        HPX_FORCEINLINE static
        typename traits::detail::shared_state_ptr<R>::type const&
        get_shared_state(lcos::future<R> const& f)
        {
            return f.shared_state_;
        }

        HPX_FORCEINLINE static
        typename traits::detail::shared_state_ptr<R>::type::element_type*
        detach_shared_state(lcos::future<R> && f)
        {
            return f.shared_state_.detach();
        }
    };

    template <typename R>
    struct future_access<lcos::shared_future<R> >
    {
        template <typename SharedState>
        static lcos::shared_future<R>
        create(boost::intrusive_ptr<SharedState> const& shared_state)
        {
            return lcos::shared_future<R>(shared_state);
        }

        template <typename T = void>
        static lcos::shared_future<R> create(
            typename detail::shared_state_ptr_for<
                lcos::shared_future<lcos::future<R>>>::type const& shared_state)
        {
            return lcos::shared_future<lcos::future<R>>(shared_state);
        }

        template <typename SharedState>
        static lcos::shared_future<R>
        create(boost::intrusive_ptr<SharedState> && shared_state)
        {
            return lcos::shared_future<R>(std::move(shared_state));
        }

        template <typename T = void>
        static lcos::shared_future<R> create(
            typename detail::shared_state_ptr_for<
                lcos::shared_future<lcos::future<R>>>::type&& shared_state)
        {
            return lcos::shared_future<lcos::future<R>>(
                std::move(shared_state));
        }

        template <typename SharedState>
        static lcos::shared_future<R>
        create(SharedState* shared_state)
        {
            return lcos::shared_future<R>(
                boost::intrusive_ptr<SharedState>(shared_state));
        }

        HPX_FORCEINLINE static
        typename traits::detail::shared_state_ptr<R>::type const&
        get_shared_state(lcos::shared_future<R> const& f)
        {
            return f.shared_state_;
        }

        HPX_FORCEINLINE static
        typename traits::detail::shared_state_ptr<R>::type::element_type*
        detach_shared_state(lcos::shared_future<R> const& f)
        {
            return f.shared_state_.get();
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    template <typename SharedState, typename Allocator>
    struct shared_state_allocator
      : detail::shared_state_allocator<SharedState, Allocator>
    {};
}}

#endif

max_stars_repo_name: ShmuelLevine/hpx

max_issues_repo_name: Jakub-Golinowski/hpx

max_forks_repo_name: Jakub-Golinowski/hpx


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2020 Alexander Sokolov <asokolov@nil.foundation>
// Copyright (c) 2021 Aleksei Moskvin <alalmoskvin@gmail.com>
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//---------------------------------------------------------------------------//

#ifndef CRYPTO3_KECCAK_FINALIZER_HPP
#define CRYPTO3_KECCAK_FINALIZER_HPP

#include <nil/crypto3/hash/detail/keccak/keccak_policy.hpp>
#include <nil/crypto3/hash/type_traits.hpp>

#include <boost/endian/conversion.hpp>

namespace nil {
    namespace crypto3 {
        namespace hashes {
            namespace detail {
                template<typename PolicyType>
                class keccak_1600_finalizer {
                    typedef PolicyType policy_type;

                    constexpr static const std::size_t word_bits = policy_type::word_bits;
                    typedef typename policy_type::word_type word_type;

                    constexpr static const std::size_t state_bits = policy_type::state_bits;
                    constexpr static const std::size_t state_words = policy_type::state_words;
                    typedef typename policy_type::state_type state_type;

                    constexpr static const std::size_t block_bits = policy_type::block_bits;
                    constexpr static const std::size_t block_words = policy_type::block_words;
                    typedef typename policy_type::block_type block_type;

                    constexpr static const std::size_t digest_bits = policy_type::digest_bits;
                    constexpr static const std::size_t digest_blocks = digest_bits / block_bits;
                    constexpr static const std::size_t last_digest_bits = digest_bits % block_bits;
                    constexpr static const std::size_t last_digest_words =
                        last_digest_bits / word_bits + ((last_digest_bits % word_bits) ? 1 : 0);

                    typedef typename policy_type::digest_type digest_type;
                    typedef keccak_1600_functions<digest_bits> policy_func_type;
                    typedef typename policy_func_type::impl_type impl_type;
                    typedef typename policy_func_type::const_impl_type const_impl_type;

                public:
                    void operator()(state_type &state) {
                        state_type temp_state;
                        std::fill(temp_state.begin(), temp_state.end(), 0);

                        for (std::size_t i = 0; i != digest_blocks; ++i) {
                            for (std::size_t j = 0; j != block_words; ++j)
                                temp_state[i * block_words + j] = state[j];

                            for (std::size_t i = 0; i != state_words; ++i)
                                boost::endian::endian_reverse_inplace(state[i]);

                            if (!CRYPTO3_IS_CONST_EVALUATED(state)) {
                                impl_type::permute(state);
                            } else {
                                const_impl_type::permute(state);
                            }

                            for (std::size_t i = 0; i != state_words; ++i)
                                boost::endian::endian_reverse_inplace(state[i]);
                        }

                        if (last_digest_bits) {
                            for (std::size_t j = 0; j != last_digest_words; ++j)
                                temp_state[digest_blocks * block_words + j] = state[j];
                        }

                        state = temp_state;
                    }
                };
            }    // namespace detail
        }        // namespace hashes
    }            // namespace crypto3
}    // namespace nil

#endif    // CRYPTO3_KECCAK_FINALIZER_HPP

max_stars_repo_name: NilFoundation/hash

max_issues_repo_name: NilFoundation/hash


text:
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
int main()
{
   Matrix3f A;
   A << 1, 2, 5,
        2, 1, 4,
        3, 0, 3;
   cout << "Here is the matrix A:\n" << A << endl;
   FullPivLU<Matrix3f> lu_decomp(A);
   // lu_decomp.setThreshold(1e-5);
   cout << "The rank of A is " << lu_decomp.rank() << endl;
   cout << "Here is a matrix whose columns form a basis of the null-space of A:\n"
        << lu_decomp.kernel() << endl;
   cout << "Here is a matrix whose columns form a basis of the column-space of A:\n"
        << lu_decomp.image(A) << endl; // yes, have to pass the original A
}


text:
//////////////////////////////////////////////////////////////////////////////
///   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
///   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI
///
///          Distributed under the Boost Software License, Version 1.0
///                 See accompanying file LICENSE.txt or copy at
///                     http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#define NT2_UNIT_MODULE "nt2 gsl_specfun toolbox - gsl_sf_choose - unit/scalar Mode"

//#include <nt2/toolbox/gsl_specfun/include/gsl_sf_choose.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <boost/type_traits/is_same.hpp>

//////////////////////////////////////////////////////////////////////////////
// Test behavior of gsl_specfun component gsl_sf_choose using NT2_TEST_CASE
//////////////////////////////////////////////////////////////////////////////
//NT2_TEST_CASE_TPL ( gsl_specfun,  (double)(nt2::uint64_t)(nt2::int64_t)
//                          (float)(nt2::uint32_t)(nt2::int32_t)
//                          (nt2::uint16_t)(nt2::int16_t)
//                          (nt2::uint8_t)(nt2::int8_t)
//                          (bool)
//                  )
//{
//  using nt2::gsl_sf_choose;
//  using nt2::functors::gsl_sf_choose_;
//
//  NT2_TEST( (boost::is_same<typename nt2::meta::call<gsl_specfun_(T, T)>::type,
//                            typename std::tr1::result_of<nt2::meta::floating<($self.const_T_type_list$)>::type
//                            >::value)
//          );
//}


text:
/// @file
/// @brief

#include <boost/test/unit_test.hpp>

BOOST_TEST_DECORATOR(
     * boost::unit_test::label( "suites" )
     * boost::unit_test::description( "Test suites usage examples" )
     )
BOOST_AUTO_TEST_SUITE( RootTestSuite )
     BOOST_AUTO_TEST_CASE( TestCase1 )
     {
          BOOST_TEST_WARN( 0 != 1 );
     }
     BOOST_AUTO_TEST_CASE( TestCase2 )
     {
          BOOST_TEST_REQUIRE( 4 == 4 );
//          BOOST_FAIL( "Unreachable code!" );
     }
     BOOST_AUTO_TEST_SUITE( ChildTestSuite )
          BOOST_AUTO_TEST_CASE( ChildTestCase1 )
          {
               BOOST_TEST( true );
          }
     BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()


text:
#include <TestSupport.h>
#include <ConfigKit/Store.h>
#include <boost/bind.hpp>
#include <algorithm>

using namespace Passenger;
using namespace std;

namespace tut {
	struct ConfigKit_StoreTest: public TestBase {
		ConfigKit::Schema schema;
		ConfigKit::Store *config;
		Json::Value doc;
		vector<ConfigKit::Error> errors;

		ConfigKit_StoreTest() {
			config = NULL;
		}

		~ConfigKit_StoreTest() {
			delete config;
		}

		void init() {
			schema.finalize();
			config = new ConfigKit::Store(schema);
		}
	};

	DEFINE_TEST_GROUP(ConfigKit_StoreTest);

	/*********** Test validation ***********/

	TEST_METHOD(1) {
		set_test_name("Validating an empty schema against an empty update set succeeds");

		init();
		config->previewUpdate(doc, errors);
		ensure(errors.empty());
	}

	TEST_METHOD(2) {
		set_test_name("Validating an empty schema against a non-empty update set succeeds");

		init();
		doc["foo"] = "bar";
		config->previewUpdate(doc, errors);
		ensure(errors.empty());
	}

	TEST_METHOD(3) {
		set_test_name("Validating a non-object update set");

		init();
		doc = Json::Value("hello");
		config->previewUpdate(doc, errors);
		ensure_equals(errors.size(), 1u);
		ensure_equals(errors[0].getMessage(), "The JSON document must be an object");
	}

	TEST_METHOD(4) {
		set_test_name("Validating values through ConfigKit::Schema");

		schema.add("foo", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED);
		schema.add("bar", ConfigKit::INT_TYPE, ConfigKit::REQUIRED);
		init();

		doc["bar"] = "string";
		config->previewUpdate(doc, errors);
		std::sort(errors.begin(), errors.end());
		ensure_equals(errors.size(), 2u);
		ensure_equals(errors[0].getMessage(), "'bar' must be an integer");
		ensure_equals(errors[1].getMessage(), "'foo' is required");
	}

	static void addErrorValidator(const ConfigKit::Store &store,
		vector<ConfigKit::Error> &errors)
	{
		errors.push_back(ConfigKit::Error("Cannot read '{{foo}}'!"));
	}

	static void logSecretValidator(const ConfigKit::Store &store,
		vector<ConfigKit::Error> &errors)
	{
		errors.push_back(ConfigKit::Error("'{{secret}}' is " + store["secret"].asString()));
	}

	TEST_METHOD(5) {
		set_test_name("Custom validators");

		schema.add("foo", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED);
		schema.add("secret", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED | ConfigKit::SECRET);
		schema.addValidator(addErrorValidator);
		schema.addValidator(addErrorValidator);
		schema.addValidator(logSecretValidator);
		init();

		doc["secret"] = "42";
		config->previewUpdate(doc, errors);
		std::sort(errors.begin(), errors.end());
		ensure_equals(errors.size(), 4u);
		ensure_equals(errors[0].getMessage(), "'foo' is required");
		ensure_equals(errors[1].getMessage(), "'secret' is 42");
		ensure_equals(errors[2].getMessage(), "Cannot read 'foo'!");
		ensure_equals(errors[3].getMessage(), "Cannot read 'foo'!");
	}

	/*********** Test other stuff ***********/

	TEST_METHOD(10) {
		set_test_name("previewUpdate()");

		schema.add("foo", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED);
		schema.add("bar", ConfigKit::INT_TYPE, ConfigKit::REQUIRED);
		schema.add("secret", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED | ConfigKit::SECRET);
		schema.add("secret_default", ConfigKit::STRING_TYPE, ConfigKit::OPTIONAL | ConfigKit::SECRET, "default");
		schema.add("secret_null", ConfigKit::STRING_TYPE, ConfigKit::OPTIONAL | ConfigKit::SECRET);
		init();

		doc["foo"] = "string";
		doc["baz"] = true;
		doc["secret"] = "my secret";

		Json::Value preview = config->previewUpdate(doc, errors);
		ensure_equals("1 error", errors.size(), 1u);
		ensure_equals(errors[0].getMessage(), "'bar' is required");
		ensure("foo exists", preview.isMember("foo"));
		ensure("bar exists", preview.isMember("bar"));
		ensure("baz does not exists", !preview.isMember("baz"));
		ensure_equals("foo is a string", preview["foo"]["user_value"].asString(), "string");
		ensure("bar is null", preview["bar"]["user_value"].isNull());

		ensure_equals("secret user value is filtered",
			preview["secret"]["user_value"].asString(), "[FILTERED]");
		ensure("secret default value is null",
			preview["secret"]["default_value"].isNull());
		ensure_equals("secret effective value is filtered",
			preview["secret"]["effective_value"].asString(), "[FILTERED]");

		ensure("secret_default user value is null",
			preview["secret_default"]["user_value"].isNull());
		ensure_equals("secret_default default value is filtered",
			preview["secret_default"]["default_value"].asString(), "[FILTERED]");
		ensure_equals("secret_default effective value is filtered",
			preview["secret_default"]["effective_value"].asString(), "[FILTERED]");

		ensure("secret_null user value is null",
			preview["secret_null"]["user_value"].isNull());
		ensure("secret_null has no default value",
			preview["secret_null"]["default_value"].isNull());
		ensure("secret_null effective value is null",
			preview["secret_null"]["effective_value"].isNull());
	}

	TEST_METHOD(12) {
		set_test_name("inspect()");

		schema.add("foo", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED);
		schema.add("bar", ConfigKit::INT_TYPE, ConfigKit::REQUIRED);
		schema.add("secret", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED | ConfigKit::SECRET);
		schema.add("secret_default", ConfigKit::STRING_TYPE, ConfigKit::OPTIONAL | ConfigKit::SECRET, "default");
		schema.add("secret_null", ConfigKit::STRING_TYPE, ConfigKit::OPTIONAL | ConfigKit::SECRET);
		init();

		doc["foo"] = "string";
		doc["bar"] = 123;
		doc["secret"] = "my secret";
		ensure("update succeeds", config->update(doc, errors));
		ensure("no errors", errors.empty());

		Json::Value dump = config->inspect();
		ensure_equals("foo user value", dump["foo"]["user_value"].asString(), "string");
		ensure_equals("foo effective value", dump["foo"]["effective_value"].asString(), "string");
		ensure_equals("bar user value", dump["bar"]["user_value"].asInt(), 123);
		ensure_equals("bar effective value", dump["bar"]["effective_value"].asInt(), 123);

		ensure_equals("secret user value is filtered",
			dump["secret"]["user_value"].asString(), "[FILTERED]");
		ensure("secret default value is null",
			dump["secret"]["default_value"].isNull());
		ensure_equals("secret effective value is filtered",
			dump["secret"]["effective_value"].asString(), "[FILTERED]");

		ensure("secret_default user value is null",
			dump["secret_default"]["user_value"].isNull());
		ensure_equals("secret_default default value is filtered",
			dump["secret_default"]["default_value"].asString(), "[FILTERED]");
		ensure_equals("secret_default effective value is filtered",
			dump["secret_default"]["effective_value"].asString(), "[FILTERED]");

		ensure("secret_null user value is null",
			dump["secret_null"]["user_value"].isNull());
		ensure("secret_null has no default value",
			dump["secret_null"]["default_value"].isNull());
		ensure("secret_null effective value is null",
			dump["secret_null"]["effective_value"].isNull());
	}

	TEST_METHOD(13) {
		set_test_name("Default values");

		schema.add("foo", ConfigKit::STRING_TYPE, ConfigKit::OPTIONAL, "string");
		schema.add("bar", ConfigKit::INT_TYPE, ConfigKit::OPTIONAL, 123);
		init();

		ensure_equals(config->get("foo").asString(), "string");
		ensure_equals(config->get("bar").asInt(), 123);

		Json::Value dump = config->inspect();
		ensure("foo user value", dump["foo"]["user_value"].isNull());
		ensure_equals("foo default value", dump["foo"]["default_value"].asString(), "string");
		ensure_equals("foo effective value", dump["foo"]["effective_value"].asString(), "string");
		ensure("bar user value", dump["bar"]["user_value"].isNull());
		ensure_equals("bar default value", dump["bar"]["default_value"].asInt(), 123);
		ensure_equals("bar effective value", dump["bar"]["effective_value"].asInt(), 123);
	}

	static Json::Value
	getNextValueAndBump(unsigned int *nextValue) {
		unsigned int result = *nextValue;
		(*nextValue)++;
		return result;
	}

	TEST_METHOD(14) {
		set_test_name("Dynamic default values and caching them");
		unsigned int nextValue = 0;

		schema.addWithDynamicDefault("foo", ConfigKit::INT_TYPE,
			ConfigKit::OPTIONAL,
			boost::bind(getNextValueAndBump, &nextValue));
		schema.addWithDynamicDefault("bar", ConfigKit::INT_TYPE,
			ConfigKit::OPTIONAL | ConfigKit::CACHE_DEFAULT_VALUE,
			boost::bind(getNextValueAndBump, &nextValue));
		init();

		ensure_equals("(1)", config->get("foo").asUInt(), 0u);
		ensure_equals("(2)", config->get("foo").asUInt(), 1u);
		ensure_equals("(3)", config->get("bar").asUInt(), 2u);
		ensure_equals("(4)", config->get("bar").asUInt(), 2u);
	}

	TEST_METHOD(15) {
		set_test_name("Read-only keys can only be written to once");

		schema.add("foo", ConfigKit::INT_TYPE,
			ConfigKit::OPTIONAL | ConfigKit::READ_ONLY);
		schema.add("foo2", ConfigKit::INT_TYPE,
			ConfigKit::OPTIONAL | ConfigKit::READ_ONLY);
		init();

		doc["foo"] = 123;
		ensure(config->update(doc, errors));
		doc["foo2"] = 123;
		ensure(config->update(doc, errors));
		ensure_equals(config->get("foo").asInt(), 123);
		ensure(config->get("foo2").isNull());
	}

	static Json::Value normalizeTargetAndLevel(const Json::Value &values) {
		Json::Value updates(Json::objectValue);

		if (values["target"].isString()) {
			updates["target"]["path"] = values["target"];
		}
		if (!startsWith(values["level"].asString(), "L")) {
			updates["level"] = "L" + values["level"].asString();
		}

		return updates;
	}

	TEST_METHOD(17) {
		set_test_name("Normalizers");

		schema.add("target", ConfigKit::ANY_TYPE, ConfigKit::REQUIRED);
		schema.add("level", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED | ConfigKit::READ_ONLY);
		schema.addNormalizer(normalizeTargetAndLevel);
		init();

		doc["target"] = "/path";
		doc["level"] = "1";
		ensure("(1)", config->update(doc, errors));
		doc = config->inspect();

		ensure("(2)", config->get("target").isObject());
		ensure_equals("(3)", config->get("target")["path"].asString(), "/path");
		ensure("(4)", doc["target"]["user_value"].isObject());
		ensure_equals("(5)", doc["target"]["user_value"]["path"].asString(), "/path");
		ensure_equals("(6)", config->get("level").asString(), "L1");
		ensure_equals("(7)", doc["level"]["user_value"].asString(), "L1");

		doc = Json::objectValue;
		doc["level"] = "2";
		ensure("(10)", config->update(doc, errors));
		doc = config->inspect();

		ensure("(11)", config->get("target").isObject());
		ensure_equals("(12)", config->get("target")["path"].asString(), "/path");
		ensure("(13)", doc["target"]["user_value"].isObject());
		ensure_equals("(14)", doc["target"]["user_value"]["path"].asString(), "/path");
		ensure_equals("(15)", config->get("level").asString(), "L1");
		ensure_equals("(16)", doc["level"]["user_value"].asString(), "L1");
	}

	TEST_METHOD(18) {
		set_test_name("Typecasting");

		schema.add("string", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED);
		schema.add("int", ConfigKit::INT_TYPE, ConfigKit::REQUIRED);
		schema.add("uint", ConfigKit::UINT_TYPE, ConfigKit::REQUIRED);
		schema.add("float", ConfigKit::FLOAT_TYPE, ConfigKit::REQUIRED);
		schema.add("bool", ConfigKit::BOOL_TYPE, ConfigKit::REQUIRED);
		schema.add("array", ConfigKit::ARRAY_TYPE, ConfigKit::REQUIRED);
		schema.add("object", ConfigKit::OBJECT_TYPE, ConfigKit::REQUIRED);
		schema.add("any", ConfigKit::ANY_TYPE, ConfigKit::REQUIRED);
		init();

		doc["string"] = 123;
		doc["int"] = -456.78;
		doc["uint"] = 456.78;
		doc["float"] = 123;
		doc["bool"] = 1;
		doc["array"] = Json::arrayValue;
		doc["object"] = Json::objectValue;
		doc["any"] = Json::objectValue;

		Json::Value preview = config->previewUpdate(doc, errors);
		ensure_equals("Validation passes (1)", errors.size(), 0u);
		ensure("Validation passes", config->update(doc, errors));

		ensure(preview["string"]["user_value"].isString());
		ensure(preview["int"]["user_value"].isInt());
		ensure(preview["uint"]["user_value"].isUInt());
		ensure(preview["float"]["user_value"].isDouble());
		ensure(preview["bool"]["user_value"].isBool());
		ensure(preview["array"]["user_value"].isArray());
		ensure(preview["object"]["user_value"].isObject());
		ensure(preview["any"]["user_value"].isObject());

		ensure(config->get("string").isString());
		ensure(config->get("int").isInt());
		ensure(config->get("uint").isUInt());
		ensure(config->get("float").isDouble());
		ensure(config->get("bool").isBool());
		ensure(config->get("array").isArray());
		ensure(config->get("object").isObject());
		ensure(config->get("any").isObject());

		ensure_equals(preview["string"]["user_value"].asString(), "123");
		ensure_equals(preview["int"]["user_value"].asInt(), -456);
		ensure_equals(preview["uint"]["user_value"].asUInt(), 456u);
		ensure_equals(preview["float"]["user_value"].asDouble(), 123);
		ensure_equals(preview["bool"]["user_value"].asBool(), true);

		ensure_equals(config->get("string").asString(), "123");
		ensure_equals(config->get("int").asInt(), -456);
		ensure_equals(config->get("uint").asUInt(), 456u);
		ensure_equals(config->get("float").asDouble(), 123);
		ensure_equals(config->get("bool").asBool(), true);
	}

	static Json::Value addExclamationFilter(const Json::Value &val) {
		return val.asString() + "!";
	}

	TEST_METHOD(19) {
		set_test_name("Inspect filters");

		schema.add("foo", ConfigKit::STRING_TYPE, ConfigKit::REQUIRED)
			.setInspectFilter(addExclamationFilter);
		init();

		doc["foo"] = "hello";
		ensure("(1)", config->update(doc, errors));
		doc = config->inspect();

		ensure_equals("(2)", config->get("foo").asString(), "hello");
		ensure_equals("(3)", doc["foo"]["user_value"].asString(), "hello!");
		ensure_equals("(4)", doc["foo"]["effective_value"].asString(), "hello!");
	}

	static Json::Value getTest20Default(const ConfigKit::Store &store) {
		return store["a1"].asInt() +
			store["a2"].asInt() +
			store["a4"].asInt() +
			store["a5"].asInt();
	}

	TEST_METHOD(20) {
		set_test_name("Cached dynamic default values that depend on other values");
		using namespace ConfigKit;

		schema.add("a1", INT_TYPE, REQUIRED);
		schema.add("a2", INT_TYPE, REQUIRED);
		schema.addWithDynamicDefault("a3", INT_TYPE,
			OPTIONAL | CACHE_DEFAULT_VALUE, getTest20Default);
		schema.add("a4", INT_TYPE, REQUIRED);
		schema.add("a5", INT_TYPE, REQUIRED);
		init();

		doc["a1"] = 1;
		doc["a2"] = 10;
		doc["a4"] = 100;
		doc["a5"] = 1000;

		ensure("(1)", config->update(doc, errors));
		doc = config->inspect();

		ensure_equals("(2)", config->get("a3").asInt(), 1111);
	}
}

max_stars_repo_name: mjgiarlo/passenger

max_issues_repo_name: philson-philip/passenger

max_forks_repo_name: philson-philip/passenger