text:
#include <QTreeWidgetItem>
#include <QInputDialog>
#include <QHeaderView>
#include <QTreeWidget>
#include <QMessageBox>
#include <QToolButton>
#include <QFileDialog>
#include <QCloseEvent>
#include <QSettings>
#include <QComboBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QTabWidget>
#include <QIcon>
#include <QMenu>
#include <QList>
#include <QUrl>

#include "qlcfixturedefcache.h"
#include "qlcfixturemode.h"
#include "qlcfixturedef.h"
#include "qlccapability.h"
#include "qlcphysical.h"
#include "qlcchannel.h"
#include "qlcconfig.h"
#include "qlcfile.h"

#ifdef Q_WS_X11
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#endif

#include "editcapability.h"
#include "fixtureeditor.h"
#include "editchannel.h"
#include "editmode.h"
#include "util.h"
#include "app.h"

extern App* _app;
extern int errno;

#define PROP_PTR Qt::UserRole

#define CH_COL_NAME 0
#define CH_COL_GRP  1

#define MODE_COL_NAME 0
#define MODE_COL_CHS  1
#define MODE_COL_HEAD 2

#define SETTINGS_GEOMETRY "fixtureeditor/geometry"

QLCFixtureEditor::QLCFixtureEditor(QWidget* parent, QLCFixtureDef* fixtureDef,
                                   const QString& fileName)
    : QWidget(parent)
    , m_fixtureDef(fixtureDef)
    , m_fileName(fileName)
    , m_modified(false)
{
    setupUi(this);
    init();
    setCaption();

    setModified(false);

    /* Connect to be able to enable/disable clipboard actions */
    connect(_app, SIGNAL(clipboardChanged()),
            this, SLOT(slotClipboardChanged()));

    /* Initial update to clipboard actions */
    slotClipboardChanged();

    QSettings settings;
    QVariant var = settings.value(SETTINGS_GEOMETRY);
    if (var.isValid() == true)
        parentWidget()->restoreGeometry(var.toByteArray());
}

QLCFixtureEditor::~QLCFixtureEditor()
{
    QSettings settings;
    settings.setValue(SETTINGS_GEOMETRY, parentWidget()->saveGeometry());

    delete m_fixtureDef;
    m_fixtureDef = NULL;
}

void QLCFixtureEditor::init()
{
    /* General page */
    m_manufacturerEdit->setText(m_fixtureDef->manufacturer());
    m_manufacturerEdit->setValidator(CAPS_VALIDATOR(this));
    connect(m_manufacturerEdit, SIGNAL(textEdited(const QString&)),
            this, SLOT(slotManufacturerTextEdited(const QString&)));

    m_modelEdit->setText(m_fixtureDef->model());
    m_modelEdit->setValidator(CAPS_VALIDATOR(this));
    connect(m_modelEdit, SIGNAL(textEdited(const QString&)),
            this, SLOT(slotModelTextEdited(const QString&)));

    m_typeCombo->setCurrentIndex(m_typeCombo->findText(m_fixtureDef->type()));
    connect(m_typeCombo, SIGNAL(activated(const QString&)),
            this, SLOT(slotTypeActivated(const QString&)));

    // Display author name or suggest current user name if there isn't one.
    // When the def already has an author, disable the field to prevent modification.
    m_authorEdit->setText(m_fixtureDef->author());
    if (m_authorEdit->text().length() > 0)
        m_authorEdit->setEnabled(false);
    else
        m_authorEdit->setText(QLCFile::currentUserName());

    /* Channel page */
    connect(m_addChannelButton, SIGNAL(clicked()),
            this, SLOT(slotAddChannel()));
    connect(m_removeChannelButton, SIGNAL(clicked()),
            this, SLOT(slotRemoveChannel()));
    connect(m_editChannelButton, SIGNAL(clicked()),
            this, SLOT(slotEditChannel()));
    connect(m_copyChannelButton, SIGNAL(clicked()),
            this, SLOT(slotCopyChannel()));
    connect(m_pasteChannelButton, SIGNAL(clicked()),
            this, SLOT(slotPasteChannel()));
    connect(m_expandChannelsButton, SIGNAL(clicked()),
            this, SLOT(slotExpandChannels()));

    connect(m_channelList, SIGNAL(currentItemChanged(QTreeWidgetItem*,
                                  QTreeWidgetItem*)),
            this, SLOT(slotChannelListSelectionChanged(QTreeWidgetItem*)));
    connect(m_channelList, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(slotChannelListContextMenuRequested()));
    connect(m_channelList, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
            this, SLOT(slotEditChannel()));
    connect(m_channelList, SIGNAL(expanded(QModelIndex)),
            this, SLOT(slotChannelItemExpanded()));

    m_channelList->setContextMenuPolicy(Qt::CustomContextMenu);
    m_channelList->setIconSize(QSize(24, 24));
    refreshChannelList();

    /* Mode page */
    connect(m_addModeButton, SIGNAL(clicked()),
            this, SLOT(slotAddMode()));
    connect(m_removeModeButton, SIGNAL(clicked()),
            this, SLOT(slotRemoveMode()));
    connect(m_editModeButton, SIGNAL(clicked()),
            this, SLOT(slotEditMode()));
    connect(m_cloneModeButton, SIGNAL(clicked()),
            this, SLOT(slotCloneMode()));
    connect(m_expandModesButton, SIGNAL(clicked()),
            this, SLOT(slotExpandModes()));

    connect(m_modeList, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
            this, SLOT(slotModeListSelectionChanged(QTreeWidgetItem*)));
    connect(m_modeList, SIGNAL(customContextMenuRequested(const QPoint&)),
            this, SLOT(slotModeListContextMenuRequested()));
    connect(m_modeList, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
            this, SLOT(slotEditMode()));
    connect(m_modeList, SIGNAL(expanded(QModelIndex)),
            this, SLOT(slotModeItemExpanded()));

    m_modeList->setContextMenuPolicy(Qt::CustomContextMenu);
    refreshModeList();
}

void QLCFixtureEditor::closeEvent(QCloseEvent* e)
{
    int r = 0;

    if (m_modified)
    {
        r = QMessageBox::information(this, tr("Close"),
                                     tr("Do you want to save changes to fixture\n\""
                                        "%1\"\nbefore closing?").arg(m_fixtureDef->name()),
                                     QMessageBox::Yes,
                                     QMessageBox::No,
                                     QMessageBox::Cancel);

        if (r == QMessageBox::Yes)
            if (save())
                e->accept();
            else
                e->ignore();
        else if (r == QMessageBox::No)
            e->accept();
        else
            e->ignore();
    }
    else
    {
        e->accept();
    }
}

bool QLCFixtureEditor::checkManufacturerModel()
{
    /* Check that the fixture has a manufacturer and a model for
       unique identification */
    if (m_fixtureDef->manufacturer().length() == 0)
    {
        QMessageBox::warning(this,
                             tr("Missing important information"),
                             tr("Missing manufacturer name.\n"
                                "Unable to save fixture."));
        m_tab->setCurrentIndex(0);
        m_manufacturerEdit->setFocus();
        return false;
    }
    else if (m_fixtureDef->model().length() == 0)
    {
        QMessageBox::warning(this,
                             tr("Missing important information"),
                             tr("Missing fixture model name.\n"
                                "Unable to save fixture."));
        m_tab->setCurrentIndex(0);
        m_modelEdit->setFocus();
        return false;
    }

    return true;
}

bool QLCFixtureEditor::save()
{
    if (checkManufacturerModel() == false)
        return false;

    if (m_fileName.simplified().isEmpty() == true)
    {
        return saveAs();
    }
    else
    {
        QFile::FileError error = m_fixtureDef->saveXML(m_fileName);
        if (error == QFile::NoError)
        {
            setModified(false);
            return true;
        }
        else
        {
            QMessageBox::critical(this, tr("Fixture saving failed"),
                                  tr("Unable to save fixture definition:\n%1")
                                  .arg(QLCFile::errorString(error)));
            return false;
        }
    }
}

bool QLCFixtureEditor::saveAs()
{
    /* Bail out if there is no manufacturer or model */
    if (checkManufacturerModel() == false)
        return false;

    /* Create a file save dialog */
    QFileDialog dialog(this);
    dialog.setWindowTitle(tr("Save fixture definition"));
    dialog.setAcceptMode(QFileDialog::AcceptSave);
    dialog.setNameFilter(KQXFFilter);

    QString path;
    QDir dir = QLCFixtureDefCache::userDefinitionDirectory();
    if (m_fileName.isEmpty() == true)
    {
        /* Construct a new path for the (yet) unnamed file */
        QString man = m_fixtureDef->manufacturer().replace(" ", "-");
        QString mod = m_fixtureDef->model().replace(" ", "-");
        path = QString("%1-%2%3").arg(man).arg(mod).arg(KExtFixture);
        dialog.setDirectory(dir);
        dialog.selectFile(path);
    }
    else
    {
        /* The fixture already has a file name. Use that then. */
        dialog.setDirectory(QDir(m_fileName));
        dialog.selectFile(m_fileName);
    }

    /* Execute the dialog */
    if (dialog.exec() != QDialog::Accepted)
        return false;

    path = dialog.selectedFiles().first();
    if (path.length() != 0)
    {
        if (path.right(strlen(KExtFixture)) != QString(KExtFixture))
            path += QString(KExtFixture);

        QFile::FileError error = m_fixtureDef->saveXML(path);
        if (error == QFile::NoError)
        {
            m_fileName = path;
            setCaption();
            setModified(false);
            return true;
        }
        else
        {
            QMessageBox::critical(this, tr("Fixture saving failed"),
                                  tr("Unable to save fixture definition:\n%1")
                                  .arg(QLCFile::errorString(error)));
            return false;
        }
    }
    else
    {
        return false;
    }
}

void QLCFixtureEditor::setCaption()
{
    QString caption;
    QString fileName;

    fileName = m_fileName;
    if (fileName.isEmpty())
        fileName = tr("New Fixture");

    /* If the document is modified, append an asterisk after the
       filename. Otherwise the caption is just the current filename */
    caption = QDir::toNativeSeparators(fileName);
    if (m_modified == true)
        caption += QString(" *");

    parentWidget()->setWindowTitle(caption);
}

void QLCFixtureEditor::setModified(bool modified)
{
    m_modified = modified;
    setCaption();
}

/*****************************************************************************
 * General tab functions
 *****************************************************************************/

void QLCFixtureEditor::slotManufacturerTextEdited(const QString &text)
{
    m_fixtureDef->setManufacturer(text);
    setModified();
}

void QLCFixtureEditor::slotModelTextEdited(const QString &text)
{
    m_fixtureDef->setModel(text);
    setModified();
}

void QLCFixtureEditor::slotTypeActivated(const QString &text)
{
    m_fixtureDef->setType(text);
    setModified();
}

/*****************************************************************************
 * Channels tab functions
 *****************************************************************************/

void QLCFixtureEditor::slotChannelListSelectionChanged(QTreeWidgetItem* item)
{
    if (item == NULL)
    {
        m_removeChannelButton->setEnabled(false);
        m_editChannelButton->setEnabled(false);
        m_copyChannelButton->setEnabled(false);
    }
    else
    {
        m_removeChannelButton->setEnabled(true);
        m_editChannelButton->setEnabled(true);
        m_copyChannelButton->setEnabled(true);
    }
}

