text:
/* Commentary:
 *
 */

/* Change log:
 *
 */

#include "dtkComposerEvaluator.h"
#include "dtkComposerGraph.h"
#include "dtkComposerMachine.h"
#include "dtkComposerMachineState.h"
#include "dtkComposerReader.h"
#include "dtkComposerScene.h"
#include "dtkComposerScene_p.h"
#include "dtkComposerSceneEdge.h"
#include "dtkComposerSceneNode.h"
#include "dtkComposerSceneNodeComposite.h"
#include "dtkComposerSceneNodeControl.h"
#include "dtkComposerSceneNodeLeaf.h"
#include "dtkComposerSceneNote.h"
#include "dtkComposerScenePort.h"
#include "dtkComposerStack.h"
#include "dtkComposerStackCommand.h"
#include "dtkComposerStackUtils.h"
#include "dtkComposerWriter.h"
#include "dtkCoreSupport/dtkGlobal.h"

dtkComposerScene::dtkComposerScene(QObject *parent) : QGraphicsScene(parent), d(new dtkComposerScenePrivate)
{
    d->factory = NULL;
    d->machine = NULL;
    d->stack = NULL;
    d->graph = NULL;

    // BspTreeIndex causes some bugs with (at least) "enter group"
    setItemIndexMethod( QGraphicsScene::NoIndex);

    d->root_node = new dtkComposerSceneNodeComposite;
    d->root_node->setRoot(true);
    d->root_node->setTitle("Root");

    d->current_node = d->root_node;
    d->current_edge = NULL;

    d->reparent_origin = NULL;
    d->reparent_target = NULL;

    d->masked_edges = false;

    d->mask_edges_action = new QAction("Mask Edges", this);
    d->mask_edges_action->setShortcut(QKeySequence(Qt::ControlModifier  + Qt::Key_M));

    d->unmask_edges_action = new QAction("Unmask Edges", this);
    d->unmask_edges_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::ShiftModifier + Qt::Key_M));

    d->flag_as_blue_action = new QAction("Flag as blue", this);
    d->flag_as_blue_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier + Qt::Key_B));
    d->flag_as_blue_action->setIcon(QIcon(":dtkComposer/pixmaps/dtk-composer-node-flag-blue.png"));

    d->flag_as_gray_action = new QAction("Flag as gray", this);
    d->flag_as_gray_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier + Qt::Key_W));
    d->flag_as_gray_action->setIcon(QIcon(":dtkComposer/pixmaps/dtk-composer-node-flag-gray.png"));

    d->flag_as_green_action = new QAction("Flag as green", this);
    d->flag_as_green_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier + Qt::Key_G));
    d->flag_as_green_action->setIcon(QIcon(":dtkComposer/pixmaps/dtk-composer-node-flag-green.png"));

    d->flag_as_orange_action = new QAction("Flag as orange", this);
    d->flag_as_orange_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier + Qt::Key_O));
    d->flag_as_orange_action->setIcon(QIcon(":dtkComposer/pixmaps/dtk-composer-node-flag-orange.png"));

    d->flag_as_pink_action = new QAction("Flag as pink", this);
    d->flag_as_pink_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier + Qt::Key_P));
    d->flag_as_pink_action->setIcon(QIcon(":dtkComposer/pixmaps/dtk-composer-node-flag-pink.png"));

    d->flag_as_red_action = new QAction("Flag as red", this);
    d->flag_as_red_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier + Qt::Key_R));
    d->flag_as_red_action->setIcon(QIcon(":dtkComposer/pixmaps/dtk-composer-node-flag-red.png"));

    d->flag_as_yellow_action = new QAction("Flag as yellow", this);
    d->flag_as_yellow_action->setShortcut(QKeySequence(Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier + Qt::Key_Y));
    d->flag_as_yellow_action->setIcon(QIcon(":dtkComposer/pixmaps/dtk-composer-node-flag-yellow.png"));

    connect(this, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));

    connect(d->mask_edges_action, SIGNAL(triggered()), this, SLOT(onMaskEdge()));
    connect(d->unmask_edges_action, SIGNAL(triggered()), this, SLOT(onUnMaskEdge()));

    connect(d->flag_as_blue_action, SIGNAL(triggered()), this, SLOT(onFlagAsBlue()));
    connect(d->flag_as_gray_action, SIGNAL(triggered()), this, SLOT(onFlagAsGray()));
    connect(d->flag_as_green_action, SIGNAL(triggered()), this, SLOT(onFlagAsGreen()));
    connect(d->flag_as_orange_action, SIGNAL(triggered()), this, SLOT(onFlagAsOrange()));
    connect(d->flag_as_pink_action, SIGNAL(triggered()), this, SLOT(onFlagAsPink()));
    connect(d->flag_as_red_action, SIGNAL(triggered()), this, SLOT(onFlagAsRed()));
    connect(d->flag_as_yellow_action, SIGNAL(triggered()), this, SLOT(onFlagAsYellow()));
}

dtkComposerScene::~dtkComposerScene(void)
{
    delete d;

    d = NULL;
}

// /////////////////////////////////////////////////////////////////

void dtkComposerScene::clear(void)
{
    foreach (dtkComposerSceneNode *node, d->root_node->nodes()) {

        dtkComposerStackCommandDestroyNode *command = new dtkComposerStackCommandDestroyNode;
        command->setGraph(d->graph);
        command->setScene(this);
        command->setFactory(d->factory);
        command->setNode(node);
        command->redo();

        delete command;
    }

    foreach (dtkComposerSceneNote *note, d->root_node->notes()) {

        dtkComposerStackCommandDestroyNote *command = new dtkComposerStackCommandDestroyNote;
        command->setGraph(d->graph);
        command->setScene(this);
        command->setFactory(d->factory);
        command->setNote(note);
        command->redo();

        delete command;
    }
}

bool dtkComposerScene::maskedEdges(void)
{
    return d->masked_edges;
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Setup
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::setFactory(dtkComposerFactory *factory)
{
    d->factory = factory;
}

void dtkComposerScene::setMachine(dtkComposerMachine *machine)
{
    d->machine = machine;
}

void dtkComposerScene::setStack(dtkComposerStack *stack)
{
    d->stack = stack;
}

void dtkComposerScene::setGraph(dtkComposerGraph *graph)
{
    d->graph = graph;
    d->graph->addNode(d->root_node);
    d->graph->layout();
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Composition depth management
// /////////////////////////////////////////////////////////////////

dtkComposerSceneNodeComposite *dtkComposerScene::root(void)
{
    return d->root_node;
}

dtkComposerSceneNodeComposite *dtkComposerScene::current(void)
{
    return d->current_node;
}

void dtkComposerScene::setRoot(dtkComposerSceneNodeComposite *root)
{
    foreach (dtkComposerSceneNote *note, root->notes())
        this->addItem(note);

    dtkComposerSceneNode *first = NULL;

    dtkComposerSceneNode *node;

    for (int i = 0; i < root->nodes().count(); ++i) {

        node = root->nodes()[i];

        if (i == 0)
            first = node;

        this->addItem(node);
    }

    foreach (dtkComposerSceneEdge *edge, root->edges()) {

        this->addItem(edge);

        if (first)
            edge->stackBefore(first);
    }

    emit modified(true);
}

void dtkComposerScene::setCurrent(dtkComposerSceneNode *node)
{
    if (!node)
        d->current_node = d->root_node;
    else if (dtkComposerSceneNodeComposite *composite = dynamic_cast<dtkComposerSceneNodeComposite *>(node))
        d->current_node = composite;
    else
        qDebug() << DTK_PRETTY_FUNCTION << "Node should be a composite one";

    emit changed();
}

void dtkComposerScene::setCurrent(dtkComposerSceneNodeComposite *current)
{
    d->current_node = current;
    emit changed();
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Scene management
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::addItem(QGraphicsItem *item)
{
    if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(item)) {

        QGraphicsScene::addItem(item);

        foreach (dtkComposerSceneNodeComposite *block, control->blocks()) {

            block->setParentItem(control);

            foreach (dtkComposerSceneNote *note, block->notes()) {
                this->addItem(note);
                control->stackBefore(note);
            }

            dtkComposerSceneNode *first = NULL;
            dtkComposerSceneNode *node;

            for (int i = 0; i < block->nodes().count(); ++i) {
                node = block->nodes()[i];

                if (i == 0)
                    first = node;

                this->addItem(node);
                control->stackBefore(node);
            }

            foreach (dtkComposerSceneEdge *edge, block->edges()) {
                this->addItem(edge);

                if (first)
                    edge->stackBefore(first);
            }
        }

        control->layout();

        emit modified(true);

        return;
    }

    if (dtkComposerSceneNodeComposite *composite = dynamic_cast<dtkComposerSceneNodeComposite *>(item)) {

        if (item != d->root_node)
            QGraphicsScene::addItem(item);

        if (!composite->flattened() && !composite->entered() && !composite->root()) {
            emit modified(true);
            return;
        }

        foreach (dtkComposerSceneNote *note, composite->notes())
            this->addItem(note);

        dtkComposerSceneNode *first = NULL;
        dtkComposerSceneNode *node;

        for (int i = 0; i < composite->nodes().count(); ++i) {
            node = composite->nodes()[i];

            if (i == 0)
                first = node;

            this->addItem(node);
        }

        foreach (dtkComposerSceneEdge *edge, composite->edges()) {
            this->addItem(edge);

            if (first)
                edge->stackBefore(first);
        }

        composite->layout();

        emit modified(true);

        return;
    }

    if (dtkComposerSceneNodeLeaf *leaf = dynamic_cast<dtkComposerSceneNodeLeaf *>(item)) {

        if (leaf->flagged()) {

            Qt::GlobalColor color = leaf->flagColor();

            if (!d->flagged_nodes[color].contains(leaf))
                d->flagged_nodes[color] << leaf;
        }
    }

    QGraphicsScene::addItem(item);

    emit modified(true);
}

void dtkComposerScene::removeItem(QGraphicsItem *item)
{
    if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(item)) {

        QGraphicsScene::removeItem(item);

        foreach (dtkComposerSceneNodeComposite *block, control->blocks()) {

            foreach (dtkComposerSceneNote *note, block->notes())
                this->removeItem(note);

            foreach (dtkComposerSceneNode *node, block->nodes())
                this->removeItem(node);

            foreach (dtkComposerSceneEdge *edge, block->edges())
                this->removeItem(edge);
        }

        emit modified(true);

        return;
    }

    if (dtkComposerSceneNodeComposite *composite = dynamic_cast<dtkComposerSceneNodeComposite *>(item)) {

        if (item != d->root_node)
            QGraphicsScene::removeItem(composite);

        if (!composite->flattened() && !composite->entered() && !composite->root()) {
            emit modified(true);
            return;
        }

        foreach (dtkComposerSceneNote *note, composite->notes())
            this->removeItem(note);

        foreach (dtkComposerSceneNode *node, composite->nodes())
            this->removeItem(node);

        foreach (dtkComposerSceneEdge *edge, composite->edges())
            this->removeItem(edge);

        emit modified(true);

        return;
    }

    QGraphicsScene::removeItem(item);

    emit modified(true);
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Actions
// /////////////////////////////////////////////////////////////////

QAction *dtkComposerScene::flagAsBlueAction(void)
{
    return d->flag_as_blue_action;
}

QAction *dtkComposerScene::flagAsGrayAction(void)
{
    return d->flag_as_gray_action;
}

QAction *dtkComposerScene::flagAsGreenAction(void)
{
    return d->flag_as_green_action;
}

QAction *dtkComposerScene::flagAsOrangeAction(void)
{
    return d->flag_as_orange_action;
}

QAction *dtkComposerScene::flagAsPinkAction(void)
{
    return d->flag_as_pink_action;
}

QAction *dtkComposerScene::flagAsRedAction(void)
{
    return d->flag_as_red_action;
}

QAction *dtkComposerScene::flagAsYellowAction(void)
{
    return d->flag_as_yellow_action;
}

QAction *dtkComposerScene::maskEdgesAction(void)
{
    return d->mask_edges_action;
}

QAction *dtkComposerScene::unmaskEdgesAction(void)
{
    return d->unmask_edges_action;
}

QList<dtkComposerSceneNodeLeaf *> dtkComposerScene::flagged(Qt::GlobalColor color)
{
    return d->flagged_nodes[color];
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Sig Events
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::modify(bool b)
{
    emit modified(b);
}

void dtkComposerScene::onMaskEdge(void)
{
    // if (d->masked_edges)
    //     return;

    d->masked_edges = true;
    populateEdges();

    foreach (dtkComposerSceneEdge *edge, d->all_edges) {
        edge->setOpacity(0.05);
    }
}

void dtkComposerScene::onUnMaskEdge(void)
{
    // if (!d->masked_edges)
    //     return;

    d->masked_edges = false;
    populateEdges();

    foreach (dtkComposerSceneEdge *edge, d->all_edges) {
        edge->setOpacity(1);
    }
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Flag Events
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::onFlagAsBlue(void)
{
    this->onFlagAs(Qt::blue);
}

void dtkComposerScene::onFlagAsGray(void)
{
    this->onFlagAs(Qt::gray);
}

void dtkComposerScene::onFlagAsGreen(void)
{
    this->onFlagAs(Qt::green);
}

void dtkComposerScene::onFlagAsOrange(void)
{
    this->onFlagAs(Qt::darkYellow);
}

void dtkComposerScene::onFlagAsRed(void)
{
    this->onFlagAs(Qt::red);
}

void dtkComposerScene::onFlagAsPink(void)
{
    this->onFlagAs(Qt::magenta);
}

void dtkComposerScene::onFlagAsYellow(void)
{
    this->onFlagAs(Qt::yellow);
}

void dtkComposerScene::onFlagAs(Qt::GlobalColor color)
{
    foreach (QGraphicsItem *item, this->selectedItems()) {

        if (dtkComposerSceneNodeLeaf *node = dynamic_cast<dtkComposerSceneNodeLeaf *>(item)) {

            if (node->flagged(color))
                d->flagged_nodes[color].removeAll(node);

            node->flag(color, !node->flagged(color));

            if (node->flagged(color))
                d->flagged_nodes[color] << node;

            emit flagged();
        }
    }
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Drag n Drop Events
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
    if (event->mimeData()->hasUrls())
        event->acceptProposedAction();
    else
        QGraphicsScene::dragEnterEvent(event);
}

void dtkComposerScene::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
    if (event->mimeData()->hasUrls())
        event->acceptProposedAction();
    else
        QGraphicsScene::dragLeaveEvent(event);
}

void dtkComposerScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
    if (event->mimeData()->hasUrls())
        event->acceptProposedAction();
    else
        QGraphicsScene::dragMoveEvent(event);
}

void dtkComposerScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
    if (event->mimeData()->hasUrls()) {

        QString name = event->mimeData()->text();
        QUrl url = event->mimeData()->urls().first();

        if (url.scheme() == "note") {

            dtkComposerStackCommandCreateNote *command = new dtkComposerStackCommandCreateNote;
            command->setScene(this);
            command->setParent(this->parentAt(event->scenePos()));
            command->setPosition(event->scenePos());

            d->stack->push(command);

            event->acceptProposedAction();

            return;
        }

        if (url.scheme() == "node") {

            dtkComposerStackCommandCreateNode *command = new dtkComposerStackCommandCreateNode;
            command->setFactory(d->factory);
            command->setScene(this);
            command->setGraph(d->graph);
            command->setParent(this->parentAt(event->scenePos()));
            command->setPosition(event->scenePos());
            command->setType(url.path());
            command->setName(name);

            d->stack->push(command);

            event->acceptProposedAction();

            return;
        }

    }

    QGraphicsScene::dropEvent(event);
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Keyboard Events
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::keyPressEvent(QKeyEvent *event)
{
    if ((event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) && (event->modifiers() & Qt::ControlModifier)) {

        QList<dtkComposerSceneNode *> selected_nodes;
        QList<dtkComposerSceneNote *> selected_notes;
        QList<dtkComposerSceneEdge *> selected_edges;

        // retrieve items to be deleted

        foreach (QGraphicsItem *item, this->selectedItems()) {
            if (dtkComposerSceneNode *snode = dynamic_cast<dtkComposerSceneNode *>(item))
                selected_nodes << snode;

            if (dtkComposerSceneNote *snote = dynamic_cast<dtkComposerSceneNote *>(item))
                selected_notes << snote;

            if (dtkComposerSceneEdge *sedge = dynamic_cast<dtkComposerSceneEdge *>(item))
                selected_edges << sedge;
        }

        // multiple node deletion

        if (selected_nodes.count() + selected_edges.count() > 1 ) {

            dtkComposerStackCommand *group = new dtkComposerStackCommand;
            group->setText("Destroy a set of nodes/edges");

            foreach (dtkComposerSceneNode *node, selected_nodes) {

                dtkComposerStackCommandDestroyNode *command = new dtkComposerStackCommandDestroyNode(group);
                command->setScene(this);
                command->setGraph(d->graph);
                command->setNode(node);
            }

            foreach (dtkComposerSceneEdge *edge, selected_edges) {

                // ne need to destroy edge if the src or dest node will be destroyed
                bool skip = false;

                foreach (dtkComposerSceneNode *node, selected_nodes)
                    if (edge->source()->node() == node || edge->destination()->node() == node) {
                        skip = true;
                    }

                if (!skip) {
                    dtkComposerStackCommandDestroyEdge *command = new dtkComposerStackCommandDestroyEdge(group);
                    command->setScene(this);
                    command->setGraph(d->graph);
                    command->setEdge(edge);
                }
            }

            d->stack->push(group);

            // single node deletion

        } else if (selected_nodes.count() == 1) {

            dtkComposerStackCommandDestroyNode *command = new dtkComposerStackCommandDestroyNode;
            command->setScene(this);
            command->setGraph(d->graph);
            command->setNode(selected_nodes.first());

            d->stack->push(command);

            // single edge deletion

        } else if (selected_edges.count() == 1) {

            dtkComposerStackCommandDestroyEdge *command = new dtkComposerStackCommandDestroyEdge;
            command->setScene(this);
            command->setGraph(d->graph);
            command->setEdge(selected_edges.first());

            d->stack->push(command);
        }

        // multiple note deletion

        if (selected_notes.count() > 1) {

            dtkComposerStackCommand *group = new dtkComposerStackCommand;
            group->setText("Destroy a set of notes");

            foreach (dtkComposerSceneNote *note, selected_notes) {

                dtkComposerStackCommandDestroyNote *command = new dtkComposerStackCommandDestroyNote(group);
                command->setScene(this);
                command->setNote(note);
            }

            d->stack->push(group);

            // single note deletion

        } else if (selected_notes.count() == 1) {

            dtkComposerStackCommandDestroyNote *command = new dtkComposerStackCommandDestroyNote;
            command->setScene(this);
            command->setNote(selected_notes.first());

            d->stack->push(command);
        }

    } else if ((event->key() == Qt::Key_G) && (event->modifiers() & Qt::ControlModifier)) {

        dtkComposerSceneNodeList selected_nodes;
        dtkComposerSceneNoteList selected_notes;

        foreach (QGraphicsItem *item, this->selectedItems()) {
            if (dtkComposerSceneNode *snode = dynamic_cast<dtkComposerSceneNode *>(item))
                selected_nodes << snode;

            if (dtkComposerSceneNote *snote = dynamic_cast<dtkComposerSceneNote *>(item))
                selected_notes << snote;
        }

        if (selected_nodes.count()) {

            dtkComposerStackCommandCreateGroup *command = new dtkComposerStackCommandCreateGroup;
            command->setScene(this);
            command->setGraph(d->graph);
            command->setNodes(selected_nodes);
            command->setNotes(selected_notes);

            if (areBrothers(selected_nodes, selected_notes))
                d->stack->push(command);
            else
                delete command;
        }

    } else if ((event->key() == Qt::Key_C) && (event->modifiers() & Qt::ControlModifier)) {
        //copy

        d->copy_nodes.clear();

        foreach (QGraphicsItem *item, this->selectedItems()) {
            if (dtkComposerSceneNode *snode = dynamic_cast<dtkComposerSceneNode *>(item))
                d->copy_nodes << snode;
        }

    } else if ((event->key() == Qt::Key_V) && (event->modifiers() & Qt::ControlModifier) ) {
        // paste
        if (d->copy_nodes.isEmpty() || !areBrothers(d->copy_nodes))
            return;

        dtkComposerStackCommandCopyNodes *command = new dtkComposerStackCommandCopyNodes;
        command->setScene(this);
        command->setGraph(d->graph);
        command->setFactory(d->factory);
        command->setNodes(d->copy_nodes);

        d->stack->push(command);

    } else if ((event->key() == Qt::Key_U) && (event->modifiers() & Qt::ControlModifier) && (this->selectedItems().count() == 1)) {

        if (dtkComposerSceneNodeComposite *group = dynamic_cast<dtkComposerSceneNodeComposite *>(this->selectedItems().first())) {

            if (!group->entered() || !group->flattened()) {

                dtkComposerStackCommandDestroyGroup *command = new dtkComposerStackCommandDestroyGroup;
                command->setGraph(d->graph);
                command->setScene(this);
                command->setNode(group);

                d->stack->push(command);
            }
        }

    } else {

        QGraphicsScene::keyPressEvent(event);

    }
}

void dtkComposerScene::keyReleaseEvent(QKeyEvent *event)
{
    QGraphicsScene::keyReleaseEvent(event);
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Mouse Events
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsScene::mouseMoveEvent(event);

    if (!(event->buttons() & Qt::LeftButton))
        return;

    if (d->current_edge)
        goto adjust_edges;

//-- Managing reparenting

    if (d->reparent_origin_pos.isNull()) {

        d->reparent_origin = this->nodeAt(event->scenePos());

        if (!d->reparent_origin) {
            this->views().at(0)->setCursor(Qt::ArrowCursor);
            goto adjust_edges;
        }

        if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(d->reparent_origin->parent()))
            d->reparent_origin = control;

        d->reparent_origin_pos = d->reparent_origin->pos();

    } else {

        dtkComposerSceneNode *node = this->nodeAt(event->scenePos(), d->reparent_origin);

        if (!node) {
            d->reparent_target = NULL;
            this->views().at(0)->setCursor(Qt::ArrowCursor);
            goto adjust_edges;
        }

        if (dynamic_cast<dtkComposerSceneNodeComposite *>(node)) {

            d->reparent_target = node;

            if (d->reparent_origin->parent() == d->reparent_target) {
                d->reparent_target = NULL;
                this->views().at(0)->setCursor(Qt::ArrowCursor);
                goto adjust_edges;
            }

            if (dynamic_cast<dtkComposerSceneNodeControl *>(d->reparent_target->parent())) {
                d->reparent_target = NULL;
                this->views().at(0)->setCursor(Qt::ArrowCursor);
                goto adjust_edges;
            }

            this->views().at(0)->setCursor(Qt::PointingHandCursor);
        }

        if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(node)) {
            // Look for a block within the control node

            dtkComposerSceneNodeComposite *block = control->blockAt(event->scenePos());

            if (!block) {
                this->views().at(0)->setCursor(Qt::ArrowCursor);
                d->reparent_target = NULL;
                goto adjust_edges;
            }

            if (d->reparent_origin->parent() == block) {
                d->reparent_target = NULL;
                this->views().at(0)->setCursor(Qt::ArrowCursor);
                goto adjust_edges;
            }

            d->reparent_target = block;

            this->views().at(0)->setCursor(Qt::PointingHandCursor);
        }

    }

// --

adjust_edges: // Adjusting edges of selected nodes

    foreach (QGraphicsItem *item, this->selectedItems())
        if (dtkComposerSceneNode *node = dynamic_cast<dtkComposerSceneNode *>(item))
            node->layout();

    this->update();

// adjust_current: // Adjusting current edge

    if (d->current_edge)
        d->current_edge->adjust(d->current_edge->source()->mapToScene(d->current_edge->source()->boundingRect().center()), event->scenePos());

    if (d->current_edge)
        this->update(d->current_edge->boundingRect());

    if (d->current_edge)
        event->accept();
}

void dtkComposerScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsScene::mousePressEvent(event);

    dtkComposerScenePort *source = this->portAt(event->scenePos());

    if (!source)
        return;

    if (d->current_edge)
        return;

    d->current_edge = new dtkComposerSceneEdge;
    d->current_edge->setSource(source);

    this->addItem(d->current_edge);
}

void dtkComposerScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsScene::mouseReleaseEvent(event);

    foreach (dtkComposerSceneEdge *e, d->connected_edges)
        e->setConnected(false);

    d->connected_edges.clear();

    // Managing of reparenting

    if (d->reparent_target && d->reparent_target != d->reparent_origin) {

        d->reparent_target_pos = event->scenePos() - event->pos();

        dtkComposerStackCommandReparentNode *command = new dtkComposerStackCommandReparentNode;
        command->setScene(this);
        command->setGraph(d->graph);
        command->setOriginNode(d->reparent_origin);
        command->setTargetNode(d->reparent_target);
        command->setOriginPosition(d->reparent_origin_pos);
        command->setTargetPosition(d->reparent_target_pos);
        d->stack->push(command);

        d->reparent_origin = NULL;
        d->reparent_target = NULL;

        this->views().at(0)->setCursor(Qt::ArrowCursor);
    }

    if (d->reparent_target == d->reparent_origin)
        this->views().at(0)->setCursor(Qt::ArrowCursor);

    d->reparent_origin_pos = QPointF();
    d->reparent_target_pos = QPointF();

    // Managing of current edge

    if (!d->current_edge) {
        foreach (QGraphicsItem *item, this->selectedItems()) {
            if (dtkComposerSceneNode *snode = dynamic_cast<dtkComposerSceneNode *>(item)) {
                if (dtkComposerSceneNodeComposite *composite = dynamic_cast<dtkComposerSceneNodeComposite *>(snode)) {
                    foreach (dtkComposerSceneEdge *e, composite->edges())
                        d->connected_edges << e;

                    foreach (dtkComposerSceneEdge *e, composite->inputEdges())
                        d->connected_edges << e;

                    foreach (dtkComposerSceneEdge *e, composite->outputEdges())
                        d->connected_edges << e;
                } else if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(snode)) {
                    d->connected_edges << control->header()->inputEdges();
                    d->connected_edges << control->footer()->outputEdges();

                    foreach (dtkComposerSceneNodeComposite *b, control->blocks()) {
                        foreach (dtkComposerSceneEdge *e, b->edges())
                            d->connected_edges << e;

                        foreach (dtkComposerSceneEdge *e, b->inputEdges())
                            d->connected_edges << e;

                        foreach (dtkComposerSceneEdge *e, b->outputEdges())
                            d->connected_edges << e;
                    }
                }

                foreach (dtkComposerSceneEdge *e, snode->inputEdges())
                    d->connected_edges << e;

                foreach (dtkComposerSceneEdge *e, snode->outputEdges())
                    d->connected_edges << e;

                foreach (dtkComposerSceneEdge *e, d->connected_edges)
                    e->setConnected(true);
            }
        }

        return;
    }

    if (dtkComposerScenePort *destination = this->portAt(event->scenePos()))
        d->current_edge->setDestination(destination);

    if (d->current_edge->link()) {
        bool srcInput = d->current_edge->source()->type() == dtkComposerScenePort::Input;
        bool dstInput = d->current_edge->destination()->type() == dtkComposerScenePort::Input;
        bool srcComposite = dynamic_cast<dtkComposerSceneNodeComposite *>(d->current_edge->source()->node()) != NULL;
        bool dstComposite = dynamic_cast<dtkComposerSceneNodeComposite *>(d->current_edge->destination()->node()) != NULL;
        bool dstParent = d->current_edge->destination()->node() == d->current_edge->source()->owner()->parent() ;
        bool srcParent = d->current_edge->source()->node() == d->current_edge->destination()->owner()->parent() ;
        bool sameParent = d->current_edge->source()->owner()->parent() == d->current_edge->destination()->owner()->parent() ;

        if (!((srcInput  && !dstInput) ||
                (!srcInput &&  dstInput &&  srcParent) ||
                (!srcInput &&  dstInput &&  dstParent) ||
                (srcInput  &&  dstInput && !srcComposite) ||
                (!srcInput && !dstInput && !dstComposite) ||
                (!sameParent && !(dstParent || srcParent)) ||
                (!srcInput && !dstInput &&  srcComposite && dstComposite && srcParent) ||
                (srcInput  &&  dstInput &&  srcComposite && dstComposite && dstParent))) {
            dtkComposerStackCommandCreateEdge *command = new dtkComposerStackCommandCreateEdge;
            command->setGraph(d->graph);
            command->setScene(this);
            command->setSource(d->current_edge->source());
            command->setDestination(d->current_edge->destination());

            d->stack->push(command);
        }
    }

    d->current_edge->unlink();

    this->removeItem(d->current_edge);

    delete d->current_edge;

    d->current_edge = NULL;
}

void dtkComposerScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
    QGraphicsScene::mouseDoubleClickEvent(event);

    dtkComposerSceneNode *node = this->nodeAt(event->scenePos());

    if (!node)
        return;

    dtkComposerSceneNodeComposite *composite = dynamic_cast<dtkComposerSceneNodeComposite *>(node);

    if (composite) {

        dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(node->parent());

        if (!control) {

            if (event->modifiers() & Qt::ControlModifier) {

                if (!composite->flattened() && !composite->entered()) {

                    dtkComposerStackCommandFlattenGroup *command = new dtkComposerStackCommandFlattenGroup;
                    command->setScene(this);
                    command->setNode(composite);
                    d->stack->push(command);

                } else if (!composite->entered()) {

                    dtkComposerStackCommandUnflattenGroup *command = new dtkComposerStackCommandUnflattenGroup;
                    command->setScene(this);
                    command->setNode(composite);
                    d->stack->push(command);
                }

            } else {

                if (!composite->entered() && !composite->flattened()) {

                    dtkComposerStackCommandEnterGroup *command = new dtkComposerStackCommandEnterGroup;
                    command->setScene(this);
                    command->setNode(composite);
                    command->setFormer(d->current_node);
                    d->stack->push(command);

                } else if (!composite->flattened()) {

                    dtkComposerStackCommandLeaveGroup *command = new dtkComposerStackCommandLeaveGroup;
                    command->setScene(this);
                    command->setNode(composite);
                    d->stack->push(command);

                }
            }

        } else {

            if (event->modifiers() & Qt::ControlModifier) {

                ; // Do nothing so far

            } else {

                if (!composite->entered()) {

                    dtkComposerStackCommandEnterGroup *command = new dtkComposerStackCommandEnterGroup;
                    command->setScene(this);
                    command->setNode(composite);
                    command->setFormer(d->current_node);
                    d->stack->push(command);

                } else {

                    dtkComposerStackCommandLeaveGroup *command = new dtkComposerStackCommandLeaveGroup;
                    command->setScene(this);
                    command->setNode(composite);
                    d->stack->push(command);

                }
            }

        }
    }

}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Geometric queries
// /////////////////////////////////////////////////////////////////

dtkComposerSceneNode *dtkComposerScene::nodeAt(const QPointF& point) const
{
    QList<QGraphicsItem *> items = this->items(QRectF(point.x(), point.y(), 1, 1), Qt::IntersectsItemBoundingRect);

    foreach (QGraphicsItem *item, items)
        if (dtkComposerSceneNode *node = dynamic_cast<dtkComposerSceneNode *>(item))
            return node;

    return NULL;
}

dtkComposerSceneNode *dtkComposerScene::nodeAt(const QPointF& point, dtkComposerSceneNode *exclude) const
{
    QList<QGraphicsItem *> items = this->items(QRectF(point.x(), point.y(), 1, 1), Qt::IntersectsItemBoundingRect);

    foreach (QGraphicsItem *item, items) {
        if (dtkComposerSceneNode *node = dynamic_cast<dtkComposerSceneNode *>(item)) {

            if (node != d->current_node) {

                if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(node->parent()))
                    node = control;

                if (node != exclude && !(node->parent() == exclude))
                    return node;
            }
        }
    }

    return d->current_node;
}

dtkComposerScenePort *dtkComposerScene::portAt(const QPointF& point) const
{
    QList<QGraphicsItem *> items = this->items(QRectF(point.x(), point.y(), 1, 1), Qt::IntersectsItemBoundingRect);

    foreach (QGraphicsItem *item, items)
        if (dtkComposerScenePort *port = dynamic_cast<dtkComposerScenePort *>(item))
            return port;

    return NULL;
}

dtkComposerSceneNodeComposite *dtkComposerScene::parentAt(const QPointF& point) const
{
    dtkComposerSceneNode *node = this->nodeAt(point);

    if (!node)
        return d->current_node;

    if (dtkComposerSceneNodeLeaf *leaf = dynamic_cast<dtkComposerSceneNodeLeaf *>(node))
        return dynamic_cast<dtkComposerSceneNodeComposite *>(leaf->parent());

    if (dtkComposerSceneNodeComposite *composite = dynamic_cast<dtkComposerSceneNodeComposite *>(node)) {

        if (composite->flattened())
            return composite;

        if (composite->entered())
            return composite;

        if (!composite->flattened() && !composite->entered())
            return composite;
    }

    if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(node)) {

        dtkComposerSceneNodeComposite *block = control->blockAt(control->mapFromScene(point));

        if (!block)
            return dynamic_cast<dtkComposerSceneNodeComposite *>(control->parent());

        return block;
    }

    return NULL;
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Internal signal handling
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::onSelectionChanged(void)
{
    QList<QGraphicsItem *> selection = this->selectedItems();

    // if(!selection.count())
    //     emit selectionCleared();
    // else if(selection.count() > 1)
    //     emit selectionCleared();
    // else
    //     emit selected(selection.first());

    if (selection.count() == 1) {

        dtkComposerSceneNode *node = dynamic_cast<dtkComposerSceneNode *>(selection.first());

        if (node)
            emit selectedNode(node);

    } else {

        emit selectionCleared();

    }
}

// /////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark - Helper functions
// /////////////////////////////////////////////////////////////////