void QLCFixtureEditor::slotAddChannel()
{
    EditChannel ec(this);

    bool ok = false;
    while (ok == false)
    {
        if (ec.exec() == QDialog::Accepted)
        {
            if (m_fixtureDef->channel(ec.channel()->name()) != NULL)
            {
                QMessageBox::warning(this,
                                     tr("Channel already exists"),
                                     tr("A channel by the name \"%1\" already exists!")
                                     .arg(ec.channel()->name()));
                ok = false;
            }
            else if (ec.channel()->name().length() == 0)
            {
                QMessageBox::warning(this,
                                     tr("Channel has no name"),
                                     tr("You must give the channel a descriptive name!"));
                ok = false;
            }
            else
            {
                /* Create a new channel and item for it */
                QTreeWidgetItem* item;
                QLCChannel* ch;

                ch = new QLCChannel(ec.channel());
                item = new QTreeWidgetItem(m_channelList);

                m_fixtureDef->addChannel(ch);
                updateChannelItem(ch, item);
                m_channelList->setCurrentItem(item);
                m_channelList->resizeColumnToContents(CH_COL_NAME);

                setModified();
                ok = true;
            }
        }
        else
        {
            /* Cancel pressed */
            ok = true;
        }
    }
}

void QLCFixtureEditor::slotRemoveChannel()
{
    QLCChannel* channel = currentChannel();
    Q_ASSERT(channel != NULL);

    if (QMessageBox::question(this, "Remove Channel",
                              tr("Are you sure you wish to remove channel: %1")
                              .arg(channel->name()),
                              QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
    {
        QTreeWidgetItem* item;
        QTreeWidgetItem* next;

        item = m_channelList->currentItem();
        if (m_channelList->itemBelow(item) != NULL)
            next = m_channelList->itemBelow(item);
        else if (m_channelList->itemAbove(item) != NULL)
            next = m_channelList->itemAbove(item);
        else
            next = NULL;

        // Remove the selected channel from the fixture (also deleted)
        m_fixtureDef->removeChannel(currentChannel());
        delete item;

        m_channelList->setCurrentItem(next);
        setModified();
    }
}

void QLCFixtureEditor::slotEditChannel()
{
    QLCChannel* real = NULL;
    QTreeWidgetItem* item = NULL;

    // Initialize the dialog with the selected logical channel or
    // bail out if there is no current selection
    real = currentChannel();
    if (real == NULL)
        return;

    EditChannel ec(this, real);
    if (ec.exec() == QDialog::Accepted)
    {
        if (m_fixtureDef->channel(ec.channel()->name()) != NULL && ec.channel()->name() != real->name())
        {
            QMessageBox::warning(this,
                                 tr("Channel already exists"),
                                 tr("A channel by the name \"%1\" already exists!")
                                 .arg(ec.channel()->name()));
        }
        else if (ec.channel()->name().length() == 0)
        {
            QMessageBox::warning(this,
                                 tr("Channel has no name"),
                                 tr("You must give the channel a descriptive name!"));
        }
        else
        {
            // Copy the channel's contents to the real channel
            *real = *(ec.channel());

            item = m_channelList->currentItem();
            updateChannelItem(real, item);
            m_channelList->resizeColumnToContents(CH_COL_NAME);

            setModified();
        }
    }
}

void QLCFixtureEditor::slotCopyChannel()
{
    _app->setCopyChannel(currentChannel());
}

void QLCFixtureEditor::slotPasteChannel()
{
    QLCChannel* ch = _app->copyChannel();
    if (ch != NULL && m_fixtureDef != NULL)
    {
        /* Create new mode and an item for it */
        QTreeWidgetItem* item;
        QLCChannel* copy;

        copy = new QLCChannel(ch);
        item = new QTreeWidgetItem(m_channelList);

        int cpIdx = 1;
        QString copyName;
        do
        {
            copyName = QString("%1 %2").arg(ch->name()).arg(cpIdx);
            cpIdx++;
        } while (m_fixtureDef->channel(copyName) != NULL);

        copy->setName(copyName);

        m_fixtureDef->addChannel(copy);
        updateChannelItem(copy, item);
        m_channelList->setCurrentItem(item);
        m_channelList->resizeColumnToContents(CH_COL_NAME);

        setModified();
    }
}

void QLCFixtureEditor::slotExpandChannels()
{
    if (m_channelList->topLevelItemCount() <= 0)
        return;
    else if (m_channelList->topLevelItem(0)->isExpanded() == true)
        m_channelList->collapseAll();
    else
        m_channelList->expandAll();
}

void QLCFixtureEditor::refreshChannelList()
{
    m_channelList->clear();

    /* Fill channels list */
    QListIterator <QLCChannel*> it(m_fixtureDef->channels());
    while (it.hasNext() == true)
        updateChannelItem(it.next(), new QTreeWidgetItem(m_channelList));

    slotChannelListSelectionChanged(m_channelList->currentItem());

    m_channelList->resizeColumnToContents(CH_COL_NAME);
    m_channelList->resizeColumnToContents(CH_COL_GRP);
}

void QLCFixtureEditor::updateChannelItem(const QLCChannel* channel, QTreeWidgetItem* item)
{
    QString str;

    Q_ASSERT(channel != NULL);
    Q_ASSERT(item != NULL);

    item->setText(CH_COL_NAME, channel->name());
    item->setIcon(CH_COL_NAME, channel->getIconFromGroup(channel->group()));
    item->setText(CH_COL_GRP, QLCChannel::groupToString(channel->group()));
    item->setData(CH_COL_NAME, PROP_PTR, (qulonglong) channel);

    /* Destroy the existing list of children */
    QList <QTreeWidgetItem*> children(item->takeChildren());
    foreach (QTreeWidgetItem* child, children)
    delete child;

    /* Put all capabilities as non-selectable sub items */
    QListIterator <QLCCapability*> capit(channel->capabilities());
    while (capit.hasNext() == true)
    {
        QLCCapability* cap = capit.next();
        Q_ASSERT(cap != NULL);

        QTreeWidgetItem* capitem = new QTreeWidgetItem(item);
        capitem->setText(CH_COL_NAME,
                         QString("[%1-%2]: %3").arg(cap->min())
                         .arg(cap->max()).arg(cap->name()));
        capitem->setFlags(0); /* No selection etc. */
    }
}

void QLCFixtureEditor::slotChannelListContextMenuRequested()
{
    QAction editAction(QIcon(":/edit.png"), tr("Edit"), this);
    QAction copyAction(QIcon(":/editcopy.png"), tr("Copy"), this);
    QAction pasteAction(QIcon(":/editpaste.png"), tr("Paste"), this);
    QAction removeAction(QIcon(":/editdelete.png"), tr("Remove"), this);

    /* Group menu */
    QMenu groupMenu;
    groupMenu.setTitle("Set group");
    QStringListIterator it(QLCChannel::groupList());
    while (it.hasNext() == true)
        groupMenu.addAction(it.next());

    /* Master edit menu */
    QMenu menu;
    menu.setTitle(tr("Channels"));
    menu.addAction(&editAction);
    menu.addAction(&copyAction);
    menu.addAction(&pasteAction);
    menu.addSeparator();
    menu.addAction(&removeAction);
    menu.addSeparator();
    menu.addMenu(&groupMenu);

    if (m_channelList->currentItem() == NULL)
    {
        copyAction.setEnabled(false);
        removeAction.setEnabled(false);
    }

    if (_app->copyChannel() == NULL)
        pasteAction.setEnabled(false);

    QAction* selectedAction = menu.exec(QCursor::pos());
    if (selectedAction == NULL)
        return;
    else if (selectedAction->text() == tr("Edit"))
        slotEditChannel();
    else if (selectedAction->text() == tr("Copy"))
        slotCopyChannel();
    else if (selectedAction->text() == tr("Paste"))
        slotPasteChannel();
    else if (selectedAction->text() == tr("Remove"))
        slotRemoveChannel();
    else
    {
        /* Group menu hook */
        QLCChannel* ch = NULL;
        QTreeWidgetItem* node = NULL;

        ch = currentChannel();
        if (ch != NULL)
            ch->setGroup(QLCChannel::stringToGroup(selectedAction->text()));
        node = m_channelList->currentItem();
        if (node != NULL)
            node->setText(CH_COL_GRP, selectedAction->text());
        setModified();
    }
}

void QLCFixtureEditor::slotChannelItemExpanded()
{
    m_channelList->resizeColumnToContents(CH_COL_NAME);
    m_channelList->resizeColumnToContents(CH_COL_GRP);
}

QLCChannel* QLCFixtureEditor::currentChannel()
{
    QLCChannel* ch = NULL;
    QTreeWidgetItem* item = NULL;

    // Convert the string-form ulong to a QLCChannel pointer and return it
    item = m_channelList->currentItem();
    if (item != NULL)
        ch = (QLCChannel*) item->data(CH_COL_NAME, PROP_PTR).toULongLong();

    return ch;
}

/*****************************************************************************
 * Modes tab functions
 *****************************************************************************/

void QLCFixtureEditor::slotModeListSelectionChanged(QTreeWidgetItem* item)
{
    if (item == NULL)
    {
        m_removeModeButton->setEnabled(false);
        m_editModeButton->setEnabled(false);
        m_cloneModeButton->setEnabled(false);
    }
    else
    {
        m_removeModeButton->setEnabled(true);
        m_editModeButton->setEnabled(true);
        m_cloneModeButton->setEnabled(true);
    }
}

void QLCFixtureEditor::slotAddMode()
{
    EditMode em(_app, m_fixtureDef);
    em.setClipboard(m_physicalCopy);
    bool ok = false;
    while (ok == false)
    {
        if (em.exec() == QDialog::Accepted)
        {
            if (m_fixtureDef->mode(em.mode()->name()) != NULL)
            {
                QMessageBox::warning(this,
                                     tr("Unable to add mode"),
                                     tr("Another mode by that name already exists"));

                // User must rename the mode to continue
                ok = false;
            }
            else if (em.mode()->name().length() == 0)
            {
                QMessageBox::warning(this,
                                     tr("Unable to add mode"),
                                     tr("You must give a name to the mode"));
                ok = false;
            }
            else
            {
                /* Create new mode and an item for it */
                QTreeWidgetItem* item;
                QLCFixtureMode* mode;

                mode = new QLCFixtureMode(m_fixtureDef, em.mode());
                item = new QTreeWidgetItem(m_modeList);

                m_fixtureDef->addMode(mode);
                updateModeItem(mode, item);
                m_modeList->setCurrentItem(item);
                m_modeList->resizeColumnToContents(MODE_COL_NAME);

                setModified();
                ok = true;
            }
        }
        else
        {
            /* Cancel pressed */
            ok = true;
        }
    }
    m_physicalCopy = em.getClipboard();
}

void QLCFixtureEditor::slotRemoveMode()
{
    QLCFixtureMode* mode = currentMode();

    if (QMessageBox::question(this, tr("Remove Mode"),
                              tr("Are you sure you wish to remove mode: %1").arg(mode->name()),
                              QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
    {
        m_fixtureDef->removeMode(mode);
        delete m_modeList->currentItem();
        setModified();
    }
}

void QLCFixtureEditor::slotEditMode()
{
    QLCFixtureMode* mode = currentMode();
    QTreeWidgetItem* item = NULL;

    if (mode == NULL)
        return;

    EditMode em(this, mode);
    em.setClipboard(m_physicalCopy);
    if (em.exec() == QDialog::Accepted)
    {
        *mode = *(em.mode());

        item = m_modeList->currentItem();
        updateModeItem(mode, item);
        setModified();
    }
    m_physicalCopy = em.getClipboard();
}

void QLCFixtureEditor::slotCloneMode()
{
    QLCFixtureMode* mode = NULL;
    bool ok = false;
    QString text;

    mode = currentMode();
    if (mode == NULL)
        return;

    while (1)
    {
        text = QInputDialog::getText(this, tr("Rename new mode"),
                                     tr("Give a unique name for the mode"),
                                     QLineEdit::Normal,
                                     tr("Copy of %1").arg(mode->name()),
                                     &ok);

        if (ok == true && text.isEmpty() == false)
        {
            /* User entered a name that is already found from
               the fixture definition -> again */
            if (mode->fixtureDef()->mode(text) != NULL)
            {
                QMessageBox::information(this,
                                         tr("Invalid name"),
                                         tr("Another mode by that name already exists."));
                ok = false;
                continue;
            }

            /* Create new mode and an item for it */
            QTreeWidgetItem* item;
            QLCFixtureMode* clone;

            clone = new QLCFixtureMode(mode->fixtureDef(), mode);
            clone->setName(text);
            item = new QTreeWidgetItem(m_modeList);

            mode->fixtureDef()->addMode(clone);
            updateModeItem(clone, item);
            m_modeList->setCurrentItem(item);

            setModified();
            break;
        }
        else
        {
            // User pressed cancel
            break;
        }
    }
}

void QLCFixtureEditor::slotExpandModes()
{
    if (m_modeList->topLevelItemCount() <= 0)
        return;
    else if (m_modeList->topLevelItem(0)->isExpanded() == true)
        m_modeList->collapseAll();
    else
        m_modeList->expandAll();
}

void QLCFixtureEditor::slotModeListContextMenuRequested()
{
    QAction editAction(QIcon(":/edit.png"), tr("Edit"), this);
    connect(&editAction, SIGNAL(triggered(bool)),
            this, SLOT(slotEditMode()));
    QAction cloneAction(QIcon(":/editcopy.png"), tr("Clone"), this);
    connect(&cloneAction, SIGNAL(triggered(bool)),
            this, SLOT(slotCloneMode()));
    QAction removeAction(QIcon(":/editdelete.png"), tr("Remove"), this);
    connect(&removeAction, SIGNAL(triggered(bool)),
            this, SLOT(slotRemoveMode()));

    QMenu menu;
    menu.setTitle(tr("Modes"));
    menu.addAction(&editAction);
    menu.addAction(&cloneAction);
    menu.addSeparator();
    menu.addAction(&removeAction);

    if (m_modeList->currentItem() == NULL)
    {
        editAction.setEnabled(false);
        cloneAction.setEnabled(false);
        removeAction.setEnabled(false);
    }

    menu.exec(QCursor::pos());
}

void QLCFixtureEditor::slotModeItemExpanded()
{
    m_modeList->resizeColumnToContents(MODE_COL_NAME);
}

void QLCFixtureEditor::refreshModeList()
{
    m_modeList->clear();

    /* Fill the list of modes */
    QListIterator <QLCFixtureMode*> it(m_fixtureDef->modes());
    while (it.hasNext() == true)
        updateModeItem(it.next(), new QTreeWidgetItem(m_modeList));

    slotModeListSelectionChanged(m_modeList->currentItem());

    m_modeList->resizeColumnToContents(MODE_COL_NAME);
    m_modeList->resizeColumnToContents(MODE_COL_HEAD);
    m_modeList->resizeColumnToContents(MODE_COL_CHS);
}

void QLCFixtureEditor::updateModeItem(const QLCFixtureMode* mode,
                                      QTreeWidgetItem* item)
{
    Q_ASSERT(mode != NULL);
    Q_ASSERT(item != NULL);

    item->setText(MODE_COL_NAME, mode->name());
    item->setData(MODE_COL_NAME, PROP_PTR, (qulonglong) mode);
    item->setText(MODE_COL_CHS, QString::number(mode->channels().size()));
    if (mode->heads().size() > 0)
        item->setText(MODE_COL_HEAD, QString::number(mode->heads().size()));
    else
        item->setText(MODE_COL_HEAD, QString());

    /* Destroy the existing list of children */
    QList <QTreeWidgetItem*> children(item->takeChildren());
    foreach (QTreeWidgetItem* child, children)
    delete child;

    /* Put all mode channels as non-selectable sub items */
    for (int i = 0; i < mode->channels().size(); i++)
    {
        QLCChannel* ch = mode->channel(i);
        Q_ASSERT(ch != NULL);

        QTreeWidgetItem* chitem = new QTreeWidgetItem(item);
        chitem->setText(MODE_COL_NAME, ch->name());
        chitem->setIcon(MODE_COL_NAME, ch->getIconFromGroup(ch->group()));
        chitem->setText(MODE_COL_CHS, QString("%1").arg(i + 1));
        chitem->setFlags(0); /* No selection etc. */
    }
}

QLCFixtureMode* QLCFixtureEditor::currentMode()
{
    QLCFixtureMode* mode = NULL;
    QTreeWidgetItem* item = NULL;

    // Convert the string-form ulong to a QLCChannel pointer and return it
    item = m_modeList->currentItem();
    if (item != NULL)
        mode = (QLCFixtureMode*) item->data(MODE_COL_NAME, PROP_PTR).toULongLong();

    return mode;
}

/*****************************************************************************
 * Clipboard
 *****************************************************************************/

void QLCFixtureEditor::slotClipboardChanged()
{
    if (_app->copyChannel() != NULL)
        m_pasteChannelButton->setEnabled(true);
    else
        m_pasteChannelButton->setEnabled(false);
}


text:
var ENTER_KEY = 13;

var InputWidget = React.createClass({

  getInitialState: function () {
    return {
      comments: []
    }
  },

  handleMsgKeyDown: function (event) {
    if (event.which === ENTER_KEY) {

      event.preventDefault();

      var val = this.refs.inputMsg.getDOMNode().value.trim();

      if (val) {
        console.log("Add New Comment:",val);

        this.setState({
          comments: this.state.comments.concat([val])
        });

        this.refs.inputMsg.getDOMNode().value = '';
      }
    }
  },

  render: function () {
    var comments = this.state.comments.map(comment =>

{comment}

    );

    return (

        <input
          ref="inputMsg"
          onKeyDown={this.handleMsgKeyDown}
          autoFocus={true}
        />
        {comments}

    )
  }
});

var App = React.createClass({
  render: function () {
    return (

Comments

        <InputWidget />

    )
  }
});

React.render(<App />, document.getElementById('app'));

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

# In order to reduce confusion and thereby grease the wheels of commerce
# As a new customer
# Homer Simpson submits invalid or incomplete information and receives instant feedback

describe "A new customer", type: :feature, js: true do
  before(:all) { configure_store }

  before do
    sign_up!
  end

  let(:beef_slab) { create(:product) }
  let!(:shipping_method) { create(:shipping_method) }

  context "when submitting invalid address details" do
    it "displays inline form-validation errors" do
      visit spree.product_path(beef_slab)

      # product.add_to_cart
      click_button 'Add To Cart'

      # cart.checkout
      click_button 'Checkout'

      # address.supply
      within '[data-hook=opco-shipping-address]' do
        within '[data-hook=opco-new-address]' do
          click_on 'Add Address'

          fill_in 'First Name', with: 'Guy'
          fill_in 'Last Name', with: 'Incognito'
          fill_in 'Address', with: '1234 Fake St.'
          fill_in 'City', with: 'New York City'
          select 'New York', from: 'State'
          fill_in 'Zip', with: '10001'
          fill_in 'Telephone', with: '555-555-1234'

          # Use the default country
          # select 'United States', from: 'Country'

          # Submit empty last name and zip-code
          fill_in 'Last Name', with: ''
          fill_in 'Zip', with: ''

          click_button 'Save'
        end
      end

      within '[data-hook=opco-shipping-address]' do
        expect(page).to have_content "can't be blank", count: 2
      end
    end
  end

  context "when submitting invalid credit-card information" do
    it "displays inline form-validation errors" do
      visit spree.product_path(beef_slab)

      # product.add_to_cart
      click_button 'Add To Cart'

      # cart.checkout
      click_button 'Checkout'

      # credit_card.create
      within '[data-hook=opco-payment-method]' do
        within '[data-hook=opco-new-credit-card]' do
          click_on 'Add Credit Card'

          fill_in 'Card Number', with: '4111111111111111'
          select '1', from: 'Expiration Month'
          select '2015', from: 'Expiration Year'
          fill_in 'Verification Value', with: '123'

          # Submit empty credit-card number and CVV
          fill_in 'Card Number', with: ''
          fill_in 'Verification Value', with: ''

          click_button 'Save'
        end
      end

      within '[data-hook=opco-payment-method]' do
        expect(page).to have_content "can't be blank", count: 2
      end
    end
  end
end


text:
#include <linux/err.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/sysfs.h>
#include <linux/workqueue.h>
#include "abx500.h"

#define DEFAULT_MONITOR_DELAY	HZ
#define DEFAULT_MAX_TEMP	130

static inline void schedule_monitor(struct abx500_temp *data)
{
	data->work_active = true;
	schedule_delayed_work(&data->work, DEFAULT_MONITOR_DELAY);
}

static void threshold_updated(struct abx500_temp *data)
{
	int i;
	for (i = 0; i < data->monitored_sensors; i++)
		if (data->max[i] != 0 || data->min[i] != 0) {
			schedule_monitor(data);
			return;
		}

	dev_dbg(&data->pdev->dev, "No active thresholds.\n");
	cancel_delayed_work_sync(&data->work);
	data->work_active = false;
}

static void gpadc_monitor(struct work_struct *work)
{
	int temp, i, ret;
	char alarm_node[30];
	bool updated_min_alarm, updated_max_alarm;
	struct abx500_temp *data;

	data = container_of(work, struct abx500_temp, work.work);
	mutex_lock(&data->lock);

	for (i = 0; i < data->monitored_sensors; i++) {
		/* Thresholds are considered inactive if set to 0 */
		if (data->max[i] == 0 && data->min[i] == 0)
			continue;

		if (data->max[i] < data->min[i])
			continue;

		ret = data->ops.read_sensor(data, data->gpadc_addr[i], &temp);
		if (ret < 0) {
			dev_err(&data->pdev->dev, "GPADC read failed\n");
			continue;
		}

		updated_min_alarm = false;
		updated_max_alarm = false;

		if (data->min[i] != 0) {
			if (temp < data->min[i]) {
				if (data->min_alarm[i] == false) {
					data->min_alarm[i] = true;
					updated_min_alarm = true;
				}
			} else {
				if (data->min_alarm[i] == true) {
					data->min_alarm[i] = false;
					updated_min_alarm = true;
				}
			}
		}
		if (data->max[i] != 0) {
			if (temp > data->max[i]) {
				if (data->max_alarm[i] == false) {
					data->max_alarm[i] = true;
					updated_max_alarm = true;
				}
			} else if (temp < data->max[i] - data->max_hyst[i]) {
				if (data->max_alarm[i] == true) {
					data->max_alarm[i] = false;
					updated_max_alarm = true;
				}
			}
		}

		if (updated_min_alarm) {
			ret = sprintf(alarm_node, "temp%d_min_alarm", i + 1);
			sysfs_notify(&data->pdev->dev.kobj, NULL, alarm_node);
		}
		if (updated_max_alarm) {
			ret = sprintf(alarm_node, "temp%d_max_alarm", i + 1);
			sysfs_notify(&data->pdev->dev.kobj, NULL, alarm_node);
		}
	}

	schedule_monitor(data);
	mutex_unlock(&data->lock);
}

/* HWMON sysfs interfaces */
static ssize_t show_name(struct device *dev, struct device_attribute *devattr,
			 char *buf)
{
	struct abx500_temp *data = dev_get_drvdata(dev);
	/* Show chip name */
	return data->ops.show_name(dev, devattr, buf);
}

static ssize_t show_label(struct device *dev,
			  struct device_attribute *devattr, char *buf)
{
	struct abx500_temp *data = dev_get_drvdata(dev);
	/* Show each sensor label */
	return data->ops.show_label(dev, devattr, buf);
}

static ssize_t show_input(struct device *dev,
			  struct device_attribute *devattr, char *buf)
{
	int ret, temp;
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	u8 gpadc_addr = data->gpadc_addr[attr->index];

	ret = data->ops.read_sensor(data, gpadc_addr, &temp);
	if (ret < 0)
		return ret;

	return sprintf(buf, "%d\n", temp);
}

/* Set functions (RW nodes) */
static ssize_t set_min(struct device *dev, struct device_attribute *devattr,
		       const char *buf, size_t count)
{
	unsigned long val;
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	int res = kstrtol(buf, 10, &val);
	if (res < 0)
		return res;

	val = clamp_val(val, 0, DEFAULT_MAX_TEMP);

	mutex_lock(&data->lock);
	data->min[attr->index] = val;
	threshold_updated(data);
	mutex_unlock(&data->lock);

	return count;
}

static ssize_t set_max(struct device *dev, struct device_attribute *devattr,
		       const char *buf, size_t count)
{
	unsigned long val;
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	int res = kstrtol(buf, 10, &val);
	if (res < 0)
		return res;

	val = clamp_val(val, 0, DEFAULT_MAX_TEMP);

	mutex_lock(&data->lock);
	data->max[attr->index] = val;
	threshold_updated(data);
	mutex_unlock(&data->lock);

	return count;
}

static ssize_t set_max_hyst(struct device *dev,
			    struct device_attribute *devattr,
			    const char *buf, size_t count)
{
	unsigned long val;
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);
	int res = kstrtoul(buf, 10, &val);
	if (res < 0)
		return res;

	val = clamp_val(val, 0, DEFAULT_MAX_TEMP);

	mutex_lock(&data->lock);
	data->max_hyst[attr->index] = val;
	threshold_updated(data);
	mutex_unlock(&data->lock);

	return count;
}

/* Show functions (RO nodes) */
static ssize_t show_min(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);

	return sprintf(buf, "%ld\n", data->min[attr->index]);
}

static ssize_t show_max(struct device *dev,
			struct device_attribute *devattr, char *buf)
{
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);

	return sprintf(buf, "%ld\n", data->max[attr->index]);
}

static ssize_t show_max_hyst(struct device *dev,
			     struct device_attribute *devattr, char *buf)
{
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);

	return sprintf(buf, "%ld\n", data->max_hyst[attr->index]);
}