void dtkComposerScene::populateEdges(dtkComposerSceneNode *node)
{
    if (!node) {
        node = d->root_node;
        d->all_edges.clear();
    }

    d->all_edges << node->inputEdges();
    d->all_edges << node->outputEdges();

    if (dtkComposerSceneNodeComposite *composite = dynamic_cast<dtkComposerSceneNodeComposite *>(node))
        foreach (dtkComposerSceneNode *child, composite->nodes())
            this->populateEdges(child);

    if (dtkComposerSceneNodeControl *control = dynamic_cast<dtkComposerSceneNodeControl *>(node)) {
        d->all_edges << control->header()->inputEdges();
        d->all_edges << control->footer()->outputEdges();

        foreach (dtkComposerSceneNodeComposite *block, control->blocks())
            this->populateEdges(block);
    }

}


text:
package org.ebayopensource.turmeric.runtime.common.impl.internal.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This class represents processed global (as opposed to per-service instance) configuration, on either client or server side.
 * <p>
 * Note: Most ConfigHolder data is available in higher-level structures. Refer to ServiceDesc and related structures
 * as the primary configuration in the public API for SOA framework.
 * @author rmurphy
 *
 */
public class GlobalConfigHolder extends BaseConfigHolder {
	private Map<String, StorageProviderConfig> m_storageProviders = new HashMap<String, StorageProviderConfig>();
	private Integer m_monitorSnapshotInterval;
	private List<String> m_serviceLayers = Arrays.asList(new String[] {"COMMON", "INTERMEDIATE", "BUSINESS"});

	/** Configuration of the global thread pool shared amongst the SOA clients.
	 * Local binding communication is one of such use cases.  We may want to create
	 * a dedicated thread pool config object when the number of properties increases.
	 */
	// the maximum time that excess idle threads will wait for new tasks before terminating.
	private Long m_threadKeepAliveTimeInSec;

	/**
	 * Safe copy method.
	 * @return a new object with a safe copy of the original data
	 */
	public GlobalConfigHolder copy() {
		GlobalConfigHolder newCH = new GlobalConfigHolder();
		newCH.m_monitorSnapshotInterval = m_monitorSnapshotInterval;
		newCH.m_storageProviders = copyStorageProviders(m_storageProviders);
		newCH.m_serviceLayers = copyServiceLayers(m_serviceLayers);
		return newCH;
	}

	private Map<String, StorageProviderConfig> copyStorageProviders(Map<String, StorageProviderConfig> inProviders) {
		if (inProviders == null) {
			return null;
		}
		HashMap<String, StorageProviderConfig> outProviders = new HashMap<String, StorageProviderConfig>();
		for (StorageProviderConfig provider : inProviders.values()) {
			outProviders.put(provider.getName(), provider.copy());
		}
		return outProviders;
	}

	private List<String> copyServiceLayers(List<String> serviceLayers) {
		if (serviceLayers == null) {
			return null;
		}
		return new ArrayList<String>(serviceLayers);
	}

	/**
	 * @return the map of metric storage provider configurations, indexed by storage provider name
	 */
	public Map<String, StorageProviderConfig> getStorageProviders() {
		if (isReadOnly()) {
			return copyStorageProviders(m_storageProviders);
		}
		return m_storageProviders;
	}

	/**
	 * Set a map of metric storage provider configurations
	 * @param providers the m_storageProviders to set
	 */
	public void setStorageProviders(
			Map<String, StorageProviderConfig> providers) {
		checkReadOnly();
		m_storageProviders = providers;
	}

	/**
	 * @return the metric collection snapshot interval (interval at which all storage providers are notified of new values)
	 */
	public Integer getMonitorSnapshotInterval() {
		return m_monitorSnapshotInterval;
	}

	/**
	 * Set the the metric collection snapshot interval.
	 * @param snapshotInterval the snapshot interval to set
	 */
	public void setMonitorSnapshotInterval(Integer snapshotInterval) {
		checkReadOnly();
		m_monitorSnapshotInterval = snapshotInterval;
	}

	/**
	 * Set the service layer values
	 * @param serviceLayers the service layers to set
	 */
	public void setServiceLayerNames(List<String> serviceLayers) {
		checkReadOnly();
		m_serviceLayers = serviceLayers;
	}

	/**
	 * @return the list of service layers
	 */
	public List<String> getServiceLayerNames() {
		if (isReadOnly()) {
			return copyServiceLayers(m_serviceLayers);
		}
		return m_serviceLayers;
	}

	/**
	 * Returns the thread keep alive time in seconds
	 */
	public Long getThreadKeepAliveTimeInSec() {
		return m_threadKeepAliveTimeInSec;
	}

	/**
	 * Sets the thread keep alive time
	 * @param keepAliveTime a long that represents the thread keep alive time in seconds
	 */
	void setThreadKeepAliveTimeInSec(Long keepAliveTime) {
		checkReadOnly();
		m_threadKeepAliveTimeInSec = keepAliveTime;
	}

	/*
	 * Provide a user-readable description of the configuration into a StringBuffer.
	 * @param sb the StringBuffer into which to write the description
	 */
	public void dump(StringBuffer sb) {
		sb.append("========== Global Monitoring Config =========="+"\n");
		if (m_monitorSnapshotInterval != null) {
			sb.append("monitorSnapshotInterval="+m_monitorSnapshotInterval + "\n");
		}

		sb.append("========== Global local-binding thread pool config =========="+"\n");
		if (m_threadKeepAliveTimeInSec != null) {
			sb.append("threadKeepAliveTimeInSec="+m_threadKeepAliveTimeInSec + "\n");
		}

		List<String> storageProviders = new ArrayList<String>(m_storageProviders.keySet());
		Collections.sort(storageProviders);
		for (String name : storageProviders) {
			StorageProviderConfig provider = m_storageProviders.get(name);
			provider.dump(sb);
		}

		sb.append("\n========== Global Layer Config =========="+"\n");
		sb.append("layers=");
		if (m_serviceLayers != null) {
			for (String name : m_serviceLayers) {
				sb.append(name).append(" ");
			}
		}
		sb.append("\n");
	}
}

redpajama_set_name: RedPajamaGithub


text:
function die() {
  echo -e "\nError: $@\n" 1>&2
  print_usage
  exit 1
}

function print_usage() {
  echo "gobblin-aws.sh <start | stop>"
  echo "Where OPTION can be:"
  echo "  --jvmflags <string of jvm flags>               String containing any additional JVM flags to include"
  echo "  --jars <column-separated list of extra jars>   Column-separated list of extra jars to put on the CLASSPATH"
  echo "  --help                                         Display this help and exit"
}

function start() {
  for jarFile in `ls ${FWDIR_LIB}/*`
  do
    GOBBLIN_JARS=${GOBBLIN_JARS}:${jarFile}
  done

  export HADOOP_USER_CLASSPATH_FIRST=true

  CLASSPATH=${FWDIR_CONF}:${GOBBLIN_JARS}:${AWS_CONF_DIR}:${HADOOP_AWS_HOME}/lib
  if [ -n "$EXTRA_JARS" ]; then
    CLASSPATH=$CLASSPATH:"$EXTRA_JARS"
  fi

  LOG4J_PATH=file://${FWDIR_CONF}/log4j-aws.properties
  COMMAND="$JAVA_HOME/bin/java -cp $CLASSPATH $JVM_FLAGS org.apache.gobblin.aws.GobblinAWSClusterLauncher -D log4j.configuration=$LOG4J_PATH"

  echo "Running command:"
  echo "$COMMAND"
  nohup $COMMAND & echo $! > $PID
}

function stop() {
  if [ -f "$PID" ]; then
    if kill -0 $PID_VALUE > /dev/null 2>&1; then
      echo 'Stopping the Gobblin AWS application'
      kill $PID_VALUE
    else
      echo "Process $PID_VALUE is not running"
    fi
  else
    echo "No pid file found"
  fi
}

FWDIR="$(cd `dirname $0`/..; pwd)"
FWDIR_LIB=${FWDIR}/lib
FWDIR_CONF=${FWDIR}/conf/aws
FWDIR_BIN=${FWDIR}/bin

. ${FWDIR_BIN}/gobblin-env.sh

for i in "$@"
do
  case "$1" in
    start|stop)
      ACTION="$1"
      shift
      ;;
    --jvmflags)
      JVM_FLAGS="$1"
      shift
      ;;
    --jars)
      EXTRA_JARS="$1"
      shift
      ;;
    --help)
      print_usage
      exit 0
      ;;
    *)
      ;;
  esac
  shift
done

if [ -z "$JAVA_HOME" ]; then
  die "Environment variable JAVA_HOME not set!"
fi

# User defined JVM flags overrides $GOBBLIN_JVM_FLAGS (if any)
if [ -n "$JVM_FLAGS" ]; then
  JVM_FLAGS="-Xmx1g -Xms512m"
fi

PID="$FWDIR/.gobblin-aws-app-pid"