static ssize_t show_min_alarm(struct device *dev,
			      struct device_attribute *devattr, char *buf)
{
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);

	return sprintf(buf, "%d\n", data->min_alarm[attr->index]);
}

static ssize_t show_max_alarm(struct device *dev,
			      struct device_attribute *devattr, char *buf)
{
	struct abx500_temp *data = dev_get_drvdata(dev);
	struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr);

	return sprintf(buf, "%d\n", data->max_alarm[attr->index]);
}

static umode_t abx500_attrs_visible(struct kobject *kobj,
				   struct attribute *attr, int n)
{
	struct device *dev = container_of(kobj, struct device, kobj);
	struct abx500_temp *data = dev_get_drvdata(dev);

	if (data->ops.is_visible)
		return data->ops.is_visible(attr, n);

	return attr->mode;
}

/* Chip name, required by hwmon */
static SENSOR_DEVICE_ATTR(name, S_IRUGO, show_name, NULL, 0);

/* GPADC - SENSOR1 */
static SENSOR_DEVICE_ATTR(temp1_label, S_IRUGO, show_label, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_input, S_IRUGO, show_input, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_min, S_IWUSR | S_IRUGO, show_min, set_min, 0);
static SENSOR_DEVICE_ATTR(temp1_max, S_IWUSR | S_IRUGO, show_max, set_max, 0);
static SENSOR_DEVICE_ATTR(temp1_max_hyst, S_IWUSR | S_IRUGO,
			  show_max_hyst, set_max_hyst, 0);