if [ -f "$PID" ]; then
  PID_VALUE=`cat $PID` > /dev/null 2>&1
else
  PID_VALUE=""
fi

case "$ACTION" in
  "start")
    start
    ;;
  "stop")
    stop
    ;;
  *)
    print_usage
    exit 1
    ;;
esac


text:
package com.intellij.psi.search.scope.packageSet;

import com.intellij.ide.IdeBundle;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;

import javax.swing.*;

@State(
  name="NamedScopeManager",
  storages= {
    @Storage(
      id="other",
      file = "$WORKSPACE_FILE$"
    )}
)
public class NamedScopeManager extends NamedScopesHolder {
  private static final Icon LOCAL_SCOPES = IconLoader.getIcon("/ide/localScope.png");

  public NamedScopeManager(final Project project) {
    super(project);
  }

  public static NamedScopeManager getInstance(Project project) {
    return ServiceManager.getService(project, NamedScopeManager.class);
  }

  public String getDisplayName() {
    return IdeBundle.message("local.scopes.node.text");
  }

  public Icon getIcon() {
    return LOCAL_SCOPES;
  }
}


text:
import {isPlainObject} from 'lodash/lang';

export default function (dispatch, componentProps) {
    const ret = {};
    let actions = componentProps.getFromActions;

    //noinspection EqualityComparisonWithCoercionJS
    if (actions != undefined) { // coercive inequality is used to check against null as well
        if (!isPlainObject(actions)) {
            throw new TypeError(`"getFromActions" must be an object, instead got ${typeof actions}`);
        }
        Object.keys(actions).forEach(function (action) {
            ret[action] = function (...args) {
                return dispatch(actions[action](...args));
            };
        });
    }
    return ret;
}


text:
using namespace mesos;

FrameworkInfoPtr toFrameworkInfo(char* user,
				 int userLen,
				 char* name,
				 int nameLen,
				 FrameworkIDPtr* frameworkID,
				 double* failoverTimeout,
				 bool* checkpoint,
				 char* role,
				 int roleLen,
				 char* hostname,
				 int hostLen,
				 char* principal,
				 int principalLen)
//	char* hostname,
// int hostLen)
{
  FrameworkInfoPtr info = new FrameworkInfo();
  info->set_user(user, userLen);
  info->set_name(name, nameLen);
  if (frameworkID != NULL)
    info->mutable_id()->MergeFrom(**frameworkID);
  if (failoverTimeout != NULL)
    info->set_failover_timeout(*failoverTimeout);
  if (checkpoint != NULL)
    {
      info->set_checkpoint(*checkpoint);
    }
  if (role != NULL)
    info->set_role(role, roleLen);

  if (hostname != NULL)
    info->set_hostname(hostname, hostLen);

  if (principal != NULL)
    info->set_principal(principal, principalLen);

  return info;
}

void fromFrameworkInfo(FrameworkInfoPtr info,
		       char** user,
		       int* userLen,
		       char** name,
		       int* nameLen,
		       FrameworkIDPtr* frameworkID,
		       bool* failoverSet,
		       double* failoverTimeout,
		       bool* checkpointSet,
		       bool* checkpoint,
		       char** role,
		       int* roleLen,
		       char** hostname,
		       int* hostLen,
		       char** principal,
		       int* principalLen)
{
  *failoverSet = false;
  *checkpointSet = false;

  std::string* u = info->mutable_user();
  *user = (char*) u->data();
  *userLen = u->size();
  std::string* n = info->mutable_name();
  *name = (char*) n->data();
  *nameLen = n->size();

  if (info->has_failover_timeout())
    {
      double timeout = info->failover_timeout();
      *failoverTimeout = timeout;
      *failoverSet = true;
    }
  if (info->has_checkpoint())
    {
      bool cp = info->checkpoint();
      *checkpoint = cp;
      *checkpointSet = true;
    }
  if (info->has_id())
    {
      *frameworkID = info->mutable_id();
    }
  if (info->has_role())
    {
      std::string* r = info->mutable_role();
      *role = (char*) r->data();
      *roleLen = r->size();
    }

  if (info->has_hostname())
    {
      std::string* h = info->mutable_hostname();
      *hostname = (char*) h->data();
      *hostLen = h->size();
    }

  if (info->has_principal())
    {
      std::string* p = info->mutable_principal();
      *principal = (char*) p->data();
      *principalLen = p->size();
    }
}

void destroyFrameworkInfo(FrameworkInfoPtr info)
{
  delete info;
}


text:
from django.db.models import Q
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend

class ModelBackend(ModelBackend):
    """
    Authenticate against the DJANGO login or user e-mail

    Use the login name, and password or userprofile.email and password
    """

    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(Q(username=username)| Q(email=username), is_active=True)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


text:
#include "config.h"
#include "DraggingMapManipulator.h"
#include "MapOperationInterface.h"
#include "MapManipulator.h"
#include "MapDrawingInterface.h"

//#include <valarray>
#include <cstdlib>

DraggingMapManipulator::DraggingMapManipulator(
   MapManipulator& mapManipulator,
   WFAPI::MapDrawingInterface* drawingInterface) :
   m_mapManipulator(mapManipulator),
   m_operationInterface(NULL),
   m_drawingInterface(drawingInterface),
   m_state(STATIC)
{
   DragState s = { MC2Coordinate(0, 0), MC2Point(0, 0) };
   m_dragState = s;
}

bool DraggingMapManipulator::attemptDrag(const WFAPI::ScreenPoint& point)
{
   if(!m_mapManipulator.okayToStart(MapManipulator::DRAGGING)) {
      return false;
   } else {
      m_mapManipulator.setIsStarting(MapManipulator::DRAGGING);
   }

   m_dragState.initialPoint = point;
   WFAPI::WGS84Coordinate tmpCoord;
   m_operationInterface->screenToWorld(tmpCoord, point);
   m_dragState.dragCoord = tmpCoord;
   setState(DRAGGING);

   return true;
}

void DraggingMapManipulator::endDrag(const WFAPI::ScreenPoint& point)
{
   setState(STATIC);

   // if( abs(point.getX() - m_dragState.initialPoint.getX()) > 3  ||
   //     abs(point.getY() - m_dragState.initialPoint.getY()) > 3 )
   // {
      m_operationInterface->setPoint(m_dragState.dragCoord, point);
      m_drawingInterface->requestRepaint();
   // }
}

void DraggingMapManipulator::updateDrag(const WFAPI::ScreenPoint& point)
{
   if( m_state == STATIC ) {
      return;
   }

   // if( abs(point.getX() - m_dragState.initialPoint.getX()) > 3  ||
   //     abs(point.getY() - m_dragState.initialPoint.getY()) > 3 )
   // {
      m_operationInterface->setPoint(m_dragState.dragCoord, point);
      m_drawingInterface->requestRepaint();
   // }
}

void DraggingMapManipulator::setState(State newState)
{
   if(newState == DRAGGING) {
      m_operationInterface->setMovementMode(true);
   } else {
      m_operationInterface->setMovementMode(false);
   }
   m_state = newState;
}

void DraggingMapManipulator::stopWorking()
{
   m_operationInterface->setMovementMode(false);
   m_state = STATIC;
}

bool DraggingMapManipulator::isWorking()
{
   return m_state != STATIC;
}

void
DraggingMapManipulator::setMapOperationInterface(
   WFAPI::MapOperationInterface* operationInterface)
{
   m_operationInterface = operationInterface;
}


text:
namespace v8 {
namespace internal {

class HeapObject;
class SnapshotByteSink;

class V8_EXPORT_PRIVATE ReadOnlySerializer : public RootsSerializer {
 public:
  ReadOnlySerializer(Isolate* isolate, Snapshot::SerializerFlags flags);
  ~ReadOnlySerializer() override;

  void SerializeReadOnlyRoots();

  // Completes the serialization of the read-only object cache and serializes
  // any deferred objects.
  void FinalizeSerialization();

  // If |obj| can be serialized in the read-only snapshot then add it to the
  // read-only object cache if not already present and emit a
  // ReadOnlyObjectCache bytecode into |sink|. Returns whether this was
  // successful.
  bool SerializeUsingReadOnlyObjectCache(SnapshotByteSink* sink,
                                         HeapObject obj);

 private:
  void SerializeObject(HeapObject o) override;
  bool MustBeDeferred(HeapObject object) override;

#ifdef DEBUG
  std::unordered_set<HeapObject, Object::Hasher> serialized_objects_;
#endif
  DISALLOW_COPY_AND_ASSIGN(ReadOnlySerializer);
};

}  // namespace internal
}  // namespace v8

#endif  // V8_SNAPSHOT_READ_ONLY_SERIALIZER_H_