static SENSOR_DEVICE_ATTR(temp1_min_alarm, S_IRUGO, show_min_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(temp1_max_alarm, S_IRUGO, show_max_alarm, NULL, 0);

/* GPADC - SENSOR2 */
static SENSOR_DEVICE_ATTR(temp2_label, S_IRUGO, show_label, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_input, S_IRUGO, show_input, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_min, S_IWUSR | S_IRUGO, show_min, set_min, 1);
static SENSOR_DEVICE_ATTR(temp2_max, S_IWUSR | S_IRUGO, show_max, set_max, 1);
static SENSOR_DEVICE_ATTR(temp2_max_hyst, S_IWUSR | S_IRUGO,
			  show_max_hyst, set_max_hyst, 1);
static SENSOR_DEVICE_ATTR(temp2_min_alarm, S_IRUGO, show_min_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(temp2_max_alarm, S_IRUGO, show_max_alarm, NULL, 1);

/* GPADC - SENSOR3 */
static SENSOR_DEVICE_ATTR(temp3_label, S_IRUGO, show_label, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_input, S_IRUGO, show_input, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_min, S_IWUSR | S_IRUGO, show_min, set_min, 2);
static SENSOR_DEVICE_ATTR(temp3_max, S_IWUSR | S_IRUGO, show_max, set_max, 2);
static SENSOR_DEVICE_ATTR(temp3_max_hyst, S_IWUSR | S_IRUGO,
			  show_max_hyst, set_max_hyst, 2);
static SENSOR_DEVICE_ATTR(temp3_min_alarm, S_IRUGO, show_min_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(temp3_max_alarm, S_IRUGO, show_max_alarm, NULL, 2);

/* GPADC - SENSOR4 */
static SENSOR_DEVICE_ATTR(temp4_label, S_IRUGO, show_label, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_input, S_IRUGO, show_input, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_min, S_IWUSR | S_IRUGO, show_min, set_min, 3);
static SENSOR_DEVICE_ATTR(temp4_max, S_IWUSR | S_IRUGO, show_max, set_max, 3);
static SENSOR_DEVICE_ATTR(temp4_max_hyst, S_IWUSR | S_IRUGO,
			  show_max_hyst, set_max_hyst, 3);
static SENSOR_DEVICE_ATTR(temp4_min_alarm, S_IRUGO, show_min_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(temp4_max_alarm, S_IRUGO, show_max_alarm, NULL, 3);

struct attribute *abx500_temp_attributes[] = {
	&sensor_dev_attr_name.dev_attr.attr,

	&sensor_dev_attr_temp1_label.dev_attr.attr,
	&sensor_dev_attr_temp1_input.dev_attr.attr,
	&sensor_dev_attr_temp1_min.dev_attr.attr,
	&sensor_dev_attr_temp1_max.dev_attr.attr,
	&sensor_dev_attr_temp1_max_hyst.dev_attr.attr,
	&sensor_dev_attr_temp1_min_alarm.dev_attr.attr,
	&sensor_dev_attr_temp1_max_alarm.dev_attr.attr,

	&sensor_dev_attr_temp2_label.dev_attr.attr,
	&sensor_dev_attr_temp2_input.dev_attr.attr,
	&sensor_dev_attr_temp2_min.dev_attr.attr,
	&sensor_dev_attr_temp2_max.dev_attr.attr,
	&sensor_dev_attr_temp2_max_hyst.dev_attr.attr,
	&sensor_dev_attr_temp2_min_alarm.dev_attr.attr,
	&sensor_dev_attr_temp2_max_alarm.dev_attr.attr,

	&sensor_dev_attr_temp3_label.dev_attr.attr,
	&sensor_dev_attr_temp3_input.dev_attr.attr,
	&sensor_dev_attr_temp3_min.dev_attr.attr,
	&sensor_dev_attr_temp3_max.dev_attr.attr,
	&sensor_dev_attr_temp3_max_hyst.dev_attr.attr,
	&sensor_dev_attr_temp3_min_alarm.dev_attr.attr,
	&sensor_dev_attr_temp3_max_alarm.dev_attr.attr,

	&sensor_dev_attr_temp4_label.dev_attr.attr,
	&sensor_dev_attr_temp4_input.dev_attr.attr,
	&sensor_dev_attr_temp4_min.dev_attr.attr,
	&sensor_dev_attr_temp4_max.dev_attr.attr,
	&sensor_dev_attr_temp4_max_hyst.dev_attr.attr,
	&sensor_dev_attr_temp4_min_alarm.dev_attr.attr,
	&sensor_dev_attr_temp4_max_alarm.dev_attr.attr,
	NULL
};

static const struct attribute_group abx500_temp_group = {
	.attrs = abx500_temp_attributes,
	.is_visible = abx500_attrs_visible,
};

static irqreturn_t abx500_temp_irq_handler(int irq, void *irq_data)
{
	struct platform_device *pdev = irq_data;
	struct abx500_temp *data = platform_get_drvdata(pdev);

	data->ops.irq_handler(irq, data);
	return IRQ_HANDLED;
}

static int setup_irqs(struct platform_device *pdev)
{
	int ret;
	int irq = platform_get_irq_byname(pdev, "ABX500_TEMP_WARM");

	if (irq < 0) {
		dev_err(&pdev->dev, "Get irq by name failed\n");
		return irq;
	}

	ret = devm_request_threaded_irq(&pdev->dev, irq, NULL,
		abx500_temp_irq_handler, IRQF_NO_SUSPEND, "abx500-temp", pdev);
	if (ret < 0)
		dev_err(&pdev->dev, "Request threaded irq failed (%d)\n", ret);

	return ret;
}

static int abx500_temp_probe(struct platform_device *pdev)
{
	struct abx500_temp *data;
	int err;

	data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
	if (!data)
		return -ENOMEM;

	data->pdev = pdev;
	mutex_init(&data->lock);

	/* Chip specific initialization */
	err = abx500_hwmon_init(data);
	if (err	< 0 || !data->ops.read_sensor || !data->ops.show_name ||
			!data->ops.show_label)
		return err;

	INIT_DEFERRABLE_WORK(&data->work, gpadc_monitor);

	platform_set_drvdata(pdev, data);

	err = sysfs_create_group(&pdev->dev.kobj, &abx500_temp_group);
	if (err < 0) {
		dev_err(&pdev->dev, "Create sysfs group failed (%d)\n", err);
		return err;
	}

	data->hwmon_dev = hwmon_device_register(&pdev->dev);
	if (IS_ERR(data->hwmon_dev)) {
		err = PTR_ERR(data->hwmon_dev);
		dev_err(&pdev->dev, "Class registration failed (%d)\n", err);
		goto exit_sysfs_group;
	}

	if (data->ops.irq_handler) {
		err = setup_irqs(pdev);
		if (err < 0)
			goto exit_hwmon_reg;
	}
	return 0;

exit_hwmon_reg:
	hwmon_device_unregister(data->hwmon_dev);
exit_sysfs_group:
	sysfs_remove_group(&pdev->dev.kobj, &abx500_temp_group);
	return err;
}

static int abx500_temp_remove(struct platform_device *pdev)
{
	struct abx500_temp *data = platform_get_drvdata(pdev);

	cancel_delayed_work_sync(&data->work);
	hwmon_device_unregister(data->hwmon_dev);
	sysfs_remove_group(&pdev->dev.kobj, &abx500_temp_group);

	return 0;
}

static int abx500_temp_suspend(struct platform_device *pdev,
			       pm_message_t state)
{
	struct abx500_temp *data = platform_get_drvdata(pdev);

	if (data->work_active)
		cancel_delayed_work_sync(&data->work);

	return 0;
}

static int abx500_temp_resume(struct platform_device *pdev)
{
	struct abx500_temp *data = platform_get_drvdata(pdev);

	if (data->work_active)
		schedule_monitor(data);

	return 0;
}

#ifdef CONFIG_OF
static const struct of_device_id abx500_temp_match[] = {
	{ .compatible = "stericsson,abx500-temp" },
	{},
};
#endif

static struct platform_driver abx500_temp_driver = {
	.driver = {
		.owner = THIS_MODULE,
		.name = "abx500-temp",
		.of_match_table = of_match_ptr(abx500_temp_match),
	},
	.suspend = abx500_temp_suspend,
	.resume = abx500_temp_resume,
	.probe = abx500_temp_probe,
	.remove = abx500_temp_remove,
};

module_platform_driver(abx500_temp_driver);

MODULE_AUTHOR("Martin Persson <martin.persson@stericsson.com>");
MODULE_DESCRIPTION("ABX500 temperature driver");
MODULE_LICENSE("GPL");


text:
'use strict';

var pg = require('pg');
var Promise = require('bluebird');
var pgConnect = Promise.promisify(pg.connect, {context: pg, multiArgs: true});

var IDENTITY = function (x) { return x; };

function connect(connectionParams) {
  var done;
  return pgConnect(connectionParams)
    .spread(function(client, _done) {
      done = _done;

      function queryOne(text, values) {
        return Promise.fromNode(function (callback) {
          return client.query(text, values, callback);
        });
      }

      function queryRaw(text, values, mapFn) {
        mapFn = mapFn || IDENTITY;
        if (Array.isArray(text)) {
          return Promise.map(text, queryOne).map(mapFn);
        } else {
          return queryOne(text, values).then(mapFn);
        }
      }

      function query(text, values) {
        return queryRaw(text, values, function (result) {
          return result.rows;
        });
      }

      query.single = function (text, values) {
        return queryRaw(text, values, function (result) {
          return result.rows && result.rows[0] || null;
        });
      };

      query.raw = queryRaw;

      return query;
    })
    .disposer(function() {
      if (done) {
        done();
      }
    });
}

function queryDefault(text, values) {
  return Promise.using(connect(queryDefault.connectionParams), function (query) {
    return query(text, values);
  });
}

queryDefault.single = function (text, values) {
  return Promise.using(connect(queryDefault.connectionParams), function (query) {
    return query.single(text, values);
  });
};

queryDefault.raw = function (text, values) {
  return Promise.using(connect(queryDefault.connectionParams), function (query) {
    return query.raw(text, values);
  });
};

queryDefault.connect = connect;

module.exports = queryDefault;


text:
package org.elasticsearch.index.cache.query;

import org.apache.lucene.search.QueryCachingPolicy;
import org.apache.lucene.search.Weight;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.indices.IndicesQueryCache;

/**
 * The index-level query cache. This class mostly delegates to the node-level
 * query cache: {@link IndicesQueryCache}.
 */
public class IndexQueryCache extends AbstractIndexComponent implements QueryCache {

    final IndicesQueryCache indicesQueryCache;

    public IndexQueryCache(IndexSettings indexSettings, IndicesQueryCache indicesQueryCache) {
        super(indexSettings);
        this.indicesQueryCache = indicesQueryCache;
    }

    @Override
    public void close() throws ElasticsearchException {
        clear("close");
    }

    @Override
    public void clear(String reason) {
        logger.debug("full cache clear, reason [{}]", reason);
        indicesQueryCache.clearIndex(index().getName());
    }

    @Override
    public Weight doCache(Weight weight, QueryCachingPolicy policy) {
        return indicesQueryCache.doCache(weight, policy);
    }

}


text:
react-maps
==========

To get the demo running:

1. Checkout the project
2. `cd` to the project directory
3. `npm install`
4. `node server`
5. Demo site will be running on `http://localhost:3000`


text:
class LinkType < ActiveRecord::Base

  # Validations

  validates :name, presence: true
  validates :description, presence: true

  has_one :picture, :as => :imageable, :dependent => :destroy, :class_name => "Image::LinkTypePicture"

  # Associations
  has_many :project_links

  # return an active record relation object with the search query in its where clause
  # Return the ActiveRecord::Relation object
  # == Examples
  #   >>> link_type.search(query)
  #   => ActiveRecord::Relation object
  scope :search, lambda {|query| where("LOWER(name) LIKE LOWER('%#{query}%') OR\
                                        LOWER(description) LIKE LOWER('%#{query}%') OR\
                                        LOWER(theme) LIKE LOWER('%#{query}%') OR\
                                        LOWER(button_text) LIKE LOWER('%#{query}%')")
                        }

end


text:
<?php defined('SYSPATH') or die('No direct script access.');

// Categories Model

class Model_Publishers extends Model_Common {

	protected $tableName = "publishers";
	protected $fieldNames = array("publisher_id", "publisher_name");

}


text:
* [stackoverflow](https://stackoverflow.com/questions/43100127/golang-error-while-make-test-signal-killed)
* [golang issues](https://github.com/golang/go/issues/19734)


text:
package com.intellij.java.psi.search;

import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.util.StandardProgressIndicatorBase;
import com.intellij.openapi.roots.DependencyScope;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassOwner;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.impl.compiled.ClsClassImpl;
import com.intellij.psi.impl.source.PsiClassImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ClassInheritorsSearch;
import com.intellij.psi.search.searches.DirectClassInheritorsSearch;
import com.intellij.testFramework.PsiTestUtil;
import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
import com.intellij.util.CommonProcessors;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class ClassInheritorsTest extends JavaCodeInsightFixtureTestCase {

  public void testClsAndSourcesDoNotMixUp() {
    PsiClass numberClass = myFixture.getJavaFacade().findClass("java.lang.Number", GlobalSearchScope.allScope(getProject()));
    assertTrue(String.valueOf(numberClass), numberClass instanceof ClsClassImpl);
    PsiClass n2 = (PsiClass)numberClass.getNavigationElement();
    assertTrue(String.valueOf(n2), n2 instanceof PsiClassImpl);
    Collection<PsiClass> subClasses = DirectClassInheritorsSearch.search(n2, GlobalSearchScope.allScope(getProject())).findAll();
    List<String> fqn = subClasses.stream().map(PsiClass::getQualifiedName).sorted().toList();
    assertEquals(fqn.toString(), fqn.size(), new HashSet<>(fqn).size()); // no dups mean no Cls/Psi mixed

    Collection<PsiClass> allSubClasses = ClassInheritorsSearch.search(n2, GlobalSearchScope.allScope(getProject()), true).findAll();
    List<String> allFqn = allSubClasses.stream().map(PsiClass::getQualifiedName).sorted().toList();
    assertEquals(allFqn.toString(), allFqn.size(), new HashSet<>(allFqn).size());
  }

  public void testStressInPresenceOfPCEs() {
    ApplicationManager.getApplication().assertIsDispatchThread(); // no write action can go through while we test
    int N = 1000;
    PsiClassOwner file0 = (PsiJavaFile)myFixture.addFileToProject("C0.java", "class C0 { }");
    for (int i=1;i<N ;i++) {
      int extI = i - 1 - (i - 1) % 10; // 10 inheritors
      myFixture.addClass("class C" + i + " extends C" + extI + " { }");
    }
    PsiClass class0 = file0.getClasses()[0];

    int delayToCancel = 100;
    for (int i=0;i<1000;i++) {
      //System.out.println("i = " + i+ "; delayToCancel="+delayToCancel);
      StandardProgressIndicatorBase progress = new StandardProgressIndicatorBase();
      JobScheduler.getScheduler().schedule(progress::cancel, delayToCancel, TimeUnit.MILLISECONDS);
      try {
        Collections.nCopies(Runtime.getRuntime().availableProcessors(), "").stream().parallel().forEach(__ -> {
          Collection<PsiClass> inheritors = Collections.synchronizedSet(new HashSet<>());
          ProgressManager.getInstance().executeProcessUnderProgress(()-> {
            boolean success = ClassInheritorsSearch.search(class0).forEach(new CommonProcessors.CollectProcessor<>(inheritors));
            if (N - 1 != inheritors.size() || !success) {
              assertEquals(N - 1, inheritors.size());
            }
          }, progress);
        });
        myFixture.getPsiManager().dropResolveCaches();
        //System.out.println("Iterated all");
        delayToCancel--;
      }
      catch (ProcessCanceledException e) {
        //System.out.println("e = " + e);
        delayToCancel++;
      }
    }
  }

  public void testPrivateClassCanHaveInheritorsInAnotherFile() {
    myFixture.addClass("""
                         public class Test {
                           public static class A { }
                           private static class B extends A { }
                           public static class C1 extends B { }
                           public static class C2 extends B { }
                         }""");
    myFixture.addClass("""
                         public class Test2 {
                           private static class D1 extends Test.C1 { }
                           private static class D2 extends Test.C2 { }
                         }""");
    assertSize(5, ClassInheritorsSearch.search(myFixture.findClass("Test.A")).findAll());
    assertSize(4, ClassInheritorsSearch.search(myFixture.findClass("Test.B")).findAll());
  }

  public void testPackageLocalClassCanHaveInheritorsInAnotherPackage() {
    myFixture.addClass("""
                         package one; public class Test {
                           public static class A { }
                           static class B extends A { }
                           public static class C1 extends B { }
                           public static class C2 extends B { }
                         }""");
    myFixture.addClass("""
                         package another; public class Test2 {
                           private static class D1 extends one.Test.C1 { }
                           private static class D2 extends one.Test.C2 { }
                         }""");
    assertSize(5, ClassInheritorsSearch.search(myFixture.findClass("one.Test.A")).findAll());
    assertSize(4, ClassInheritorsSearch.search(myFixture.findClass("one.Test.B")).findAll());
  }

  public void testInheritorsInAnotherModuleWithNoDirectDependency() throws IOException {
    myFixture.addFileToProject("A.java", "class A {}");
    myFixture.addFileToProject("mod1/B.java", "class B extends A {}");
    myFixture.addFileToProject("mod1/C.java", "class C extends B {}");

    Module mod1 = PsiTestUtil.addModule(getProject(), StdModuleTypes.JAVA, "mod1", myFixture.getTempDirFixture().findOrCreateDir("mod1"));
    Module mod2 = PsiTestUtil.addModule(getProject(), StdModuleTypes.JAVA, "mod2", myFixture.getTempDirFixture().findOrCreateDir("mod1"));

    ModuleRootModificationUtil.addDependency(mod1, getModule(), DependencyScope.COMPILE, false);
    ModuleRootModificationUtil.addDependency(mod2, mod1, DependencyScope.COMPILE, false);

    assertSize(2, ClassInheritorsSearch.search(myFixture.findClass("A")).findAll());
  }

  public void testInheritorsInAnotherModuleWithProductionOnTestDependency() throws IOException {
    myFixture.addFileToProject("tests/B.java", "class B {}");
    myFixture.addFileToProject("mod2/C.java", "class C extends B {}");

    PsiTestUtil.addSourceRoot(getModule(), myFixture.getTempDirFixture().findOrCreateDir("tests"), true);
    Module mod2 = PsiTestUtil.addModule(getProject(), StdModuleTypes.JAVA, "mod2", myFixture.getTempDirFixture().findOrCreateDir("mod2"));

    ModuleRootModificationUtil.updateModel(mod2, model ->
      model.addModuleOrderEntry(getModule()).setProductionOnTestDependency(true));

    assertSize(1, ClassInheritorsSearch.search(myFixture.findClass("B")).findAll());
  }

  public void testSpaceBeforeSuperTypeGenerics() {
    myFixture.addFileToProject("A.java", "interface A<T> {}");
    myFixture.addFileToProject("B.java", "class B implements A <T> {}");
    assertSize(1, ClassInheritorsSearch.search(myFixture.findClass("A")).findAll());
  }

  public void testQueryingNonAnonymousInheritors() {
    PsiClass foo = myFixture.addClass("class Foo { { new Foo(){}; }; class Bar extends Foo {} }");
    GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
    assertSize(1, ClassInheritorsSearch.search(foo, scope, true, true, false).findAll());
    assertSize(2, ClassInheritorsSearch.search(foo, scope, true, true, true).findAll());
  }
}


text:
"""dbmodels.py: Import each app's models submodule."""

import os

import config
import db
import helpers

dir_names = helpers.get_modules(config.DIR_APPS)
base_name = os.path.basename(config.DIR_APPS)

for dir_name in dir_names:
    module_format = '{}.{}'.format(base_name, dir_name)
    module = helpers.custom_import(module_format)
    module_path = module.__path__[0]

    if 'models.py' in os.listdir(module_path):
        submodule_format = '{}.{}.models'.format(base_name, dir_name)

        helpers.custom_import(submodule_format)

db.Base.metadata.create_all(db.engine)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
    [UseExportProvider]
    public class DiagnosticDataTests
    {
        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText()
        {
            var code = "";
            await VerifyTextSpanAsync(code, 10, 10, 20, 20, new TextSpan(0, 0));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText1()
        {
            var code = @"
";

            await VerifyTextSpanAsync(code, 30, 30, 40, 40, new TextSpan(code.Length, 0));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText2()
        {
            var code = @"
";

            await VerifyTextSpanAsync(code, -1, 30, 40, 40, new TextSpan(0, code.Length));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText3()
        {
            var code = @"
";

            await VerifyTextSpanAsync(code, -1, 30, -1, 40, new TextSpan(0, 0));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText4()
        {
            var code = @"
";

            await VerifyTextSpanAsync(code, 1, 30, -1, 40, new TextSpan(code.Length, 0));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText5()
        {
            var code = @"
";

            await VerifyTextSpanAsync(code, 1, 30, 1, 40, new TextSpan(code.Length, 0));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText6()
        {
            var code = @"
";

            await VerifyTextSpanAsync(code, 1, 30, 2, 40, new TextSpan(code.Length, 0));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText7()
        {
            var code = @"
";

            await VerifyTextSpanAsync(code, 1, 0, 1, 2, new TextSpan(code.Length, 0));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_GetText8()
        {
            var code = @"
namespace B
{
    class A
    {
    }
}
";

            await VerifyTextSpanAsync(code, 3, 10, 3, 11, new TextSpan(28, 1));
        }

        private static async Task VerifyTextSpanAsync(string code, int startLine, int startColumn, int endLine, int endColumn, TextSpan span)
        {
            using var workspace = new TestWorkspace(composition: EditorTestCompositions.EditorFeatures);
            var document = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp).AddDocument("TestDocument", code);

            var data = new DiagnosticData(
                id: "test1",
                category: "Test",
                message: "test1 message",
                severity: DiagnosticSeverity.Info,
                defaultSeverity: DiagnosticSeverity.Info,
                isEnabledByDefault: false,
                warningLevel: 1,
                projectId: document.Project.Id,
                customTags: ImmutableArray<string>.Empty,
                properties: ImmutableDictionary<string, string>.Empty,
                location: new DiagnosticDataLocation(document.Id, null, "originalFile1", startLine, startColumn, endLine, endColumn),
                language: document.Project.Language);

            var text = await document.GetTextAsync();
            var actual = DiagnosticData.GetExistingOrCalculatedTextSpan(data.DataLocation, text);

            Assert.Equal(span, actual);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        [WorkItem(46377, "https://github.com/dotnet/roslyn/issues/46377")]
        public async Task DiagnosticData_ExternalAdditionalLocationIsPreserved()
        {
            using var workspace = new TestWorkspace(composition: EditorTestCompositions.EditorFeatures);

            var additionalDocument = workspace.CurrentSolution.AddProject("TestProject", "TestProject", LanguageNames.CSharp)
                .AddDocument("test.cs", "")
                .Project.AddAdditionalDocument("AdditionalDocument.txt", "First line in file", filePath: "AdditionalDocument.txt");
            var document = additionalDocument.Project.Documents.Single();

            var externalAdditionalLocation = new DiagnosticDataLocation(
                additionalDocument.Id, sourceSpan: new TextSpan(0, 1), originalFilePath: additionalDocument.Name,
                originalStartLine: 0, originalStartColumn: 0, originalEndLine: 0, originalEndColumn: 1);

            var diagnosticData = new DiagnosticData(
                id: "test1",
                category: "Test",
                message: "test1 message",
                severity: DiagnosticSeverity.Info,
                defaultSeverity: DiagnosticSeverity.Info,
                isEnabledByDefault: true,
                warningLevel: 1,
                projectId: document.Project.Id,
                customTags: ImmutableArray<string>.Empty,
                properties: ImmutableDictionary<string, string>.Empty,
                location: new DiagnosticDataLocation(document.Id),
                additionalLocations: ImmutableArray.Create(externalAdditionalLocation),
                language: document.Project.Language);

            var diagnostic = await diagnosticData.ToDiagnosticAsync(document.Project, CancellationToken.None);
            var roundTripDiagnosticData = DiagnosticData.Create(diagnostic, document);

            var roundTripAdditionalLocation = Assert.Single(roundTripDiagnosticData.AdditionalLocations);
            Assert.Equal(externalAdditionalLocation.DocumentId, roundTripAdditionalLocation.DocumentId);
            Assert.Equal(externalAdditionalLocation.SourceSpan, roundTripAdditionalLocation.SourceSpan);
            Assert.Equal(externalAdditionalLocation.OriginalFilePath, roundTripAdditionalLocation.OriginalFilePath);
            Assert.Equal(externalAdditionalLocation.OriginalStartLine, roundTripAdditionalLocation.OriginalStartLine);
            Assert.Equal(externalAdditionalLocation.OriginalStartColumn, roundTripAdditionalLocation.OriginalStartColumn);
            Assert.Equal(externalAdditionalLocation.OriginalEndLine, roundTripAdditionalLocation.OriginalEndLine);
            Assert.Equal(externalAdditionalLocation.OriginalEndLine, roundTripAdditionalLocation.OriginalEndLine);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.Diagnostics)]
        public async Task DiagnosticData_SourceGeneratedDocumentLocationIsPreserved()
        {
            var content = @"
namespace B
{
    class A
    {
    }
}
";
            using var workspace = TestWorkspace.CreateCSharp(files: Array.Empty<string>(), sourceGeneratedFiles: new[] { content }, composition: EditorTestCompositions.EditorFeatures);
            var hostDocument = workspace.Documents.Single();
            Assert.True(hostDocument.IsSourceGenerated);

            var documentId = hostDocument.Id;
            var project = workspace.CurrentSolution.GetRequiredProject(documentId.ProjectId);
            var document = await project.GetSourceGeneratedDocumentAsync(documentId, CancellationToken.None);

            await VerifyTextSpanAsync(content, 3, 10, 3, 11, new TextSpan(28, 1));
            var location = new DiagnosticDataLocation(
                documentId, sourceSpan: new TextSpan(28, 1), originalFilePath: document.FilePath,
                originalStartLine: 3, originalStartColumn: 10, originalEndLine: 3, originalEndColumn: 11);

            var diagnosticData = new DiagnosticData(
                id: "test1",
                category: "Test",
                message: "test1 message",
                severity: DiagnosticSeverity.Info,
                defaultSeverity: DiagnosticSeverity.Info,
                isEnabledByDefault: true,
                warningLevel: 1,
                projectId: documentId.ProjectId,
                customTags: ImmutableArray<string>.Empty,
                properties: ImmutableDictionary<string, string>.Empty,
                location: location,
                additionalLocations: ImmutableArray<DiagnosticDataLocation>.Empty,
                language: project.Language);

            var diagnostic = await diagnosticData.ToDiagnosticAsync(project, CancellationToken.None);
            var roundTripDiagnosticData = DiagnosticData.Create(diagnostic, document);

            var roundTripLocation = roundTripDiagnosticData.DataLocation;
            Assert.NotNull(roundTripDiagnosticData.DataLocation);
            Assert.Equal(location.DocumentId, roundTripLocation.DocumentId);
            Assert.Equal(location.SourceSpan, roundTripLocation.SourceSpan);
            Assert.Equal(location.OriginalFilePath, roundTripLocation.OriginalFilePath);
            Assert.Equal(location.OriginalStartLine, roundTripLocation.OriginalStartLine);
            Assert.Equal(location.OriginalStartColumn, roundTripLocation.OriginalStartColumn);
            Assert.Equal(location.OriginalEndLine, roundTripLocation.OriginalEndLine);
            Assert.Equal(location.OriginalEndLine, roundTripLocation.OriginalEndLine);
        }
    }
}


text:
package org.apache.struts.tiles;

/**
 * Component attribute.
 * Such attribute value represent an instance name.
 */
public class DefinitionNameAttribute extends UntypedAttribute {

    /**
     * Constructor.
     */
    public DefinitionNameAttribute(String value) {
        super(value);
    }

    /**
     * Constructor.
     */
    public DefinitionNameAttribute(String value, String role) {
        super(value, role);
    }

}


text:
void raw6_icmp_error(struct sk_buff *, int nexthdr,
		u8 type, u8 code, int inner_offset, __be32);
int raw6_local_deliver(struct sk_buff *, int);

extern int			rawv6_rcv(struct sock *sk,
					  struct sk_buff *skb);

#if defined(CONFIG_IPV6_MIP6) || defined(CONFIG_IPV6_MIP6_MODULE)
int rawv6_mh_filter_register(int (*filter)(struct sock *sock,
					   struct sk_buff *skb));
int rawv6_mh_filter_unregister(int (*filter)(struct sock *sock,
					     struct sk_buff *skb));
#endif

#endif

#endif


text:
layout: page
title: Terry Humphrey's 48th Birthday
date: 2016-05-24
author: Danielle Singh
tags: weekly links, java
status: published
summary: Nullam et posuere ante. Duis rutrum ipsum id velit suscipit.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 12/12/2016
  endDate: 12/15/2016
  ctyhocn: LNKAPHX
  groupCode: TH4B
published: true
---
Proin mi ante, tempus at tempus et, elementum sit amet eros. Donec ut nunc orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec posuere nibh in nisl imperdiet, ultrices egestas ex eleifend. Vestibulum vulputate mauris et ornare eleifend. Nulla facilisi. Pellentesque sit amet velit accumsan, condimentum risus at, malesuada diam. Aenean gravida sodales tristique. Vivamus rhoncus elementum nisi ut porta. Aliquam in blandit urna. Curabitur id ultricies risus. Nullam sit amet malesuada tortor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nam sapien urna, pretium ac tempor eget, mattis sed sapien. Mauris et vulputate lectus. Aliquam non risus libero.

1 Sed quis risus maximus, dignissim libero non, tristique arcu
1 Phasellus pharetra neque sed condimentum condimentum.

Maecenas ultrices libero nisi, a pretium velit dictum eu. Fusce hendrerit risus orci, at sodales metus ullamcorper eget. In et arcu quis odio tincidunt pulvinar sed in augue. Curabitur cursus fermentum ligula, sit amet tristique justo ornare id. Fusce at tincidunt tellus. Fusce et fringilla nulla, et hendrerit tortor. Nunc cursus mattis fermentum. Cras lacinia dictum sapien, vel sodales mi sodales non. Cras luctus, nibh sit amet ultricies aliquam, diam nisi egestas augue, eu posuere velit velit at massa. Aenean nunc mi, vestibulum ac laoreet vel, imperdiet porta risus. Nunc ornare euismod ipsum faucibus sodales. Vestibulum rhoncus, eros quis gravida accumsan, lorem massa fringilla erat, ac eleifend velit orci at ipsum. Nulla mauris tortor, finibus sed risus sed, porttitor elementum nibh.


text:
package org.consumersunion.stories.dashboard.client.application.ui;

public enum BuilderTab {
    QUESTIONS("Questions/Content"),
    CONTENT("Content"),
    ON_SUBMIT("On Submit"),
    PUBLICATION("Publication");

    private final String label;

    BuilderTab(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }

    @Override
    public String toString() {
        return label;
    }
}


text:
namespace Microsoft.Azure.Graph.RBAC
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// DeletedApplicationsOperations operations.
    /// </summary>
    public partial interface IDeletedApplicationsOperations
    {
        /// <summary>
        /// Restores the deleted application in the directory.
        /// </summary>
        /// <param name='objectId'>
        /// Application object ID.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="GraphErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<Application>> RestoreWithHttpMessagesAsync(string objectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a list of deleted applications in the directory.
        /// </summary>
        /// <param name='filter'>
        /// The filter to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="GraphErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<Application>>> ListWithHttpMessagesAsync(string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Hard-delete an application.
        /// </summary>
        /// <param name='applicationObjectId'>
        /// Application object ID.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="GraphErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> HardDeleteWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a list of deleted applications in the directory.
        /// </summary>
        /// <param name='nextLink'>
        /// Next link for the list operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="GraphErrorException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<Application>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
title: Meeting Tonight, Woodworking Class Saturday
author: Andrew Mike
date: 2017-06-20
layout: post
---

Hello everyone!  We're having a general meeting tonight at 7:30 PM at the space. The agenda is [here](https://wiki.hacksburg.org/meetings:2017-06-20_general_meeting).

At 1 PM this Saturday, we'll be having our [intro woodworking class](https://wiki.hacksburg.org/events:woodworking_101_-_2017). For $10 ($5 for members), you'll be trained on the usage and safety on our wide variety of woodworking tools while making one of two small projects to take home! All levels of experience are welcome!

Thanks for reading, and we hope to see you at the space!


text:
{% extends "resources/base.html" %}
{% load isfollow from codesters %}
{% load markup %}

{% block meta_description %}{{ current_topic.description|slice:":200" }}{% endblock %}

{% block extra_head %}
<link rel="alternate" type="application/atom+xml" title="Recent Resources for {{ current_topic.name }}-Rss" href="{% url 'topic_feed_rss' topic_slug=current_topic.slug %}" />
<link rel="alternate" type="application/atom+xml" title="Recent Resources for {{ current_topic.name }}-Atom" href="{% url 'topic_feed_atom' topic_slug=current_topic.slug %}" />
{% endblock %}

{% block resource_heading %}{{ current_topic.name }}{% endblock %}

{% block resource_content %}

            {% include "snippets/share_this.html" %}

                {% if user.is_staff %}  Edit {% endif %}
                 Subscribe to Feeds

Rss

Atom

            {% if user.is_authenticated %}
            {% if current_topic|isfollow:user %} Unfollow{% else %} Follow this Topic{% endif %}
            {% endif %}

{% if current_topic.description %}

About {{ current_topic.name }}

{% if current_topic.thumbnail %}

{% endif %}
{{ current_topic.description|markdown:"safe" }}

NOTE: Above information has been taken from wikipedia and/or official websites of topics.

{% endif %}

Featured Resources

        {% for k,v in resourcetypes.items %}

                {{ v.resource_type }}

{{ v.title }}

{{ v.help_text|slice:":100" }} ...Details

                More {{ v.resource_type }}s

        {% empty %}

Sorry, No resources submitted till now

        {% endfor %}

            Browse all {{ current_topic.name }} resources

{% endblock %}

{% block extra_js %}

{% endblock %}


text:
An example of a simple Node API server with a React front end. And Pokemon.

## Slides from the API presentation

[ProvoJS, July 2015: APIs](https://slides.com/andrewjensen/provojs-apis/).

## Running the server

Clone the repository, then run these commands in the project folder:
```
npm install
npm start
```

Now you can access the Web app ([http://localhost:3000](http://localhost:3000)) and the API ([http://localhost:4000](http://localhost:4000)).

## Current API endpoints

- `GET /api/trainers` (Get all the trainers in the database)
- `GET /api/pokemon` (Get all the pokemon in the database)

You can test out these endpoints in your web browser by navigating to [http://localhost:4000/api/trainers](http://localhost:4000/api/trainers) and [http://localhost:4000/api/pokemon](http://localhost:4000/api/pokemon). You can also format the JSON data that is returned with a Chrome extension - see below.

## Completing the project

The front end is already finished, but there are a few API endpoints that need to be implemented for the project to work.
You need to implement the following endpoints:

- `GET /api/trainers:id` (get a specific trainer)
- `GET /api/trainers:id/pokemon` (get the pokemon for a specific trainer)
- `GET /api/pokemon/:id` (get a specific pokemon)
- `POST /api/trainers` (add a trainer)
- `POST /api/pokemon` (add a pokemon)

See `api-server.js` for more help on how to create these endpoints.

## Resources

- [JSON Formatter Chrome extension](https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en)


text:
require 'spec_helper'

RSpec.describe Vtex::SkuResource do
  subject(:resource) { described_class.new(connection: connection) }
  include_context 'resources'

  describe "#sku" do
    it "returns a single sku" do
      stub_do_api('/api/catalog_system/pvt/sku/stockkeepingunitbyid/1', :get).to_return(body: api_fixture('sku/sku'))
      sku = resource.sku(sku_id: 1)
      expect(sku).to be_kind_of(Vtex::Sku)
    end
  end

  describe "#sku_id_by_ref_id" do
    it "returns a sku id" do
      stub_do_api('/api/catalog_system/pvt/sku/stockkeepingunitidbyrefid/playera', :get).to_return(body: "2001773", status: 200)
      sku = resource.sku_id_by_ref_id(ref_id: 'playera')
      expect(sku).to be_a(String)
    end
  end

  describe "#sku_by_ean" do
    it "returns a sku object" do
      stub_do_api('/api/catalog_system/pvt/sku/stockkeepingunitbyean/1234567890', :get).to_return(body: api_fixture('sku/sku'))
      sku = resource.sku_by_ean(ean: 1234567890)
      expect(sku).to be_kind_of(Vtex::Sku)
    end
  end

  describe "#sku_by_alternate_id" do
    it "returns a sku object" do
      stub_do_api('/api/catalog_system/pvt/sku/stockkeepingunitbyalternateId/1234567890', :get).to_return(body: api_fixture('sku/sku'))
      sku = resource.sku_by_alternate_id(ean: 1234567890)
      expect(sku).to be_kind_of(Vtex::Sku)
    end
  end

  describe "#sku_list_by_product_id" do
    it "returns a list of skus objects" do
      stub_do_api('/api/catalog_system/pvt/sku/stockkeepingunitByProductId/1', :get).to_return(body: api_fixture('sku/sku_list_by_product_id'))
      skus = resource.sku_list_by_product_id(product_id: 1)
      expect(skus).to match_array(Vtex::SkuList::Sku)
    end
  end
end


text:
require "sidekiq"
require "sidekiq_json_encoding_patch"
require "airbrake"

module Elasticsearch
  # This class requires the `config.rb` file to be loaded, since it requires
  # access to the `search_config` setting, but including it here can cause a
  # circular require dependency, from:
  #
  #   SearchConfig -> SearchServer -> IndexGroup -> Index -> DocumentQueue ->
  #   BulkIndexWorker -> SearchConfig
  class BaseWorker
    include Sidekiq::Worker

    # How long to wait, by default, if the index is currently locked
    LOCK_DELAY = 60  # seconds

    # Default options: can be overridden with `sidekiq_options` in subclasses
    sidekiq_options :retry => 5, :backtrace => 12

    def logger
      self.class.logger
    end

    # Logger is defined on the class for use in the `sidekiq_retries_exhausted`
    # block, and as an instance method for use the rest of the time
    def self.logger
      Logging.logger[self]
    end

    def self.forward_to_failure_queue
      sidekiq_retries_exhausted do |msg|
        logger.warn "Job '#{msg["jid"]}' failed; forwarding to failure queue"
        Airbrake.notify_or_ignore(FailedJobException.new(msg))
      end
    end

    class FailedJobException < Exception; end

  private
    def index(index_name)
      settings.search_config.search_server.index(index_name)
    end
  end
end


text:
package com.yfiton.core;

import com.google.common.collect.ImmutableMap;
import com.yfiton.api.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * @author lpellegr
 */
public final class NotifierRegistry {

    private static final Logger log = LoggerFactory.getLogger(NotifierRegistry.class);

    private final ServiceLoader<Notifier> notifierLoader;

    private Map<String, Notifier> availableNotifiers;

    private static final class LazyHolder {

        private static final NotifierRegistry INSTANCE = new NotifierRegistry();

    }

    public NotifierRegistry() {
        availableNotifiers = new HashMap<>();
        notifierLoader = ServiceLoader.load(Notifier.class);

        reload();
    }

    public Notifier find(String name) {
        return availableNotifiers.get(name);
    }

    public ImmutableMap<String, Notifier> getAvailable() {
        return ImmutableMap.copyOf(availableNotifiers);
    }

    public void register(Notifier notifier) {
        if (availableNotifiers.containsKey(notifier.getKey())) {
            throw new IllegalArgumentException("Notifier with the same key already registered: " + notifier.getKey());
        }

        availableNotifiers.put(notifier.getKey(), notifier);
    }

    public void reload() {
        notifierLoader.reload();

        Iterator<Notifier> iterator = notifierLoader.iterator();

        while (iterator.hasNext()) {
            try {
                register(iterator.next());
            } catch (ServiceConfigurationError e) {
                log.warn(e.getMessage() + ". Missing JavaFX dependency?");
            }
        }
    }

    public static NotifierRegistry getInstance() {
        return LazyHolder.INSTANCE;
    }

}


text:
#include "PropCamera.h"
//#include <tools/nmayacamcontrol.h>
#include <DB/AttrID.h>

// A manually controlled camera property which implements different control models.
// Based on mangalore VideoCameraProperty2_(C) 2005 Radon Labs GmbH

namespace Attr
{
	DeclareFloat(FilmAspectRatio);
	DeclareFloat(NearClipPlane);
	DeclareFloat(FarClipPlane);
	DeclareMatrix44(ProjectionMatrix);
};

namespace Properties
{

class CPropVideoCamera2 : public CPropCamera
{
	DeclareRTTI;
	DeclareFactory(CPropVideoCamera2);

private:

	//nMayaCamControl MayaCamera;

	DECLARE_EVENT_HANDLER(UpdateTransform, OnUpdateTransform);
	DECLARE_EVENT_HANDLER(OnObtainInputFocus, OnObtainInputFocus);
	DECLARE_EVENT_HANDLER(OnLoseInputFocus, OnLoseInputFocus);

	virtual void OnRender();
	virtual void OnObtainCameraFocus();

public:

	virtual void Activate();
	virtual void Deactivate();
	virtual void GetAttributes(nArray<DB::CAttrID>& Attrs);
};

RegisterFactory(CPropVideoCamera2);

}

#endif


text:
!ifdef NODELPHI
TARGETS=etl2log
!else
TARGETS=oskbulkrenderer etl2log
!endif
CLEANS=clean-support

!include ..\Header.mak

# ----------------------------------------------------------------------

oskbulkrenderer: .virtual
    cd $(ROOT)\src\support\oskbulkrenderer
    $(MAKE) $(TARGET)

etl2log: .virtual
    cd $(ROOT)\src\support\etl2log
    $(MAKE) $(TARGET)

# ----------------------------------------------------------------------

clean-support:
    cd $(ROOT)\src\support
    -del version.txt

!include ..\Target.mak

# ----------------------------------------------------------------------
# EOF
# ----------------------------------------------------------------------


text:
import unittest

from cathead import cadriver
from cathead.drivers import eca

class EcaDriverTestCase(unittest.TestCase):

    def test_sign(self):
        driver = eca.EcaDriver("host", "port", "user", "password")
        self.assertTrue(isinstance(driver, cadriver.CaDriver))


text:
class SzlMaximum: public SzlTabWriter {
 private:
  explicit SzlMaximum(const SzlType& type)
    : SzlTabWriter(type, true, false),
      cmp_(type.table() == "maximum"
           ? static_cast<SzlValueCmp*>(new SzlValueLess(&weight_ops()))
         : static_cast<SzlValueCmp*>(new SzlValueGreater(&weight_ops())))  { }
  virtual ~SzlMaximum()  { delete cmp_; }
  class SzlMaximumEntry;

 public:
  static SzlTabWriter* Create(const SzlType& type, string* error) {
    if (type.weight() == NULL)
      LOG(ERROR) << "Internal error - maximum/minimum without weight";
    if (!SzlOps::IsOrdered(type.weight()->type())) {
      *error = "can't compare weights";
      return NULL;
    }
    return new SzlMaximum(type);
  }

  virtual SzlTabEntry* CreateEntry(const string& index) const {
    return new SzlMaximumEntry(weight_ops(), param(), cmp());
  }

  // Accessors
  const SzlValueCmp* cmp() const { return cmp_; }

 private:
  // The comparison we want for our heap.
  SzlValueCmp* cmp_;

  class SzlMaximumEntry : public SzlTabEntry {
   public:
    SzlMaximumEntry(const SzlOps& weight_ops, int param, const SzlValueCmp* cmp)
      : weight_ops_(weight_ops), heap_(weight_ops, cmp, param)  { }

    virtual int AddElem(const string& elem) {
      return AddWeightedElem(elem, SzlValue(static_cast<int64>(1)));
    }

    virtual int AddWeightedElem(const string& elem, const SzlValue& weight) {
      ++tot_elems_;
      return heap_.AddElem(elem, weight);
    }

    virtual void Flush(string* output);
    virtual void FlushForDisplay(vector<string>* output);
    virtual SzlTabEntry::MergeStatus Merge(const string& val);

    virtual void Clear() {
      tot_elems_ = 0;
      heap_.Clear();
    }

    virtual int Memory() {
      return sizeof(SzlMaximumEntry) + heap_.Memory() + sizeof(SzlValueCmp);
    }

    virtual int64 TotElems() const { return tot_elems_; }
    virtual int TupleCount() { return heap_.nElems(); }

    const SzlOps& weight_ops() const  { return weight_ops_; }

   private:
    const SzlOps& weight_ops_;

    // Structure for keeping track of the current biggest (or smallest) elements.
    // TODO: Add an iterator for sorted output to improve
    // FlushForDisplay performance.
    SzlHeap heap_;

    // Total elements ever added to the table.
    int64 tot_elems_;
  };
};

// Register for both minimum and maximum tables.
REGISTER_SZL_TAB_WRITER(maximum, SzlMaximum);
REGISTER_SZL_TAB_WRITER(minimum, SzlMaximum);

void SzlMaximum::SzlMaximumEntry::Flush(string* output) {
  if (heap_.nElems() == 0) {
    output->clear();
    return;
  }
  // Combine all of the counts and tags into a single sorted string.
  SzlEncoder enc;
  enc.PutInt(tot_elems_ - heap_.nElems());
  enc.PutInt(heap_.nElems());

  // ReHeap is necessary after the Sort.
  heap_.Sort();
  for (int i = 0; i < heap_.nElems(); ++i) {
    const SzlHeap::Elem* elem = heap_.Element(i);
    enc.PutBytes(elem->value.data(), elem->value.size());
    weight_ops().Encode(elem->weight, &enc);
  }

  enc.Swap(output);
  Clear();
}

void SzlMaximum::SzlMaximumEntry::FlushForDisplay(vector<string>* output) {
  output->clear();
  if (heap_.nElems() == 0) {
    output->push_back("");
    return;
  }

  // ReHeap is necessary after the sort.
  heap_.Sort();
  for (int i = 0; i < heap_.nElems(); ++i) {
    // TODO: check this and similar cases.
    // Encoding code and decoding code does not match because "elem->value" is
    // already SzlEncode'ed. SzlEncoder string handling relies on '\0' and
    // does not allow more than one wrapping.
    SzlEncoder enc;
    const SzlHeap::Elem* elem = heap_.Element(i);
    weight_ops().Encode(elem->weight, &enc);
    string encoded;
    enc.Swap(&encoded);
    output->push_back(elem->value + encoded);
  }
  heap_.ReHeap();
}

SzlTabEntry::MergeStatus SzlMaximum::SzlMaximumEntry::Merge(const string& val) {
  if (val.empty())
    return MergeOk;

  SzlDecoder dec(val.data(), val.size());
  int64 extra;
  if (!dec.GetInt(&extra))
    return MergeError;
  int64 nvals;
  if (!dec.GetInt(&nvals))
    return MergeError;

  // Check for consistent params.
  if (nvals > heap_.maxElems() || (nvals < heap_.maxElems() && extra != 0))
    return MergeError;

  // Check input validity.
  for (int i = 0; i < nvals; ++i) {
    if (!dec.Skip(SzlType::BYTES) || !weight_ops().Skip(&dec))
      return MergeError;
  }
  if (!dec.done())
    return MergeError;

  // Now we know the string is ok, sample all of its elements.
  dec.Restart();
  if (!dec.Skip(SzlType::INT))
    return MergeError;
  if (!dec.Skip(SzlType::INT))
    return MergeError;
  SzlValue w;
  for (int i = 0; i < nvals; ++i) {
    string s;
    if (!dec.GetBytes(&s))
      return MergeError;
    if (!weight_ops().Decode(&dec, &w))
      return MergeError;
    AddWeightedElem(s, w);
  }
  weight_ops().Clear(&w);

  tot_elems_ += extra;

  return MergeOk;
}


text:
package org.matrix.androidsdk.rest.model.search;

import org.matrix.androidsdk.rest.model.Event;

import java.util.List;
import java.util.Map;

/**
 * Class representing a search API response
 */
public class SearchRoomEventResults {
    /**
     * Total number of results found.
     */
    public Integer count;

    /**
     * List of results in the requested order.
     */
    public List<SearchResult> results;

    /**
     * The current state for every room in the results.
     * This is included if the request had the include_state key set with a value of true.
     * The key is the roomId, the value its state. (TODO_SEARCH: right?)
     */
    public Map<String, List<Event>> state;

    /**
     * Any groups that were requested.
     * The key is the group id (TODO_SEARCH).
     */
    public Map<String, SearchGroup> groups;

    /**
     * Token that can be used to get the next batch of results in the group, if exists.
     */
    public String nextBatch;
}


text:
#include<iostream>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<vector>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<cassert>
#include<cmath>

using namespace std;

namespace cds_utils
{

	clock_t init;
	void start_timing() {
		init = clock();
	}

	double get_timing() {
		clock_t fin = clock();
		return (1000.*(fin-init)/CLOCKS_PER_SEC);
	}

};


text:
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-up "['<Control><Primary><Alt>k']"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-down "['<Control><Primary><Alt>j']"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-left "['<Control><Primary><Alt>h']"
gsettings set org.gnome.desktop.wm.keybindings switch-to-workspace-right "['<Control><Primary><Alt>l']"
gsettings set org.gnome.desktop.wm.keybindings move-to-workspace-up "['<Control><Primary><Alt><Shift>k']"
gsettings set org.gnome.desktop.wm.keybindings move-to-workspace-down "['<Control><Primary><Alt><Shift>j']"
gsettings set org.gnome.desktop.wm.keybindings move-to-workspace-left "['<Control><Primary><Alt><Shift>h']"
gsettings set org.gnome.desktop.wm.keybindings move-to-workspace-right "['<Control><Primary><Alt><Shift>l']"

gsettings set org.gnome.desktop.wm.keybindings toggle-maximized "['F4']"


text:
PYTHON=python3

test:
	$(PYTHON) -m unittest discover -s tests -p 'test_*.py'

clean:
	find . -name "*.py[oc]" -delete
	find . -name "__pycache__" -delete
	rm -rf build dist MANIFEST

pypi: clean
	$(PYTHON) setup.py sdist upload