text:
from accelerator.models import Organization
from impact.v1.helpers import (
    COULD_BE_STARTUP_CHECK,
    IS_STARTUP_CHECK,
    OrganizationHelper,
)
from impact.v1.views.base_detail_view import BaseDetailView

class OrganizationDetailView(BaseDetailView):
    view_name = "organization_detail"
    helper_class = OrganizationHelper

    def __init__(self, *args, **kwargs):
        self.organization = None
        super().__init__(*args, **kwargs)

    def options(self, request, pk):
        self.organization = Organization.objects.get(pk=pk)
        return super().options(request, pk)

    def description_check(self, check_name):
        if check_name in [IS_STARTUP_CHECK, COULD_BE_STARTUP_CHECK]:
            return OrganizationHelper(self.organization).is_startup
        return check_name


text:
package edu.upc.eetac.dsa.where.Client.Entity;

/**
 * Created by Carolina on 17/01/16.
 */
public class MediaType {

    public final static String WHERE_AUTH_TOKEN = "application/vnd.dsa.where.auth-token+json";
    public final static String WHERE_USER = "application/vnd.dsa.where.user+json";
    public final static String WHERE_RESTAURANT = "application/vnd.dsa.where.restaurant+json";
    public final static String WHERE_RESTAURANT_COLLECTION = "application/vnd.dsa.where.restaurant.collection+json";
    public final static String WHERE_COMMENT = "application/vnd.dsa.where.restaurant.comment+json";
    public final static String WHERE_COMMENT_COLLECTION = "application/vnd.dsa.where.restaurant.comment.collection+json";
    public final static String WHERE_ROOT = "application/vnd.dsa.where.root+json";
}


text:
#include "third_party/blink/renderer/core/paint/clip_rect.h"

#include "third_party/blink/renderer/core/layout/hit_test_location.h"
#include "third_party/blink/renderer/platform/geometry/layout_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/float_clip_rect.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"

namespace blink {

ClipRect::ClipRect()
    : rect_(PhysicalRect::InfiniteIntRect()),
      has_radius_(false),
      is_infinite_(true) {}

ClipRect::ClipRect(const FloatClipRect& rect) {
  SetRectInternal(rect);
}

void ClipRect::SetRect(const FloatClipRect& rect) {
  if (rect.IsInfinite() && IsInfinite())
    return;
  SetRectInternal(rect);
}

void ClipRect::SetRectInternal(const FloatClipRect& rect) {
  has_radius_ = rect.HasRadius();
  is_infinite_ = rect.IsInfinite();
  rect_ = PhysicalRect::FastAndLossyFromFloatRect(rect.Rect());
}

void ClipRect::SetRect(const PhysicalRect& rect) {
  rect_ = rect;
  has_radius_ = false;
  is_infinite_ = false;
}

void ClipRect::Intersect(const PhysicalRect& other) {
  if (IsInfinite()) {
    rect_ = other;
    is_infinite_ = false;
  } else {
    rect_.Intersect(other);
  }
}

void ClipRect::Intersect(const ClipRect& other) {
  if (other.IsInfinite())
    return;
  Intersect(other.Rect());
  if (other.HasRadius())
    has_radius_ = true;
}

bool ClipRect::Intersects(const HitTestLocation& hit_test_location) const {
  if (is_infinite_)
    return true;
  return hit_test_location.Intersects(rect_);
}

void ClipRect::Reset() {
  if (is_infinite_)
    return;
  has_radius_ = true;
  is_infinite_ = true;
  rect_ = PhysicalRect(LayoutRect::InfiniteIntRect());
}

String ClipRect::ToString() const {
  return rect_.ToString() + (has_radius_ ? " hasRadius" : " noRadius") +
         (is_infinite_ ? " isInfinite" : " notInfinite");
}

std::ostream& operator<<(std::ostream& ostream, const ClipRect& rect) {
  return ostream << rect.ToString();
}

}  // namespace blink


text:
<?php

class Teampagereply_model extends CI_Model
{
    function __construct(){
        parent::__construct();
    }

    function getTeamReplyList($teampage_num){
        return $this->db->query("SELECT * FROM teampage_reply WHERE teampage_num ='$teampage_num'")->result();
    }

    function insertReply($user_id, $teampage_num,$teampage_reply_content){
        $date = date('Y-m-d H:i:s');
        $sql = "INSERT INTO teampage_reply(user_id,teampage_num,teampage_reply_content,teampage_reply_date)";
        $sql.=" VALUES('$user_id','$teampage_num','$teampage_reply_content','$date')";

        $this->db->query($sql);
    }
    function modifyReply($teampage_reply_num,$teampage_reply_content){
        $date = date('Y-m-d H:i:s');
        $sql = "UPDATE teampage_reply SET teampage_reply_content='$teampage_reply_content', teampage_reply_date = '$date'";
        $sql.=" WHERE teampage_reply_num = '$teampage_reply_num'";

        $this->db->query($sql);
    }
    function deleteReply($teampage_reply_num){
        $sql = "DELETE FROM teampage_reply WHERE teampage_reply_num = '$teampage_reply_num'";

        $this->db->query($sql);
    }
}


text:
external help file: AutomatedLabWorker-help.xml
Module Name: AutomatedLabWorker
online version: https://automatedlab.org/en/latest/AutomatedLabWorker/en-us/Get-LWAzureVm
schema: 2.0.0
---

# Get-LWAzureVm

## SYNOPSIS
Get Azure VMs in the lab resource group

## SYNTAX

```
Get-LWAzureVm [[-ComputerName] <String[]>] [<CommonParameters>]
```

## DESCRIPTION
Get Azure VMs in the lab resource group

## EXAMPLES

### Example 1
```powershell
PS C:\> Get-LWAzureVm
```

Get Azure VMs in the lab resource group

## PARAMETERS

### -ComputerName
Computers to filter on

```yaml
Type: String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### None

## OUTPUTS

### System.Object
## NOTES

## RELATED LINKS


text:
package io.vertx.ext.web.handler.sockjs;

import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.WebTestBase;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

/**
 * SockJS protocol tests
 *
 * @author Tim Fox
 */
public class SockJSProtocolTest extends WebTestBase {

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

  @Override
  public void setUp() throws Exception {
    super.setUp();
    SockJSHandler.installTestApplications(router, vertx);
  }

  /*
  We run the actual Python SockJS protocol tests - these are taken from the 0.3.3 branch of the sockjs-protocol repository:
  https://github.com/sockjs/sockjs-protocol/tree/v0.3.3
   */
  @Test
  public void testProtocol() throws Exception {
    // does this system have python 2.x?
    Process p = Runtime.getRuntime().exec("python pythonversion.py", null, new File("src/test"));
    int res = p.waitFor();

    if (res == 0) {
      File dir = new File("src/test/sockjs-protocol");
      p = Runtime
          .getRuntime()
          .exec("python sockjs-protocol-0.3.3.py", new String[]{"SOCKJS_URL=http://localhost:8080"}, dir);

      try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
        String line;
        while ((line = input.readLine()) != null) {
          log.info(line);
        }
      }

      res = p.waitFor();

      // Make sure all tests pass
      assertEquals("Protocol tests failed", 0, res);
    } else {
      System.err.println("*** No Python runtime sockjs tests will be skiped!!!");
    }
  }
}


text:
import itk
import core.modules
from core.modules.vistrails_module import Module, ModuleError
from ITK import *
from Image import Image

class RegionOfInterestImageFilter(Module):
    my_namespace="Filter|Selection"

    def setStart(self, start):
        if start == 2:
            self.index = self.get_input("Input 2D Index").ind_
        else:
            self.index = self.get_input("Input 3D Index").ind_

        self.region_.SetIndex(self.index)

    def compute(self):
        im = self.get_input("Input Image")

        #check for input PixelType
        if self.has_input("Input PixelType"):
            inPixelType = self.get_input("Input PixelType")
        else:
            inPixelType = im.getPixelType()

        #check for output PixelType
        if self.has_input("Output PixelType"):
            outPixelType = self.get_input("Output PixelType")
        else:
            outPixelType = inPixelType

        #check for dimension
        if self.has_input("Input Dimension"):
            dim = self.get_input("Input Dimension")
        else:
            dim = im.getDim()

        if self.has_input("Output Dimension"):
            outDim = self.get_input("Output Dimension")
        else:
            outDim = dim

        #set up filter
        inImgType = itk.Image[inPixelType._type, dim]
        outImgType = itk.Image[outPixelType._type, outDim]

        self.filter_ = itk.RegionOfInterestImageFilter[inImgType, outImgType].New()

        #TODO this is not correct, needs fixing
        if self.has_input("Input Region"):
            self.region_ = self.get_input("Input Region").region_
        else:
            self.region_ = itk.ImageRegion[indim]()
            self.setStart(indim)
            self.region_.SetSize(self.get_input("Region Size").size_)

        self.filter_.SetRegionOfInterest(self.region_)
        self.filter_.SetInput(im.getImg())
        self.filter_.Update()

        #setup output image
        outIm = Image()
        outIm.setImg(self.filter_.GetOutput())
        outIm.setPixelType(outPixelType)
        outIm.setDim(outDim)

        self.set_output("Output Image", outIm)
        self.set_output("Output PixelType", outPixelType)
        self.set_output("Output Dimension", outDim)
        self.set_output("Filter", self)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, name="Region of Interest Image Filter", namespace=cls.my_namespace)

        reg.add_input_port(cls, "Input Image", (Image, 'Input Image'))
        reg.add_input_port(cls, "Input Dimension", (basic.Integer, 'Dimension'),True)
        reg.add_input_port(cls, "Output Dimension", (basic.Integer, 'Dimension'),True)
        reg.add_input_port(cls, "Input PixelType", (PixelType, 'Input PixelType'),True)
        reg.add_input_port(cls, "Output PixelType", (PixelType, 'Output PixelType'),True)
        reg.add_input_port(cls, "Input Region", (Region, 'Input Region'))
        reg.add_input_port(cls, "Region Size", (Size, 'Region Size'))

        reg.add_output_port(cls, "Output Image", (Image, 'Output Image'))
        reg.add_output_port(cls, "Output PixelType", (PixelType, 'Output PixelType'),True)
        reg.add_output_port(cls, "Output Dimension", (basic.Integer, 'Dimension'),True)

class CastImageFilter(Module):
    my_namespace="Filter|Selection"
    def compute(self):
        im = self.get_input("Input Image")

        #check for input PixelType
        if self.has_input("Input PixelType"):
            inPixelType = self.get_input("Input PixelType")
        else:
            inPixelType = im.getPixelType()

        #check for output PixelType
        if self.has_input("Output PixelType"):
            outPixelType = self.get_input("Output PixelType")
        else:
            outPixelType = inPixelType

        #check for in dimension
        if self.has_input("Input Dimension"):
            dim = self.get_input("Input Dimension")
        else:
            dim = im.getDim()

        #check for out dimension
        if self.has_input("Output Dimension"):
            outDim = self.get_input("Output Dimension")
        else:
            outDim = dim

        #set up filter
        inImgType = itk.Image[inPixelType._type, dim]
        outImgType = itk.Image[outPixelType._type, outDim]

        self.filter_ = itk.CastImageFilter[inImgType, outImgType].New(im.getImg())
        self.filter_.Update()

        #setup output image
        outIm = Image()
        outIm.setImg(self.filter_.GetOutput())
        outIm.setPixelType(outPixelType)
        outIm.setDim(outDim)

        self.set_output("Output Image", outIm)
        self.set_output("Output PixelType", outPixelType)
        self.set_output("Output Dimension", outDim)
        self.set_output("Filter", self)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, name="Cast Image Filter", namespace=cls.my_namespace)

        reg.add_input_port(cls, "Input Dimension", (basic.Integer, 'Input Dimension'),True)
        reg.add_input_port(cls, "Output Dimension", (basic.Integer, 'Output Dimension'))
        reg.add_input_port(cls, "Input PixelType", (PixelType, 'Input PixelType'),True)
        reg.add_input_port(cls, "Output PixelType", (PixelType, 'Output PixelType'))
        reg.add_input_port(cls, "Input Image", (Image, 'Input Image'))

        reg.add_output_port(cls, "Output Image", (Image, 'Output Image'))
        reg.add_output_port(cls, "Output PixelType", (PixelType, 'Output PixelType'),True)
        reg.add_output_port(cls, "Filter", (Filter, 'Filter'),True)
        reg.add_output_port(cls, "Output Dimension", (basic.Integer, 'Output Dimension'),True)

class ExtractImageFilter(Module):
    my_namespace="Filter|Selection"
    def compute(self):
        #TODO should this be Input Volume?
        im = self.get_input("Input Volume")
        #check for input PixelType
        if self.has_input("Input PixelType"):
            inPixelType = self.get_input("Input PixelType")
        else:
            inPixelType = im.getPixelType()

        #set outPixelType
        outPixelType = inPixelType

        #check for dimension
        if self.has_input("Dimension"):
            dim = self.get_input("Dimension")
        else:
            dim = im.getDim()

        #check for out dimension
        if self.has_input("Output Dimension"):
            outDim = self.get_input("Output Dimension")
        else:
            outDim = im.getDim()

        #set up filter
        inImgType = itk.Image[inPixelType._type, dim]
        outImgType = itk.Image[outPixelType._type, outDim]

        self.filter_ = itk.ExtractImageFilter[inImgType,outImgType].New(im.getImg())

        region = self.get_input("Extraction Region")
        self.filter_.SetExtractionRegion(region.region_)
        self.filter_.Update()

        #setup output image
        outIm = Image()
        outIm.setImg(self.filter_.GetOutput())
        outIm.setPixelType(outPixelType)
        outIm.setDim(outDim)

        self.set_output("Output Image", outIm)
        self.set_output("Output PixelType", outPixelType)
        self.set_output("Dimension", outDim)

    @classmethod
    def register(cls, reg, basic):
        reg.add_module(cls, name="Extract Image Filter", namespace=cls.my_namespace)

        reg.add_input_port(cls, "Input Volume", (Image, 'Input Image'))
        reg.add_input_port(cls, "Input Dimension", (basic.Integer, 'Input Dimension'),True)
        reg.add_input_port(cls, "Output Dimension", (basic.Integer, 'Output Dimension'),True)
        reg.add_input_port(cls, "Input PixelType", (PixelType, 'Input PixelType'),True)
        reg.add_input_port(cls, "Extraction Region", (Region, 'Extraction Region'))

        reg.add_output_port(cls, "Output Image", (Image, 'Output Image'))
        reg.add_output_port(cls, "Output PixelType", (PixelType, 'Output PixelType'),True)
        reg.add_output_port(cls, "Dimension", (basic.Integer, 'Dimension'),True)


text:
extern crate chip8;
extern crate sdl2;

use sdl2::pixels::PixelFormatEnum;
use sdl2::rect::Rect;
use sdl2::Sdl;
use std::time::{Duration, Instant};
use std::thread::sleep;

/// Represents a display.  In this case, it represents an SDL window.
pub struct Display<'a> {
    width: u32,
    height: u32,
    renderer: sdl2::render::Renderer<'a>,
    texture: sdl2::render::Texture,
    frame_duration: Duration,
    frame_last: Instant,
}

impl<'a> Display<'a> {
    /// Constructs a new SDL window with the given SDL context,
    /// the given title, the given width (in pixels, the given height
    /// (in pixels), and the given frame duration.
    ///
    /// The frame duration is used to set how long each frame should last.
    /// Higher values lead to slower emulator performance but also help
    /// smooth the framerate.
    pub fn new(context: &Sdl,
               title: &str,
               width: u32,
               height: u32,
               duration: Duration) -> Self {
        let video_subsystem = context.video().unwrap();
        let window = video_subsystem.window(title, width, height)
            .position_centered()
            .opengl()
            .build()
            .unwrap();
        let renderer = window.renderer().build().unwrap();
        let texture = renderer.create_texture_streaming(
            PixelFormatEnum::RGB24, 64, 32).unwrap();

        Display {
            width: width,
            height: height,
            renderer: renderer,
            texture: texture,
            frame_duration: duration,
            frame_last: Instant::now(),
        }
    }

    /// The window draws the give bitmap image on the Display's frame duration.
    ///
    /// If there is time left over, that time is spent sleeping.
    pub fn draw_frame(&mut self, bitmap: &[u8; chip8::NPIXELS]) {
        // Keep timing okay
        let prev_duration = Instant::now().duration_since(self.frame_last);
        debug!("Last frame duration: {:?}", prev_duration);
        if prev_duration < self.frame_duration {
            let diff = self.frame_duration - prev_duration;
            debug!("Sleeping for: {:?}", diff);
            sleep(diff);
        }
        self.frame_last = Instant::now();

        self.texture.with_lock(None, |buffer: &mut [u8], pitch: usize| {
            for y in 0..32 {
                for x in 0..64 {
                    let offset = y*pitch + x*3;
                    let value = if 0 != bitmap[y * 64 + x] { 255 } else { 0 };
                    buffer[offset + 0] = value as u8;
                    buffer[offset + 1] = value as u8;
                    buffer[offset + 2] = 0;
                }
            }

        }).unwrap();
        self.renderer.clear();
        self.renderer.copy(&self.texture,
                           None,
                           Some(Rect::new(0, 0, self.width, self.height)));
        self.renderer.present();
    }
}