text:
//
//  UserController.m
//  MedicineNurse
//
//  Created by lanou3g on 15/10/14.
//  Copyright © 2015年 Adar-Li. All rights reserved.
//

#import "UserController.h"
#import "AVUser.h"
#import "HomeController.h"
#import "UserManager.h"

@interface UserController ()
@property (weak, nonatomic) IBOutlet UITextField *textField4Name;
@property (weak, nonatomic) IBOutlet UITextField *textField4Password;

@end

@implementation UserController

- (void)viewWillDisappear:(BOOL)animated{

    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewWillAppear:(BOOL)animated{

        self.tabBarController.tabBar.hidden = YES;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        //去sb 中找到这个控制器
        UserController * user = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"user"];
        self = user;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)btn4Login:(id)sender {
    [AVUser logInWithUsernameInBackground:_textField4Name.text password:_textField4Password.text block:^(AVUser *user, NSError *error) {
        if (user != nil) {

            [[UserManager shareUserManager]setUserName:_textField4Name.text];
            [[UserManager shareUserManager]setUserPassWorld:_textField4Password.text];
            //发出通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginAction" object:nil userInfo:@{@"name":_textField4Name.text}];

            UIAlertController*alert = [UIAlertController alertControllerWithTitle:@"登陆成功" message:@"尽情享受吧" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:nil];
            UIAlertAction *oneAc = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

            }];

            UIAlertAction *twoAc = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self dismissViewControllerAnimated:YES completion:nil];
            }];

            [alert addAction:oneAc];
            [alert addAction:twoAc];
//            [self dismissViewControllerAnimated:YES completion:nil];

        } else {
            UIAlertController*alert = [UIAlertController alertControllerWithTitle:@"登陆失败" message:@"账户或者密码不正确" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *oneAc = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

            }];

            UIAlertAction *twoAc = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            }];

            [alert addAction:oneAc];
            [alert addAction:twoAc];

            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}
- (IBAction)btn4Regis:(id)sender {

}
- (IBAction)btn4Find:(id)sender {
}
- (IBAction)btn4Back:(id)sender {
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self dismissViewControllerAnimated:YES completion:nil];
}
//撤销键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
#include "player.h"
#include "playlist.h"
#include "model.h"
#include "log.h"
#include "widgets.h"
#include "config.h"
#include "shortcutdialog.h"
#include <QDebug>
#include "resizer.h"
#include "skinselectiondialog.h"

enum SkinSelectionMechanism
{
    DirectlySelectFolder,
    SkinFolderListView
};

static inline const char *activateMember(QAbstractButton *)
{
    return "1animateClick()";
}

static inline const char *activateMember(QAction *)
{
    return "1trigger()";
}

static inline QWidget *widget(QAction *a)
{
    return a->parentWidget();
}

static inline QWidget *widget(QWidget *a)
{
    return a;
}

// could use stringrefs
static inline QString unquote(QString string)
{
    static QRegExp rx("^'(.*[^\\\\])'$");
    if (rx.exactMatch(string))
        string = rx.cap(1);

    string.replace("\\'", "'");
    return string;
}

Q_DECLARE_METATYPE(QList<QShortcut*>);
inline uint qHash(const QKeySequence &seq) { return qHash(seq.toString()); }
template <class T> static void setShortcuts(T *t)
{
    Q_ASSERT(!t->objectName().isEmpty());
    const QKeySequence defaultShortcut = qVariantValue<QKeySequence>(t->property("defaultShortcut"));
    qDeleteAll(qFindChildren<QShortcut*>(t));
    const QString value = Config::value<QString>(QString("Shortcuts/%1").arg(t->objectName()).simplified());
    QSet<QKeySequence> shortcuts;
    if (!value.isEmpty()) {
        const QStringList list = value.split(' ', QString::SkipEmptyParts);
        for (int i=0; i<list.size(); ++i) {
            const QString str = ::unquote(list.at(i));
            QKeySequence key;
            if (str == "[default]") {
                key = defaultShortcut;
                if (defaultShortcut.isEmpty()) {
                    Log::log(0) << t->objectName() << "doesn't have a default shortcut";
                    continue;
                }
            } else {
                key = QKeySequence(str);
                if (key.isEmpty()) {
                    Log::log(0) << "Can't decode key" << str << "for" << t->objectName();
                    continue;
                }
            }
            shortcuts.insert(key);
        }
    } else if (!defaultShortcut.isEmpty()) {
        shortcuts.insert(defaultShortcut);
    }

    foreach(const QKeySequence &key, shortcuts) {
        Q_ASSERT(!key.isEmpty());
        QShortcut *shortcut = new QShortcut(key, ::widget(t));
        QObject::connect(shortcut, SIGNAL(activated()), t, ::activateMember(t));
        QList<QShortcut*> shortcuts = qVariantValue<QList<QShortcut*> >(t->property("shortcuts"));
        t->setProperty("shortcuts", qVariantFromValue<QList<QShortcut*> >(shortcuts));
    }
} // use this for both buttons and actions

Player::Player(QDBusInterface *interface, QWidget *parent)
    : QWidget(parent)
{
    d.moving = false;
    if (Config::isEnabled("resizer", true)) {
        d.resizer = new WidgetResizer(this);
        d.resizer->setAreas(AbstractResizer<QPoint, QSize, QRect>::AllAreas & ~AbstractResizer<QPoint, QSize, QRect>::Center);
        d.resizer->setPaintingEnabled(Config::isEnabled("resizePainting", false));
    } else {
        d.resizer = 0;
    }
#ifdef QT_DEBUG
    d.overlay = 0;
#endif

    setContextMenuPolicy(Qt::ActionsContextMenu);
    d.channelMode = Private::Stereo;
    if (!Config::isEnabled("ignorelastgeometry", false)) {
        const QByteArray g = Config::value<QByteArray>("geometry");
        if (!g.isEmpty()) {
            restoreGeometry(g);
            if (!QApplication::desktop()->availableGeometry(this).intersects(geometry())) {
                QRect r(QPoint(), sizeHint());
                r.moveCenter(QApplication::desktop()->availableGeometry(this).center());
                setGeometry(r);
            }
        }
    } else {
        QRect r(QPoint(), sizeHint());
        r.moveCenter(QApplication::desktop()->availableGeometry(this).center());
        setGeometry(r);
    }

    d.interface = interface;
    if (d.interface) {
        d.model = new TrackModel(d.interface, this);
        d.playlist = new PlaylistWidget(d.interface, d.model);
        d.interface->connection().connect(SERVICE_NAME, "/", QString(), "wakeUp", this, SLOT(wakeUp()));
    }

    if (!Config::isEnabled("titlebar", false)) {
        Qt::WindowFlags flags = windowFlags() | Qt::FramelessWindowHint;
        if (Config::isEnabled("bypassx11", false))
            flags |= Qt::X11BypassWindowManagerHint;
        setWindowFlags(flags);
    }
    setAttribute(Qt::WA_OpaquePaintEvent);
    setAttribute(Qt::WA_NoSystemBackground);
    setFocus();
//    const char *separator = "";
    struct {
        const char *name;
        QObject *receiver;
        const char *member;
        const QRect rect;
        const bool checkable;
        const QKeySequence shortcut;
    } const buttonInfo[] = {
        // prev, pause, pause, stop, next
        { QT_TRANSLATE_NOOP("Player", "Previous"), d.interface, SLOT(prev()),
          QRect(16, 88, 23, 18), false, Qt::Key_Z },
        { QT_TRANSLATE_NOOP("Player", "Play"), d.interface, SLOT(play()),
          QRect(39, 88, 23, 18), false, Qt::Key_X },
        { QT_TRANSLATE_NOOP("Player", "Pause"), d.interface, SLOT(pause()),
          QRect(62, 88, 23, 18), false, Qt::Key_C },
        { QT_TRANSLATE_NOOP("Player", "Stop"), d.interface, SLOT(stop()),
          QRect(85, 88, 23, 18), false, Qt::Key_V },
        { QT_TRANSLATE_NOOP("Player", "Next"), d.interface, SLOT(next()),
          QRect(108, 88, 22, 18), false, Qt::Key_B },
        { QT_TRANSLATE_NOOP("Player", "Open"), this, SLOT(open()),
          QRect(136, 89, 22, 16), false, QKeySequence::Open },
        { QT_TRANSLATE_NOOP("Player", "Shuffle"), d.interface, SLOT(setShuffle(bool)),
          QRect(164, 89, 46, 15), true, Qt::ControlModifier + Qt::Key_Z }, // is there a shortcut for this one?
        { QT_TRANSLATE_NOOP("Player", "Repeat"), d.interface, SLOT(setRepeat(bool)),
          QRect(210, 89, 28, 15), true, Qt::Key_R }, // is there a shortcut for this one?
        { QT_TRANSLATE_NOOP("Player", "Equalizer"), this, SLOT(setEqualizerVisible(bool)),
          QRect(219, 58, 23, 12), true, Qt::Key_E },
        { QT_TRANSLATE_NOOP("Player", "Playlist"), d.playlist, SLOT(setVisible(bool)),
          QRect(242, 58, 23, 12), true, Qt::ControlModifier + Qt::Key_P },
        { 0, 0, 0, QRect(), false, QKeySequence() },
    };

#ifdef QT_DEBUG
    const bool debugButtons = Config::isEnabled("debugButtons");
#endif
    for (int i=0; buttonInfo[i].member; ++i) {
        Q_ASSERT(i < ButtonCount);
        d.buttons[i] = new Button(this);
        d.buttons[i]->setObjectName(QString::fromLatin1(buttonInfo[i].name));
        const QString translated = QApplication::translate("Playlist", buttonInfo[i].name);
        d.buttons[i]->setToolTip(translated);
        d.buttons[i]->setText(translated); // used by shortcut editor
        d.buttons[i]->setProperty("defaultGeometry", buttonInfo[i].rect);
        d.buttons[i]->setProperty("defaultShortcut", buttonInfo[i].shortcut);
        d.buttons[i]->setGeometry(buttonInfo[i].rect);
        d.buttons[i]->setCheckable(buttonInfo[i].checkable);
        connect(d.buttons[i], buttonInfo[i].checkable
                ? SIGNAL(toggled(bool))
                : SIGNAL(clicked()), buttonInfo[i].receiver, buttonInfo[i].member);
#ifdef QT_DEBUG
        if (debugButtons)
            connect(d.buttons[i], SIGNAL(clicked()), this, SLOT(debugButton()));
#endif
        // ### icons?
        if (buttonInfo[i].checkable && Config::isEnabled(buttonInfo[i].name)) {
            QTimer::singleShot(0, d.buttons[i], SLOT(toggle()));
        }
    }

    enum CheckStatus {
        None = 0x0,
        Checkable = 0x1,
        Checked = 0x2
    };

    const char *separator = "";
    struct {
        const char *name;
        const char *member;
        const uint checkstatus;
        const QKeySequence shortcut;
    } const actionInfo[] = {
        { QT_TRANSLATE_NOOP("Player", "Quit"), SLOT(close()), None, QKeySequence::Close },
        { QT_TRANSLATE_NOOP("Player", "Edit shortcuts"), SLOT(editShortcuts()), None, QKeySequence() },
        { QT_TRANSLATE_NOOP("Player", "Restore default size"), SLOT(restoreDefaultSize()), None, QKeySequence() },
        { QT_TRANSLATE_NOOP("Player", "OpenSkin"), SLOT(openSkin()), None, QKeySequence(Qt::ControlModifier + Qt::Key_S) },
#ifdef QT_DEBUG
        { QT_TRANSLATE_NOOP("Player", "Toggle debug geometry"), SLOT(toggleDebugGeometry(bool)),
          (Config::isEnabled("debuggeometry") ? Checked|Checkable : Checkable),
          QKeySequence(Qt::AltModifier + Qt::Key_D) },
        { QT_TRANSLATE_NOOP("Player", "Toggle overlay"), SLOT(toggleOverlay(bool)),
          Checkable, QKeySequence(Qt::AltModifier | Qt::Key_O) },
#endif
        { 0, 0, QKeySequence(), false }
    };
    for (int i=0; actionInfo[i].member; ++i) {
        const QKeySequence shortcut = actionInfo[i].shortcut;
        QAction *action = new QAction(QCoreApplication::translate("Player", actionInfo[i].name), this);
        action->setObjectName(QString::fromLatin1(actionInfo[i].name));
        action->setCheckable(actionInfo[i].checkstatus & Checkable);
        action->setChecked(actionInfo[i].checkstatus & Checked);
        if (actionInfo[i].member == separator) {
            action->setSeparator(true);
        } else {
            action->setProperty("defaultShortcut", shortcut);
            connect(action, SIGNAL(triggered(bool)), this, actionInfo[i].member);
        }
        addAction(action);
    }

    d.posBarSlider = new Slider(Qt::Horizontal, this);
    d.posBarSlider->setGeometry(14, 72, 253, 10);
    d.posBarSlider->setProperty("defaultGeometry", d.posBarSlider->geometry());
    d.posBarSlider->setRange(0, 600);
    d.posBarSlider->setStyle(d.posBarStyle = new SliderStyle(this));

//    mainwin_volume = create_hslider(&mainwin_wlist, mainwin_bg, mainwin_gc, 107, 57, 68, 13, 15, 422, 0, 422, 14, 11, 15, 0, 0, 51, mainwin_volume_framecb, mainwin_volume_motioncb, mainwin_volume_releasecb, SKIN_VOLUME);

    d.volumeSlider = new Slider(Qt::Horizontal, this);
    d.volumeSlider->setGeometry(107, 57, 68, 13);
    d.volumeSlider->setRange(0, 100);
//    d.volumeSlider->setStyle(d.volumeStyle = new SliderStyle(this));
    reloadSettings();
    if (!setSkin(Config::value<QString>("skin", QString(":/skins/dullSod")))) {
        const bool ret = setSkin(":/skins/dullSod");
        Q_ASSERT(ret);
        Q_UNUSED(ret);
    }
    connect(d.playlist, SIGNAL(visibilityChanged(bool)), d.buttons[Playlist], SLOT(setChecked(bool)));
}

Player::~Player()
{
    delete d.resizer;
    delete d.posBarStyle;
}

void Player::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    p.setTransform(qVariantValue<QTransform>(property("transform")));
    d.main.render(&p);
//     d.numbers.render(&p, QPoint(10, 10), "143245");
//     d.text.render(&p, QPoint(150, 25), "THIS IS COOL");
}

void Player::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton) {
        d.dragOffset = e->pos();
        d.moving = true;
    }
}

void Player::mouseMoveEvent(QMouseEvent *e)
{
    if (e->buttons() == Qt::LeftButton && d.moving) {
        move(e->globalPos() - d.dragOffset);
    }
}

void Player::mouseReleaseEvent(QMouseEvent *)
{
    d.moving = false;
}

static QPixmap findPixmap(const QString &dir, const QStringList &list, const char *buttonName,
                          bool warn = true)
{
    static const QList<QByteArray> formats = QImageReader::supportedImageFormats();
    QRegExp rx(QString("%1\\.(.*)$").arg(buttonName));
    rx.setCaseSensitivity(Qt::CaseInsensitive);
    const int index = list.indexOf(rx);
    if (index != -1 && formats.contains(rx.cap(1).toLower().toLocal8Bit())) { // toLatin1()?
        QPixmap pix(QString("%1/%2").arg(dir).arg(list.at(index)));
        if (pix.isNull() && warn) {
            qWarning("Can't load image '%s'", qPrintable(QString("%1/%2").arg(dir).arg(list.at(index))));
        }
        return pix;
    } else if (warn) {
        qWarning("Can't find image '%s'", qPrintable(QString("%1/%2.*").arg(dir).arg(buttonName)));
    }
    return QPixmap();
}

static inline bool verifySkin(const QString &path, bool warn)
{
    const QDir dir(path);
    if (!dir.exists()) {
        if (warn)
            qWarning("%s doesnt seem't seem to exist", qPrintable(path));
        return false;
    }

    const QStringList files = dir.entryList();
    static const char *fileNames[] = {
        "cbuttons", "eqmain", "monoster", /*"nums_ex",*/ "pledit",
        "shufrep", "titlebar", "eq_ex", "main", "numbers",
        "playpaus", "posbar", "text", "volume", 0
    };
    for (int i=0; fileNames[i]; ++i) {
        if (::findPixmap(dir.absolutePath(), files, fileNames[i], warn).isNull()) {
            return false;
        }
    }
    return true;
}

bool Player::verifySkin(const QString &path)
{
    return ::verifySkin(path, false);
}

bool Player::setSkin(const QString &path)
{
    if (!::verifySkin(path, true)) {
        qDebug() << "Passed skin path is not acceptable";
        return false;
    }

    QDir dir(path);
    Q_ASSERT(dir.exists());
    const QStringList files = dir.entryList();
    struct {
        const char *name;
        const QRect sourceRect;
        const QRect targetRect;
        RenderObject *renderObject;
    } const buttons[] = {
        { "main", QRect(), QRect(), &d.main },

        { "cbuttons", QRect(0, 0, 23, 18), QRect(), &d.buttons[Previous]->pixmaps[Button::Normal] }, // Previous
        { "cbuttons", QRect(0, 18, 23, 18), QRect(), &d.buttons[Previous]->pixmaps[Button::Pressed] },

        { "cbuttons", QRect(23, 0, 23, 18), QRect(), &d.buttons[Play]->pixmaps[Button::Normal] }, // Play
        { "cbuttons", QRect(23, 18, 23, 18), QRect(), &d.buttons[Play]->pixmaps[Button::Pressed] },

        { "cbuttons", QRect(46, 0, 23, 18), QRect(), &d.buttons[Pause]->pixmaps[Button::Normal] }, // Pause
        { "cbuttons", QRect(46, 18, 23, 18), QRect(), &d.buttons[Pause]->pixmaps[Button::Pressed] },

        { "cbuttons", QRect(69, 0, 23, 18), QRect(), &d.buttons[Stop]->pixmaps[Button::Normal] }, // Stop
        { "cbuttons", QRect(69, 18, 23, 18), QRect(), &d.buttons[Stop]->pixmaps[Button::Pressed] },

        { "cbuttons", QRect(92, 0, 22, 18), QRect(), &d.buttons[Next]->pixmaps[Button::Normal] }, // Next
        { "cbuttons", QRect(92, 18, 22, 18), QRect(), &d.buttons[Next]->pixmaps[Button::Pressed] },

        { "cbuttons", QRect(114, 0, 22, 16), QRect(), &d.buttons[Open]->pixmaps[Button::Normal] }, // Open
        { "cbuttons", QRect(114, 16, 22, 16), QRect(), &d.buttons[Open]->pixmaps[Button::Pressed] },

        { "shufrep", QRect(28, 0, 46, 15), QRect(), &d.buttons[Shuffle]->pixmaps[Button::Normal] }, // Shuffle
        { "shufrep", QRect(28, 15, 46, 15), QRect(), &d.buttons[Shuffle]->pixmaps[Button::Pressed] },
        { "shufrep", QRect(28, 30, 46, 15), QRect(), &d.buttons[Shuffle]->pixmaps[Button::Checked] },
        { "shufrep", QRect(28, 45, 46, 15), QRect(), &d.buttons[Shuffle]->pixmaps[Button::Checked|Button::Pressed] },

        { "shufrep", QRect(0, 0, 28, 15), QRect(), &d.buttons[Repeat]->pixmaps[Button::Normal] }, // Repeat
        { "shufrep", QRect(0, 15, 28, 15), QRect(), &d.buttons[Repeat]->pixmaps[Button::Pressed] },
        { "shufrep", QRect(0, 30, 28, 15), QRect(), &d.buttons[Repeat]->pixmaps[Button::Checked] },
        { "shufrep", QRect(0, 45, 28, 15), QRect(), &d.buttons[Repeat]->pixmaps[Button::Checked|Button::Pressed] },

        { "shufrep", QRect(0, 61, 23, 12), QRect(), &d.buttons[Equalizer]->pixmaps[Button::Normal] }, // EQ
        { "shufrep", QRect(0, 73, 23, 12), QRect(), &d.buttons[Equalizer]->pixmaps[Button::Checked] },

        { "shufrep", QRect(23, 61, 23, 12), QRect(), &d.buttons[Playlist]->pixmaps[Button::Normal] }, // Playlist
        { "shufrep", QRect(23, 73, 23, 12), QRect(), &d.buttons[Playlist]->pixmaps[Button::Checked] },

        { 0, QRect(), QRect(), 0 }
    };

    QHash<const char *, QPixmap> pixmaps;
    const bool dumpPixmaps = Config::isEnabled("dump-pixmaps");
    const bool noSubPixmaps = !Config::isEnabled("subpixmaps", true);
    for (int i=0; buttons[i].name; ++i) {
        QPixmap pixmap;
        if (!pixmaps.contains(buttons[i].name)) {
            pixmap = ::findPixmap(dir.absolutePath(), files, buttons[i].name, false);
            pixmaps[buttons[i].name] = pixmap;
        } else {
            pixmap = pixmaps.value(buttons[i].name);
        }
        Q_ASSERT(buttons[i].renderObject);
        Q_ASSERT(!pixmap.isNull());
        if (noSubPixmaps) {
            pixmap = pixmap.copy(buttons[i].sourceRect);
        } else {
            buttons[i].renderObject->sourceRect = buttons[i].sourceRect;
        }
        buttons[i].renderObject->pixmap = pixmap;

        buttons[i].renderObject->targetRect = buttons[i].targetRect;
        Q_ASSERT(buttons[i].targetRect.isNull() || buttons[i].targetRect.size() == buttons[i].sourceRect.size());
        if (dumpPixmaps) {
            pixmap.copy(buttons[i].sourceRect).save(QString("%1_%2.png").arg(i).arg(buttons[i].name), "PNG");
        }

    }

    struct {
        const char *name;
        const char *letters;
        const QSize letterSize; // do I need offset
        TextObject *textObject;
    } const textObjects[] = {
        { "numbers", "0123456789", QSize(9, 13), &d.numbers },
//        { "nums_ex", "0123456789 -", QSize(9, 13), &d.numbers }, // doesn't seem to exist everywhere. Not in YummiYogurt
        // ### is this @ larger than other stuff?
        // could make the last one on each line larger or something?
        // maybe a nasty hack like if char == '@'
        // what is this .. character and the one after the dollar?
        { "text",
          "ABCDEFGHIJKLMNOPQRSTUVWXYZ\"@\n"
          "0123456789._:()-'!_+\\/[]^&%,=$#\n"
          "...?. ",
          QSize(5, 9), &d.text },
        { 0, 0, QSize(), 0 }
    };

    for (int i=0; textObjects[i].name; ++i) {
        TextObject *textObject = textObjects[i].textObject;
        textObject->pixmap = ::findPixmap(dir.absolutePath(), files, textObjects[i].name);
        Q_ASSERT(!textObject->pixmap.isNull());
        QRect sourceRect(QPoint(0, 0), textObjects[i].letterSize);
        for (int j=0; textObjects[i].letters[j]; ++j) {
            if (textObjects[i].letters[j] == '\n') {
                sourceRect.moveTopLeft(QPoint(0, sourceRect.y() + sourceRect.height()));
            } else {
                textObject->sourceRects[QLatin1Char(textObjects[i].letters[j])] = sourceRect;
//                 qDebug() << "setting" << textObjects[i].letters[j]
//                          << "to" << sourceRect.size();
                sourceRect.moveTopLeft(QPoint(sourceRect.x() + sourceRect.width(), sourceRect.y()));
            }
        }
    }
    const QPixmap sliderPixmap = ::findPixmap(dir.absolutePath(), files, "posbar");
    Q_ASSERT(!sliderPixmap.isNull());
    d.posBarStyle->normal.pixmap = sliderPixmap;
    d.posBarStyle->normal.sourceRect = QRect(278, 0, 30, 10);
    d.posBarStyle->normal.targetRect = QRect(0, 0, 30, 10);
    d.posBarStyle->pressed.pixmap = sliderPixmap;
    d.posBarStyle->pressed.sourceRect = QRect(248, 0, 30, 10);
    d.posBarStyle->pressed.targetRect = QRect(0, 0, 30, 10);
    d.posBarStyle->groovePressed.pixmap = sliderPixmap;
    d.posBarStyle->groovePressed.sourceRect = QRect(0, 0, 248, 10);
    // ### a lot of this stuff should be in Player::Player()
    update();
    return true;
}

void Player::showEvent(QShowEvent *e)
{
    activateWindow();
    raise();
    QWidget::showEvent(e);
}

void Player::open()
{
    const QStringList list = QFileDialog::getOpenFileNames(this, tr("Open files"),
                                                           Config::value<QString>("lastDirectory", QDir::homePath()),
                                                           tr("Music files(*.mp3 *.ogg *.flac)"));
    if (list.isEmpty())
        return;
    Config::setValue("lastDirectory", QFileInfo(list.first()).absolutePath());
    foreach(const QString &path, list) {
        d.interface->asyncCall("load", path);
        // ### do I warn if it can't load it?
    }

    // ### need to query these extensions

}

void Player::openSkin()
{
    switch(Config::value<int>("skinSelectionMechism", DirectlySelectFolder)) {
    case SkinFolderListView:
        SkinSelectionDialog::instance(this)->show();
        break;
    case DirectlySelectFolder:
    {
        QFileDialog fd(this);
        fd.setFileMode(QFileDialog::DirectoryOnly);
        fd.setDirectory(Config::value<QString>("skin", QCoreApplication::applicationDirPath()));
        if (fd.exec()) {
            Config::setValue<QString>("skin", fd.directory().absolutePath());
            setSkin(Config::value<QString>("skin"));
            update();
        }
    }
    break;
    }
}

void Player::reloadSettings()
{
    foreach(QAction *a, actions()) {
//        qDebug() << a->objectName() << a;
        if (!a->isSeparator())
            ::setShortcuts(a);
    }

    for (int i=0; i<ButtonCount; ++i) {
        ::setShortcuts(d.buttons[i]);
//        qDebug() << d.buttons[i]->objectName() << d.buttons[i];
    }
}

void Player::closeEvent(QCloseEvent *e)
{
    Config::setValue("geometry", saveGeometry());
    QWidget::closeEvent(e);
    QApplication::quit();
}

void Player::editShortcuts()
{
    ShortcutDialog dialog(this);
    if (dialog.exec())
        reloadSettings();
}

void Player::wakeUp()
{
    activateWindow();
    raise();
}

#ifdef QT_DEBUG
void Player::debugButton()
{
    qDebug() << sender()->objectName();
}
void Player::toggleDebugGeometry(bool on)
{
    Config::setEnabled("debuggeometry", on);
    update();
    foreach(QWidget *w, qFindChildren<QWidget*>(this)) {
        w->update();
    }
}

class Overlay : public QWidget
{
public:
    Overlay(const QPixmap &pix, QWidget *parent)
        : QWidget(parent)
    {
        QPalette pal = palette();
        pal.setBrush(backgroundRole(), pix);
        setPalette(pal);
        setAutoFillBackground(true);
        Q_ASSERT(parent);
        parent->installEventFilter(this);
        setGeometry(parent->rect());
        setAttribute(Qt::WA_MouseTracking);
    }

    void paintEvent(QPaintEvent *)
    {
        QPainter p(this);
        p.setPen(Qt::white);
        const bool debug = Config::isEnabled("debuggeometry");
        foreach(Button *b, qFindChildren<Button*>(window())) {
            QRect r = QRect(b->mapTo(window(), QPoint(0, 0)), b->size());
            if (debug)
                p.drawRect(r.adjusted(0, 0, -1, -1));

            if (r.contains(QCursor::pos() - window()->pos())) {
                p.fillRect(r, QColor(255, 0, 0, 70));
            }
        }
    }
    void mouseMoveEvent(QMouseEvent *)
    {
        update();
    }

    bool eventFilter(QObject *, QEvent *e)
    {
        if (e->type() == QEvent::Resize) {
            setGeometry(parentWidget()->rect());
        }
        return false;
    }
};

void Player::toggleOverlay(bool on)
{
    if (!d.overlay)
        d.overlay = new Overlay(QPixmap("original.png"), this);
    d.overlay->setVisible(on);
    if (on)
        d.overlay->raise();
}

#endif

void Player::resizeEvent(QResizeEvent *e)
{
    static const QSize defaultSize(275, 116);
    double sw = 1;
    double sh = 1;
    if (width() != defaultSize.width()) {
        sw = double(width()) / double(defaultSize.width());
    }

    if (height() != defaultSize.height()) {
        sh = double(height()) / double(defaultSize.height());
    }

    QTransform transform;
    transform.scale(sw, sh);
    setProperty("transform", transform);

    foreach(QWidget *w, qFindChildren<QWidget*>(this)) {
        const QRect defaultGeometry = w->property("defaultGeometry").toRect();
        if (!defaultGeometry.isNull()) {
            w->setGeometry(transform.mapRect(defaultGeometry));
        }
    }
    QWidget::resizeEvent(e);
}

QSize Player::sizeHint() const
{
    return QSize(275, 116);
}

void Player::restoreDefaultSize()
{
    resize(sizeHint());
}

void Player::togglePlaylist()
{
    d.playlist->setVisible(!d.playlist->isVisible());
}

redpajama_set_name: RedPajamaGithub


text:
import type { CSSProperties } from "react";
import type { Theme } from "../lib/types";

const useBackgroundStyle = (
  theme?: Theme,
  thumbnail: boolean = false
): CSSProperties | null =>
  theme?.background
    ? {
        width: "100%",
        backgroundColor: theme.background.color,
        backgroundImage: theme.background.image,
        backgroundSize: theme.background.size,
        backgroundRepeat: theme.background.repeat,
        ...(thumbnail
          ? {
              height: "130px",
            }
          : {
              height: "100%",
              position: "absolute",
              top: 0,
              left: 0,
              zIndex: -1,
            }),
      }
    : null;

export default useBackgroundStyle;


text:
import StructuredSource from "structured-source";
import { ParsedCode, ParsedResults, ParserArgs } from "@power-doctest/types";
import * as fs from "fs";
import * as path from "path";

const Asciidoctor = require("asciidoctor");
const asciidoctor = Asciidoctor();
type Attributes = {
    [index: string]: string;
};
const getState = (attributes: Attributes): "none" | "enabled" | "disabled" => {
    const state = attributes["doctest-state"] || attributes["doctest"];
    if (!state) {
        return "none";
    }
    if (/enable(d)?/.test(state)) {
        return "enabled";
    } else if (/disable(d)?/.test(state)) {
        return "disabled";
    }
    return "none";
};

const getExpectedError = (attributes: Attributes): string | undefined => {
    const error = attributes["doctest-error"] || attributes["doctest"];
    if (!error) {
        return;
    }
    const pattern = /(\w+Error)/;
    const match = error.match(pattern);
    if (match && match[1]) {
        return match[1];
    }
    return;
};

const getMeta = (attributes: Attributes): {} | undefined => {
    const meta = attributes["doctest-meta"];
    if (!meta) {
        return;
    }
    try {
        return JSON.parse(meta);
    } catch (error) {
        // parse error
        throw new Error(`Can not parsed. doctest-meta={...} should be JSON object: ${error}`);
    }
};

const getOptions = (attributes: Attributes): {} | undefined => {
    const meta = attributes["doctest-options"];
    if (!meta) {
        return;
    }
    try {
        return JSON.parse(meta);
    } catch (error) {
        // parse error
        throw new Error(`Can not parsed. doctest-options={...} should be JSON object: ${error}`);
    }
};

// inlining include::
const inlineCode = (code: string, baseFilePath: string): string => {
    // include:: -> link:
    const pattern = /link:(.+)\[.*?]/;
    const dirName = path.dirname(baseFilePath);
    return code.replace(pattern, (all, filePath) => {
        const fileName = path.resolve(dirName, filePath);
        if (fs.existsSync(fileName)) {
            return fs.readFileSync(fileName, "utf-8");
        }
        return all;
    });
};

export function parse(args: ParserArgs): ParsedResults {
    const structuredSource = new StructuredSource(args.content);
    const doc = asciidoctor.load(args.content);
    return doc
        .getBlocks()
        .filter((block: any) => {
            const attributes = block.getAttributes();
            return (
                attributes.style === "source" && (attributes.language === "js" || attributes.language === "javascript")
            );
        })
        .map((block: any) => {
            // FIXME: workaround get lineno
            // asciidoctor.js does not suport lineno for the block
            const code: string = block.getSource();
            const index = args.content.indexOf(code);
            const startPosition = structuredSource.indexToPosition(index);
            const endPostion = structuredSource.indexToPosition(index + code.length);
            const attributes: {} = block.getAttributes();
            const meta = getMeta(attributes);
            const doctestOptions = getOptions(attributes);
            const parsedCode: ParsedCode = {
                code: inlineCode(code, args.filePath),
                state: getState(attributes),
                expectedError: getExpectedError(attributes),
                location: {
                    start: startPosition,
                    end: endPostion,
                },
                metadata: meta,
                doctestOptions: doctestOptions
                    ? {
                          filePath: args.filePath,
                          ...doctestOptions,
                      }
                    : {
                          filePath: args.filePath,
                      },
            };
            return parsedCode;
        });
}


text:
using Foundation;
using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

namespace MyWeather.iOS
{
	// The UIApplicationDelegate for the application. This class is responsible for launching the
	// User Interface of the application, as well as listening (and optionally responding) to application events from iOS.
	[Register ("AppDelegate")]
	public class AppDelegate : FormsApplicationDelegate
    {

		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
            Forms.Init();

            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }

		public override void OnResignActivation (UIApplication application)
		{
			// Invoked when the application is about to move from active to inactive state.
			// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message)
			// or when the user quits the application and it begins the transition to the background state.
			// Games should use this method to pause the game.
		}

		public override void DidEnterBackground (UIApplication application)
		{
			// Use this method to release shared resources, save user data, invalidate timers and store the application state.
			// If your application supports background exection this method is called instead of WillTerminate when the user quits.
		}

		public override void WillEnterForeground (UIApplication application)
		{
			// Called as part of the transiton from background to active state.
			// Here you can undo many of the changes made on entering the background.
		}

		public override void OnActivated (UIApplication application)
		{
			// Restart any tasks that were paused (or not yet started) while the application was inactive.
			// If the application was previously in the background, optionally refresh the user interface.
		}

		public override void WillTerminate (UIApplication application)
		{
			// Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground.
		}
	}
}


text:
package siesta

import (
	"fmt"
	"log"
	"time"

	"github.com/jimlawless/cfg"
)

type ProducerRecord struct {
	Topic string
	Key   interface{}
	Value interface{}

	partition    int32
	encodedKey   []byte
	encodedValue []byte
	metadataChan chan *RecordMetadata
}

type RecordMetadata struct {
	Offset    int64
	Topic     string
	Partition int32
	Error     error
}

type PartitionInfo struct{}
type Metric struct{}
type ProducerConfig struct {
	MetadataFetchTimeout time.Duration
	MetadataExpire       time.Duration
	MaxRequestSize       int
	TotalMemorySize      int
	CompressionType      string
	BatchSize            int
	Linger               time.Duration
	Retries              int
	RetryBackoff         time.Duration
	BlockOnBufferFull    bool

	ClientID        string
	MaxRequests     int
	SendRoutines    int
	ReceiveRoutines int
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	RequiredAcks    int
	AckTimeoutMs    int32
	BrokerList      []string
}

func NewProducerConfig() *ProducerConfig {
	return &ProducerConfig{
		BatchSize:       1000,
		ClientID:        "siesta",
		MaxRequests:     10,
		SendRoutines:    10,
		ReceiveRoutines: 10,
		ReadTimeout:     5 * time.Second,
		WriteTimeout:    5 * time.Second,
		RequiredAcks:    1,
		AckTimeoutMs:    1000,
		Linger:          1 * time.Second,
	}
}

type Serializer func(interface{}) ([]byte, error)

func ByteSerializer(value interface{}) ([]byte, error) {
	if value == nil {
		return nil, nil
	}

	if array, ok := value.([]byte); ok {
		return array, nil
	}

	return nil, fmt.Errorf("Can't serialize %v", value)
}

func StringSerializer(value interface{}) ([]byte, error) {
	if str, ok := value.(string); ok {
		return []byte(str), nil
	}

	return nil, fmt.Errorf("Can't serialize %v to string", value)
}

type Producer interface {
	// Send the given record asynchronously and return a channel which will eventually contain the response information.
	Send(*ProducerRecord) <-chan *RecordMetadata

	// Flush any accumulated records from the producer. Blocks until all sends are complete.
	Flush()

	// Get a list of partitions for the given topic for custom partition assignment. The partition metadata will change
	// over time so this list should not be cached.
	PartitionsFor(topic string) []PartitionInfo

	// Return a map of metrics maintained by the producer
	Metrics() map[string]Metric

	// Tries to close the producer cleanly within the specified timeout. If the close does not complete within the
	// timeout, fail any pending send requests and force close the producer.
	Close(timeout int)
}

type KafkaProducer struct {
	config          *ProducerConfig
	time            time.Time
	partitioner     Partitioner
	keySerializer   Serializer
	valueSerializer Serializer
	metrics         map[string]Metric
	accumulator     *RecordAccumulator
	metricTags      map[string]string
	connector       Connector
	metadata        *Metadata
	RecordsMetadata chan *RecordMetadata
}

func NewKafkaProducer(config *ProducerConfig, keySerializer Serializer, valueSerializer Serializer, connector Connector) *KafkaProducer {
	log.Println("Starting the Kafka producer")
	producer := &KafkaProducer{}
	producer.config = config
	producer.time = time.Now()
	producer.metrics = make(map[string]Metric)
	producer.partitioner = NewHashPartitioner()
	producer.keySerializer = keySerializer
	producer.valueSerializer = valueSerializer
	producer.connector = connector
	producer.metadata = NetMetadata(connector, config.MetadataExpire)
	metricTags := make(map[string]string)

	networkClientConfig := NetworkClientConfig{}
	client := NewNetworkClient(networkClientConfig, connector, config)

	accumulatorConfig := &RecordAccumulatorConfig{
		batchSize:         config.BatchSize,
		totalMemorySize:   config.TotalMemorySize,
		compressionType:   config.CompressionType,
		linger:            config.Linger,
		retryBackoff:      config.RetryBackoff,
		blockOnBufferFull: config.BlockOnBufferFull,
		metrics:           producer.metrics,
		time:              producer.time,
		metricTags:        metricTags,
		networkClient:     client,
	}
	producer.accumulator = NewRecordAccumulator(accumulatorConfig, producer.RecordsMetadata)

	log.Println("Kafka producer started")

	return producer
}

func ProducerConfigFromFile(filename string) (*ProducerConfig, error) {
	c, err := cfg.LoadNewMap(filename)
	if err != nil {
		return nil, err
	}

	producerConfig := NewProducerConfig()
	if err := setDurationConfig(&producerConfig.MetadataFetchTimeout, c["metadata.fetch.timeout"]); err != nil {
		return nil, err
	}
	if err := setDurationConfig(&producerConfig.MetadataExpire, c["metadata.max.age"]); err != nil {
		return nil, err
	}
	if err := setIntConfig(&producerConfig.MaxRequestSize, c["metadata.expire"]); err != nil {
		return nil, err
	}
	if err := setIntConfig(&producerConfig.BatchSize, c["batch.size"]); err != nil {
		return nil, err
	}
	if err := setIntConfig(&producerConfig.RequiredAcks, c["acks"]); err != nil {
		return nil, err
	}
	if err := setInt32Config(&producerConfig.AckTimeoutMs, c["timeout.ms"]); err != nil {
		return nil, err
	}
	if err := setDurationConfig(&producerConfig.Linger, c["linger"]); err != nil {
		return nil, err
	}
	setStringConfig(&producerConfig.ClientID, c["client.id"])
	if err := setIntConfig(&producerConfig.SendRoutines, c["send.routines"]); err != nil {
		return nil, err
	}
	if err := setIntConfig(&producerConfig.ReceiveRoutines, c["receive.routines"]); err != nil {
		return nil, err
	}
	if err := setIntConfig(&producerConfig.MaxRequestSize, c["max.request.size"]); err != nil {
		return nil, err
	}
	setBoolConfig(&producerConfig.BlockOnBufferFull, c["block.on.buffer.full"])
	if err := setIntConfig(&producerConfig.Retries, c["retries"]); err != nil {
		return nil, err
	}
	if err := setDurationConfig(&producerConfig.RetryBackoff, c["retry.backoff"]); err != nil {
		return nil, err
	}
	setStringConfig(&producerConfig.CompressionType, c["compression.type"])
	if err := setIntConfig(&producerConfig.MaxRequests, c["max.requests"]); err != nil {
		return nil, err
	}

	setStringsConfig(&producerConfig.BrokerList, c["bootstrap.servers"])
	if len(producerConfig.BrokerList) == 0 {
		setStringsConfig(&producerConfig.BrokerList, c["metadata.broker.list"])
	}

	return producerConfig, nil
}

func (kp *KafkaProducer) Send(record *ProducerRecord) <-chan *RecordMetadata {
	record.metadataChan = make(chan *RecordMetadata, 1)
	kp.send(record)
	return record.metadataChan
}

func (kp *KafkaProducer) send(record *ProducerRecord) {
	metadataChan := record.metadataChan
	metadata := new(RecordMetadata)

	serializedKey, err := kp.keySerializer(record.Key)
	if err != nil {
		metadata.Error = err
		metadataChan <- metadata
		return
	}

	serializedValue, err := kp.valueSerializer(record.Value)
	if err != nil {
		metadata.Error = err
		metadataChan <- metadata
		return
	}

	record.encodedKey = serializedKey
	record.encodedValue = serializedValue

	partitions, err := kp.metadata.Get(record.Topic)
	if err != nil {
		metadata.Error = err
		metadataChan <- metadata
		return
	}

	partition, err := kp.partitioner.Partition(record, partitions)
	if err != nil {
		metadata.Error = err
		metadataChan <- metadata
		return
	}
	record.partition = partition

	kp.accumulator.addChan <- record
}

func (kp *KafkaProducer) Flush() {}

func (kp *KafkaProducer) PartitionsFor(topic string) []PartitionInfo {
	return []PartitionInfo{}
}

func (kp *KafkaProducer) Metrics() map[string]Metric {
	return make(map[string]Metric)
}

// TODO return channel and remove timeout
func (kp *KafkaProducer) Close(timeout time.Duration) {
	closed := kp.accumulator.close()
	select {
	case <-closed:
	case <-time.After(timeout):
	}
}


text:
using System.Collections.Generic;

namespace Cassandra.DataStax.Graph
{
    /// <summary>
    /// Represents a Vertex in DSE Graph.
    /// </summary>
    public interface IVertex : IElement
    {
        /// <summary>
        /// Gets the first property of this element that has the given name, or null if the property
        /// does not exist.
        /// <para>
        /// If more than one property of this element has the given name, it will return one of them
        /// (unspecified order).
        /// </para>
        /// </summary>
        new IVertexProperty GetProperty(string name);

        /// <summary>
        /// Gets the properties of this element that has the given name or an empty iterator if not found.
        /// </summary>
        IEnumerable<IVertexProperty> GetProperties(string name);

        /// <summary>
        /// Gets the properties of this element.
        /// </summary>
        new IEnumerable<IVertexProperty> GetProperties();
    }
}


text:
import sys
from gi.repository import Gtk
from gi.repository import PanelApplet
from nm_dispatcher_olsrd_applet import applet_factory

if __name__ == '__main__':	# testing for execution
	print('Starting factory')

	if len(sys.argv) > 1 and sys.argv[1] == '-d': # debugging
		mainWindow = Gtk.Window()
		mainWindow.set_title('Applet window')
		mainWindow.connect('destroy', Gtk.main_quit)
		applet_factory(mainWindow, None)
		mainWindow.show_all()
		Gtk.main()
		sys.exit()
	else:
		PanelApplet.Applet.factory_main("nm-dispatcher-olsrd-appletFactory",
				PanelApplet.Applet.__gtype__,
				applet_factory,
				None)


text:
<?php

namespace app\models\warehouse;

use Yii;

/**
 * This is the model class for table "distributor".
 *
 * @property integer $ID_Distributor
 * @property string $Nama
 *
 * @property Puchaseorder[] $puchaseorders
 */
class Distributor extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'distributor';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ID_Distributor', 'Nama'], 'required'],
            [['ID_Distributor'], 'integer'],
            [['Nama'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID_Distributor' => 'Id  Distributor',
            'Nama' => 'Nama',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPuchaseorders()
    {
        return $this->hasMany(Puchaseorder::className(), ['Distributor_ID' => 'ID_Distributor']);
    }
    public function findDistributorWithModule(){
        $sql = "select * from distributor";

        return self::findBySql($sql)->asArray()->all();
    }
    public function getLastIdDistributor(){
        $sql = "select max(ID_Distributor) distributorID from distributor";
        $id = self::findBySql($sql)->asArray()->one();
        return $id['distributorID'];
    }
}


text:
class ResourceMesh : public Resource
{
public:
	ResourceMesh(UID uuid);
	virtual ~ResourceMesh();

	bool LoadInMemory()override;
	bool RemoveFromMemory()override;

	void LoadToVRAM();
	void FreeFromVRAM();

public:
	uint numIndices = 0;
	uint* indices = nullptr;

	uint numVertices = 0;

	//----------------------

	float* vertices = nullptr;
	float* normals = nullptr;
	float* uvs = nullptr;
	float* colors = nullptr;

	//----------------------

	uint idIndices = 0;
	uint idVertices = 0;
	uint idNormals = 0;
	uint idUvs = 0;
	uint idColors = 0;

	uint idContainer = 0;

	//----------------------

	AABB aabb;

};

#endif // !__RESOURCE_MESH_H__


text:
#ifndef _RING_BUFFER_H_
#define _RING_BUFFER_H_

#include <cassert>
#include <iterator>

namespace threadsafe {

template<typename T> class ring_buffer;

namespace impl {

template<typename T>
struct Node {
    Node(bool is_root=false):
        next(this),
        prev(this),
        is_root_(is_root) {
    }

    T val;

    Node* next;
    Node* prev;

    bool is_root() const { return is_root_; }

    void inc_ref() const {
        if(is_root()) return;

        assert(ref_count > -1);
        ++ref_count;
    }

    void dec_ref() const {
        if(is_root()) return;

        --ref_count;
        assert(ref_count > -1);
        if(ref_count == 0) {
            delete this;
        }
    }

private:
    bool is_root_ = false;
    mutable int ref_count = 0;

    Node(const Node& rhs) = delete;
    void operator=(const Node& rhs) = delete;
};

template<typename T, bool is_const=false>
class Iterator : public std::iterator<std::bidirectional_iterator_tag, T> {
public:
    typedef typename std::conditional<is_const, const Node<T>*, Node<T>*>::type node_pointer_type;
    typedef typename std::conditional<is_const, const T&, T&>::type value_reference_type;

private:
    friend class ring_buffer<T>;

    node_pointer_type node_ = nullptr;

public:
    Iterator(const Iterator& rhs) {
        rhs.node_->inc_ref();
        node_ = rhs.node_;
    }

    Iterator& operator=(const Iterator& rhs) {
        if(this == &rhs) {
            return *this;
        }

        if(node_) {
            node_->dec_ref();
        }

        rhs.node_->inc_ref();
        node_ = rhs.node_;
        return *this;
    }

    Iterator(node_pointer_type node) {
        node->inc_ref();
        node_ = node;
    }

    ~Iterator() {
        if(node_) {
            node_->dec_ref();
        }
    }

    value_reference_type operator*() const {
        return node_->val;
    }

    T* operator->() const {
        return &node_->val;
    }

    Iterator& operator++() {
        node_pointer_type old = node_;
        node_ = old->next;
        node_->inc_ref();
        old->dec_ref();

        return *this;
    }

    Iterator operator++(int i) {
        node_pointer_type old = node_;
        node_ = old->next;
        node_->inc_ref();
        old->dec_ref();

        return *this;
    }

    bool operator==(const Iterator& rhs) const {
        return node_ == rhs.node_;
    }
    bool operator!=(const Iterator& rhs) const {
        return !(*this == rhs);
    }
};

} //End impl namespace

template<typename T>
class ring_buffer {
public:
    typedef T value_type;
    typedef impl::Iterator<T> iterator;
    typedef impl::Iterator<T, true> const_iterator;

    ring_buffer():
        root_(true) {}

    ~ring_buffer() {
        erase(begin(), end());
    }

    //  [ R, X1, X2 ]

    void push_back(const value_type& val) {
        impl::Node<T>* new_node = new impl::Node<T>();
        new_node->val = val;
        new_node->prev = root_.prev;
        new_node->next = &root_;
        new_node->inc_ref(); //Always hold a reference for the buffer

        root_.prev->next = new_node; //Forward iterators now find this node
        root_.prev = new_node; //Reverse iterators now find this node
    }

    void push_front(const value_type& val) {
        impl::Node<T>* new_node = new impl::Node<T>();
        new_node->val = val;
        new_node->next = root_.next;
        new_node->prev = &root_;
        new_node->inc_ref();

        root_.next->prev = new_node; //Reverse iterators now find the new node
        root_.next = new_node; //Forward iterators now find the new node
    }

    void pop_back() {
        assert(!empty());
        impl::Node<T>* to_delete = root_.prev;
        to_delete->prev->next = &root_; //Forward iterators now skip this node
        root_.prev = to_delete->prev; //Reverse iterators now skip this node
        to_delete->dec_ref(); //Remove the hold we have on it
    }

    void pop_front() {
        assert(!empty());
        impl::Node<T>* to_delete = root_.next;
        root_.next = to_delete->next; //Forward iterators now skip this node
        to_delete->next->prev = &root_; //Reverse iterators now skip this node
        to_delete->dec_ref();  //Remove the hold we have on it
    }

    T front() const { return root_.next->val; }
    T back() const { return root_.prev->val; }

    iterator begin() { return iterator(root_.next); }
    iterator end() { return iterator(&root_); }

    const_iterator begin() const { return const_iterator(root_.next); }
    const_iterator end() const { return const_iterator(&root_); }

    const bool empty() const { return root_.next == &root_; }
    const size_t size() const {
        size_t i = 0;
        for(auto it: *this) { ++i; }
        return i;
    }

    iterator erase(iterator it) {
        assert(!empty());
        impl::Node<T>* to_delete = it.node_;
        to_delete->prev->next = to_delete->next;
        to_delete->next->prev = to_delete->prev;

        iterator ret(to_delete->next);
        to_delete->dec_ref();
        return ret;
    }

    iterator erase(iterator start, iterator end) {
        for(; start != end;) {
            start = erase(start);
        }
        return start;
    }

private:
    /*
     *  Root stays constant through the lifetime of the ring_buffer. It acts as a dummy node that
     *  represents the "end" iterator. Iterators start at root->next or root->prev and end when they hit
     *  root.
     */
    impl::Node<T> root_;
};

}

#endif


text:
<?xml version="1.0"?>

<?dlps id="WhaShow"?>
<?dlps page-images="none" figure-images="no"?>
<?dlps transcription="other"?>

<!DOCTYPE TEI.2 SYSTEM "http://text.lib.virginia.edu/dtd/tei/tei-p4/tei2.dtd" [
<!ENTITY % POSTKB "INCLUDE">
<!ENTITY % TEI.extensions.ent SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.ent">
<!ENTITY % TEI.extensions.dtd SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.dtd">
<!ENTITY % ISOnum SYSTEM "http://text.lib.virginia.edu/charent/iso-num.ent"> %ISOnum;
<!ENTITY % ISOpub SYSTEM "http://text.lib.virginia.edu/charent/iso-pub.ent"> %ISOpub;
]>

<TEI.2 id="WhaShow">
<teiHeader type="migrated" creator="Etext">
<fileDesc>
<titleStmt>
<title type="main">April Showers</title>
<title type="sort">april showers</title>
<author>Wharton, Edith, 1862-1937</author>
<respStmt>
<resp>Creation of machine-readable version:</resp>
<name>Judy Boss</name>
<resp>Conversion to TEI.2-conformant markup:</resp>
<name>University of Virginia Library Electronic Text Center</name>
</respStmt>
</titleStmt>
<extent>ca. <num type="kilobytes">26</num> kilobytes</extent>
<publicationStmt>
<publisher>University of Virginia Library</publisher>
<pubPlace>Charlottesville, Virginia</pubPlace>
<idno type="ETC">WhaShow</idno>
<date value="1995">1995</date>
<availability status="public">

Copyright © 1995 by the Rector and Visitors of the University of Virginia

Publicly accessible

</availability>
<idno type="uva-pid">uva-lib:476528</idno>
</publicationStmt>
<seriesStmt>
<title>University of Virginia Library, Text collection</title>
<idno type="uva-set">UVA-LIB-Text</idno>
</seriesStmt>
<notesStmt>
<note>

Any other notes.

</note>
</notesStmt>
<sourceDesc>
<biblFull>
<titleStmt>
<title type="main">April Showers</title>
<title type="sort">april showers</title>
<author>Edith Wharton</author>
</titleStmt>
<editionStmt>

1st Edition

</editionStmt>
<publicationStmt>
<publisher>The Youth's Companion</publisher>
<date value="1900">1900</date>
</publicationStmt>
</biblFull>
</sourceDesc>
</fileDesc>
<encodingDesc>
<projectDesc>

Prepared for the University of Virginia Library Electronic
Text Center

</projectDesc>
<editorialDecl>

All quotation marks retained as data

Verification made against printed text.

All unambiguous end-of-line hyphens have been removed, and the
trailing part of a word has been joined to the preceding
line.

Keywords in the header are a local Electronic Text
Center scheme
to aid in establishing analytical groupings

</editorialDecl>
<refsDecl>

ID elements are given for each page element and are composed
of the text's
unique cryptogram and the given page number, as in AusEmma1 for
page one of
Jane Austen's Emma.

</refsDecl>
</encodingDesc>
<profileDesc>
<creation>
<date value="1900">1900</date>
</creation>
<langUsage>
<language id="eng" usage="main">English</language>
</langUsage>
<textClass>
<keywords>
<term>fiction</term>
<term>prose</term>
<term>Women Writers</term>
</keywords>
</textClass>
</profileDesc>
<revisionDesc>
<change>
<date value="1995-04">April 1995</date>
<respStmt>
<resp>corrector</resp>
<name>Kelly Moulton</name>
</respStmt>
<item>TEI tagging</item>
</change>
<change>
<date value="2005-07">July 2005</date>
<respStmt>
<resp>Corrector</resp>
<name>Margaret Konkol</name>
</respStmt>
<item>Converted SGML to XML and fixed tagging.</item>
</change>
<change>
<date value="2007-09">September 2007</date>
<respStmt>
<resp>Migration</resp>
<name>Ethan Gruber, University of Virginia Library</name>
</respStmt>
<item>Converted XML markup from TEI Lite to uva-dl-tei (TEI P4 with local customizations).</item>
</change>
<change>
<date value="2008-01">January 2008</date>
<respStmt>
<resp>Migration</resp>
<name>Greg Murray, University of Virginia Library</name>
</respStmt>
<item>Programmatically updated TEI header markup (but not header content) for minimal compliance with current QA requirements.</item>
</change>
</revisionDesc>
</teiHeader>

<text id="d1">

<div1 type="story" id="d3">
Wharton, Edith.  "April Showers."  <hi rend="italic"> The Youth's Companion</hi>
74,  18 Jan. 1900: 25-26.

<pb n="25"/>

  "BUT Guy's heart slept under the violets on Muriel's
grave."

     It was a beautiful ending; Theodora had seen girls cry over
last chapters that weren't half as pathetic.  She laid her pen
aside and read the words over, letting her voice linger on the
fall
of the sentence; then, drawing a deep breath, she wrote across
the
foot of the page the name by which she had decided to become
known
in literature—Gladys Glyn.

     Down-stairs the library clock struck two.  Its muffled thump
sounded like an admonitory knock against her bedroom floor.  Two
o'clock! and she had promised her mother to be up early enough to
see that the buttons were sewn on Johnny's reefer, and that Kate
had her cod-liver oil before starting for school!

     Lingeringly, tenderly she gathered up the pages of her
novel,—there were five hundred of them,—and tied them with the
blue satin ribbon that her Aunt Julia had given her.  She had
meant
to wear the ribbon with her new dotted muslin on Sundays, but
this
was putting it to a nobler use.  She bound it round her
manuscript,
tying the ends in a pretty bow.  Theodora was clever at making
bows, and could have trimmed hats beautifully, had not all her
spare moments been given to literature.  Then, with a last look
at
the precious pages, she sealed and addressed the package.  She
meant to send it off next morning to the <hi rend="italic"> Home Circle</hi>.
She knew
it would be hard to obtain access to a paper which numbered so
many
popular authors among its contributors, but she had been
encouraged
to make the venture by something her Uncle James had said the
last
time he had come down from Boston.

     He had been telling his brother, Doctor Dace, about his new
house out at Brookline.  Uncle James was prosperous, and was
always
moving into new houses with more "modern improvements."  Hygiene
was his passion, and he migrated in the wake of sanitary
plumbing.

     "The bath-rooms alone are worth the money," he was saying,
cheerfully, "although it <hi rend="italic"> is</hi> a big rent.  But then, when a
man's
got no children to save up for—" he glanced compassionately
round
Doctor Dace's crowded table—"and it <hi rend="italic"> is</hi> something to be
in a
neighborhood where the drainage is A 1.  That's what I was
telling
our neighbor.  Who do you suppose she is, by the way?"  He smiled
at Theodora.  "I rather think that young lady knows all about
her.
Ever hear of Kathleen Kyd?"

     Kathleen Kyd!  The famous "society novelist," the creator of
more "favorite heroines" than all her predecessors put together
had
ever turned out; the author of "Fashion and Passion," "An
American
Duchess," "Rhona's Revolt."  Was there any intelligent girl from
Maine to California whose heart would not have beat faster at the
mention of that name?

     "Why, yes," Uncle James was saying, "Kathleen Kyd lives next
door.  Frances G. Wollop is her real name, and her husband's a
dentist.  She's a very pleasant, sociable kind of woman; you'd
never think she was a writer.  Ever hear how she began to write?
She told me the whole story.  It seems she was saleswoman in a
store, working on starvation wages, with a mother and a
consumptive
sister to support.  Well, she wrote a story one day, just for
fun,
and sent it to the <hi rend="italic"> Home Circle</hi>.  They'd never heard of
her, of
course, and she never expected to hear from them.  She did,
though.
They took the story and passed their plate for more.  She became
a
regular contributor and eventually was known all over the
country.
Now she tells me her books bring her in about ten thousand a
year.
Rather more than you and I can boast of, eh, John?  Well, I hope
<hi rend="italic">
this</hi> household doesn't contribute to her support."  He
glanced
sharply at Theodora.  "I don't believe in feeding youngsters on
sentimental trash; it's like sewer-gas—doesn't smell bad, and
infects the system without your knowing it."

     Theodora listened breathlessly.  Kathleen Kyd's first story
had been accepted by the <hi rend="italic"> Home Circle</hi>, and they had asked
for
more!  Why should Gladys Glyn be less fortunate?  Theodora had
done
a great deal of novel-reading,—far more than her parents were
aware of,—and felt herself competent to pronounce upon the
quality
of her own work.  She was almost sure that "April Showers" was a
remarkable book.  If it lacked Kathleen Kyd's lightness of touch,
it had an emotional intensity never achieved by that brilliant
writer.  Theodora did not care to amuse her readers; she left
that
to more frivolous talents.  Her aim was to stir the depths of
human
nature, and she felt she had succeeded.  It was a great thing for
a girl to be able to feel that about her first novel.  Theodora
was
only seventeen; and she remembered, with a touch of retrospective
compassion, that George Eliot had not become famous till she was
nearly forty.

     No, there was no doubt about the merit of "April Showers."
But would not an inferior work have had a better chance of
success?
Theodora recalled the early struggles of famous authors, the
notorious antagonism of publishers and editors to any new writer
of
exceptional promise.  Would it not be wiser to write the book
down
to the average reader's level, reserving for some later work the
great "effects" into which she had thrown all the fervor of her
imagination?  The thought was sacrilege!  Never would she lay
hands
on the sacred structure she had reared; never would she resort to
the inartistic expedient of modifying her work to suit the
popular
taste.  Better obscure failure than a vulgar triumph.  The great
authors never stooped to such concessions, and Theodora felt
herself included in their ranks by the firmness with which she
rejected all thought of conciliating an unappreciative public.
The
manuscript should be sent as it was.

     She woke with a start and a heavy sense of apprehension.
The
<hi rend="italic"> Home Circle</hi> had refused "April Showers!"  No, that
couldn't be
it; there lay the precious manuscript, waiting to be posted.
What
was it, then?  Ah, that ominous thump below stairs—nine o'clock
striking!  It was Johnny's buttons!

     She sprang out of bed in dismay.  She had been so determined
not to disappoint her mother about Johnny's buttons!  Mrs. Dace,
helpless from chronic rheumatism, had to entrust the care of the
household to her eldest daughter; and Theodora honestly meant to
see that Johnny had his full complement of buttons, and that Kate
and Bertha went to school tidy.  Unfortunately, the writing of a
great novel leaves little time or memory for the lesser
obligations
of life, and Theodora usually found that her good intentions
matured too late for practical results.

     Her contrition was softened by the thought that literary
success would enable her to make up for all the little
negligences
of which she was guilty.  She meant to spend all her money on her
family; and already she had visions of a wheeled chair for her
mother, a fresh wallpaper for the doctor's shabby office,
bicycles
for the girls, and Johnny's establishment at a boarding-school
where sewing on his buttons would be included in the curriculum.
If her parents could have guessed her intentions, they would not
have found fault with her as they did: and Doctor Dace, on this
particular morning, would not have looked up to say, with his
fagged, ironical air:

     "I suppose you didn't get home from the ball till
morning."

     Theodora's sense of being in the right enabled her to take
the
thrust with a dignity that would have awed the unfeeling parent
of
fiction.

     "I'm sorry to be late, father," she said.

     Doctor Dace, who could never be counted on to behave like a
father in a book, shrugged his shoulders impatiently.

     "Your sentiments do you credit, but they haven't kept your
mother's breakfast warm."

     "Hasn't mother's tray gone up yet?"

     "Who was to take it, I should like to know?  The girls came
down so late that I had to hustle them off before they'd finished
breakfast, and Johnny's hands were so dirty that I sent him back
to
his room to make himself decent.  It's a pretty thing for the
doctor's children to be the dirtiest little savages in
Norton!"

     Theodora had hastily prepared her mother's tray, leaving her
own breakfast untouched.  As she entered the room up-stairs, Mrs.
Dace's patient face turned to her with a smile much harder to
bear
than her father's reproaches.

     "Mother, I'm <hi rend="italic"> so</hi> sorry—"

     "No matter, dear.  I suppose Johnny's buttons kept you.  I
can't think what that boy does to his clothes!"

     Theodora set the tray down without speaking.  It was
impossible to own to having forgotten Johnny's buttons without
revealing the cause of her forgetfulness.  For a few weeks longer
she must bear to be misunderstood; then—ah, then if her novel
were
accepted, how gladly would she forget and forgive!  But what if
it
were refused?  She turned aside to hide the dismay that flushed
her
face.  Well, then she would admit the truth—she would ask her
parents' pardon, and settle down without a murmur to an obscure
existence of mending and combing.

     She had said to herself that after the manuscript had been
sent, she would have time to look after the children and catch up
with the mending; but she had reckoned without the postman.  He
came three times a day; and for an hour before each ring she was
too excited to do anything but wonder if he would bring an answer
this time, and for an hour afterward she moved about in a leaden
stupor of disappointment.  The children had never been so trying.

They seemed to be always coming to pieces, like cheap furniture;
<pb n="26"/>  one would have supposed they had been put
together with bad
glue.  Mrs. Dace worried herself ill over Johnny's tatters,
Bertha's bad marks at school, and Kate's open abstention from
cod-liver oil; and Doctor Dace, coming back late from a long round of
visits to a fireless office with a smoky lamp, called out
furiously
to know if Theodora would kindly come down and remove the "East,
West, home's best" that hung above the empty grate.

     In the midst of it all, Miss Sophy Brill called.  It was
very
kind of her to come, for she was the busiest woman in Norton.
She
made it her duty to look after other people's affairs, and there
was not a house in town but had the benefit of her personal
supervision.  She generally came when things were going wrong,
and
the sight of her bonnet on the door-step was a surer sign of
calamity than a crape bow on the bell.  After she left, Mrs. Dace
looked very sad, and the doctor punished Johnny for warbling down
the entry:

                    "Miss Sophy Brill

                     Is a bitter pill!"

while Theodora, locking herself in her room, resolved with tears
that she would never write another novel.

     The week was a long nightmare.  Theodora could neither eat
nor
sleep.  She was up early enough, but instead of looking after the
children and seeing that breakfast was ready, she wandered down
the
road to meet the postman, and came back wan and empty-handed,
oblivious of her morning duties.  She had no idea how long the
suspense would last; but she didn't see how authors could live if
they were kept waiting more than a week.

     Then suddenly, one afternoon—she never quite knew how or
when
it happened—she found herself with a <hi rend="italic"> Home Circle</hi>
envelope in
her hands, and her dazzled eyes flashing over a wild dance of
words
that wouldn't settle down and make sense.

     "Dear Madam:"  [They called her <hi rend="italic"> Madam!</hi>  And then;
yes, the
words were beginning to fall into line now.]  "Your novel, 'April
Showers,' has been received, and we are glad to accept it on the
usual terms.  A serial on which we were counting for immediate
publication has been delayed by the author's illness, and the
first
chapters of 'April Showers' will therefore appear in our
midsummer
number.  Thanking you for favoring us with your manuscript, we
remain," and so forth.

     Theodora found herself in the wood beyond the schoolhouse.
She was kneeling on the ground, brushing aside the dead leaves
and
pressing her lips to the little bursting green things that pushed
up eager tips through last year's decay.  It was spring—spring!
Everything was crowding toward the light, and in her own heart
hundreds of germinating hopes had burst into sudden leaf.  She
wondered if the thrust of those little green fingers hurt the
surface of the earth as her springing raptures hurt—yes,
actually
hurt!—her hot, constricted breast!  She looked up through
interlacing boughs at a tender, opaque blue sky full of the
coming
of a milky moon.  She seemed enveloped in an atmosphere of loving
comprehension.  The brown earth throbbed with her joy, the tree-tops trembled with it, and a sudden star broke through the
branches
like an audible "I know!"

     Theodora, on the whole, behaved very well.  Her mother
cried,
her father whistled and said he supposed he must put up with
grounds in his coffee now, and be thankful if he ever got a hot
meal again; while the children took the most deafening and
harassing advantage of what seemed a sudden suspension of the
laws
of nature.

     Within a week everybody in Norton knew that Theodora had
written a novel, and that it was coming out in the <hi rend="italic"> Home
Circle</hi>.
On Sundays, when she walked up the aisle, her friends dropped
their
prayer-books and the soprano sang false in her excitement.  Girls
with more pin-money than Theodora had ever dreamed of copied her
hats and imitated her way of speaking.  The local paper asked her
for a poem; her old school-teachers stopped to shake hands and
grew
shy over their congratulations; and Miss Sophy Brill came to
call.
She had put on her Sunday bonnet, and her manner was almost
abject.
She ventured, very timidly, to ask her young friend how she
wrote,
whether it "just came to her," and if she had found that the kind
of pen she used made any difference; and wound up by begging
Theodora to write a sentiment in her album.

     Even Uncle James came down from Boston to talk the wonder
over.  He called Theodora a "sly baggage," and proposed that she
should give him her earnings to invest in a new patent
grease-trap
company.  From what Kathleen Kyd had told him, he thought
Theodora
would probably get a thousand dollars for her story.  He
concluded
by suggesting that she should base her next romance on the
subject
of sanitation, making the heroine nearly die of sewer-gas
poisoning
because her parents won't listen to the handsome young doctor
next
door, when he warns them that their plumbing is out of order.
That
was a subject that would interest everybody, and do a lot more
good
than the sentimental trash most women wrote.

     At last the great day came.  Theodora had left an order with
the bookseller for the midsummer number of the <hi rend="italic"> Home
Circle</hi>, and
before the shop was open she was waiting on the sidewalk.  She
clutched the precious paper and ran home without opening it.  Her
excitement was almost more than she could bear.  Not heeding her
father's call to breakfast, she rushed up-stairs and locked
herself
in her room.  Her hands trembled so that she could hardly turn
the
pages.  At last—yes, there it was: "April Showers."

     The paper dropped from her hands.  What name had she read
beneath the title?  Had her emotion blinded her?

     "April Showers, by <hi rend="italic"> Kathleen Kyd</hi>."

     Kathleen Kyd!  Oh, cruel misprint!  Oh, dastardly
typographer!
Through tears of rage and disappointment Theodora looked again:
yes, there was no mistaking the hateful name.  Her glance ran on.

She found herself reading a first paragraph that she had never
seen
before.  She read farther.  All was strange.  The horrible truth
burst upon her: <hi rend="italic"> It was not her story!</hi>

                             —

     She never knew how she got back to the station.  She
struggled
through the crowd on the platform, and a gold-banded arm pushed
her
into the train just starting for Norton.  It would be dark when
she
reached home; but that didn't matter—nothing mattered now.  She
sank into her seat, closing her eyes in the vain attempt to shut
out the vision of the last few hours; but minute by minute memory
forced her to relive it; she felt like a rebellious school child
dragged forth to repeat the same detested "piece."

     Although she did not know Boston well, she had made her way
easily enough to the <hi rend="italic"> Home Circle</hi> building; at least, she
supposed she had, since she remembered nothing till she found
herself ascending the editorial stairs as easily as one does
incredible things in dreams.  She must have walked very fast, for
her heart was beating furiously, and she had barely breath to
whisper the editor's name to a young man who looked out at her
from
a glass case, like a zoological specimen.  The young man led her
past other glass cases containing similar specimens to an inner
enclosure which seemed filled by an enormous presence.  Theodora
felt herself enveloped in the presence, submerged by it, gasping
for air as she sank under its rising surges.

     Gradually fragments of speech floated to the surface.
"'April
Showers?'  Mrs. Kyd's new serial?  <hi rend="italic"> Your</hi> manuscript, you
say?
You have a letter from me?  The name, please?  Evidently some
unfortunate misunderstanding.  One moment."  And then a bell
ringing, a zoological specimen ordered to unlock a safe, her name
asked for again, the manuscript, her own precious manuscript,
tied
with Aunt Julia's ribbon, laid on the table before her, and her
outcries, her protests, her interrogations, drowned in a flood of
bland apology: "An unfortunate accident—Mrs. Kyd's manuscript
received the same day—extraordinary coincidence in the choice of
a title—duplicate answers sent by mistake—Miss Dace's novel
hardly suited to their purpose—should of course have been
returned—regrettable oversight—accidents would happen—sure she
understood."

     The voice went on, like the steady pressure of a surgeon's
hand on a shrieking nerve.  When it stopped she was in the
street.
A cab nearly ran her down, and a car-bell jangled furiously in
her
ears.  She clutched her manuscript, carrying it tenderly through
the crowd, like a live thing that had been hurt.  She could not
bear to look at its soiled edges and the ink-stain on Aunt
Julia's
ribbon.

     The train stopped with a jerk, and she opened her eyes.  It
was dark, and by the windy flare of gas on the platform she saw
the
Norton passengers getting out.  She stood up stiffly and followed
them.  A warm wind blew into her face the fragrance of the summer
woods, and she remembered how, two months earlier, she had knelt
among the dead leaves, pressing her lips to the first shoots of
green.  Then for the first time she thought of home.  She had
fled
away in the morning without a word, and her heart sank at the
thought of her mother's fears.  And her father—how angry he
would
be!  She bent her head under the coming storm of his
derision.

     The night was cloudy, and as she stepped into the darkness
beyond the station a hand was slipped in hers.  She stood still,
too weary to feel frightened, and a voice said, quietly:

     "Don't walk so fast, child.  You look tired."

     "Father!"  Her hand dropped from his, but he recaptured it
and
drew it through his arm.  When she found voice, it was to
whisper,
"You were at the station?"

     "It's such a good night I thought I'd stroll down and meet
you."

     Her arm trembled against his.  She could not see his face in
the dimness, but the light of his cigar looked down on her like a
friendly eye, and she took courage to falter out: "Then you
knew—"

     "That you'd gone to Boston?  Well, I rather thought you
had."

     They walked on slowly, and presently he added, "You see, you
left the <hi rend="italic"> Home Circle</hi> lying in your room."

     How she blessed the darkness and the muffled sky!  She could
not have borne the scrutiny of the tiniest star.

     "Then mother wasn't very much frightened?"

     "Why, no, she didn't appear to be.  She's been busy all day
over some toggery of Bertha's."

     Theodora choked.  "Father, I'll—"  She groped for words,
but
they eluded her.  "I'll do things—differently; I haven't
meant—"
Suddenly she heard herself bursting out: "It was all a mistake,
you
know—about my story.  They didn't want it; they won't have it!"
and she shrank back involuntarily from his impending
mirth.

     She felt the pressure of his arm, but he didn't speak, and
she
figured his mute hilarity.  They moved on in silence.  Presently
he
said:

     "It hurts a bit just at first, doesn't it?"

     "O father!"

     He stood still, and the gleam of his cigar showed a face of
unexpected participation.

     "You see I've been through it myself."

     "You, father?  You?"

     "Why, yes.  Didn't I ever tell you?  I wrote a novel once.
I
was just out of college, and I didn't want to be a doctor.  No; I
wanted to be a genius.  So I wrote a novel."

     The doctor paused, and Theodora clung to him in a mute
passion
of commiseration.  It was as if a drowning creature caught a live
hand through the murderous fury of the waves.

     "Father—O father!"

     "It took me a year—a whole year's hard work; and when I'd
finished it the publishers wouldn't have it, either; not at any
price.  And that's why I came down to meet you, because I
remembered my walk home."

</div1>

</text>
</TEI.2>


text:
package org.trifort.rootbeer.testcases.rootbeertest.serialization;

import org.trifort.rootbeer.runtime.Kernel;
import org.trifort.rootbeer.runtime.RootbeerGpu;

public class StringConstantKernel implements Kernel {

  private String m_string;

  public StringConstantKernel(){
    m_string = "abc";
  }

  public void gpuMethod() {
    m_string = "hello world";
  }

  boolean compare(StringConstantKernel rhs) {
    if(m_string.equals(rhs.m_string) == false){
      System.out.println("m_string: "+m_string);
      System.out.println("rhs.m_string: "+rhs.m_string);
      return false;
    }
    return true;
  }

}


text:
import React from "react";
import {
  mountWithIntl,
  shallowWithIntl,
  renderWithIntl
} from "utils/i18nTesting";

import Table from "./index.js";
import TableLineItem from "./components/TableLineItem";
import GMServiceTableLineItem from "./components/GMServiceTableLineItem";
import TableColHeader from "components/Main/components/TableColHeader";
import TableColLatencyHeader from "components/Main/components/TableColLatencyHeader";

let wrapper;
let routesProps = {
  type: "Route",
  items: [
    {
      errorPercent: "0.000",
      errorsCount: 20,
      inThroughput: 0,
      latency50: 0,
      latency99: 3,
      outThroughput: 29945110,
      requests: 399334,
      requestsPerSecond_dygraph: {
        data: [
          ["Mon Nov 13 2017 17:22:58 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:03 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:08 GMT-0500 (EST)", 0]
        ],
        attributes: ["Time", "Requests"]
      },
      requestsPerSecond_sparkline: [0, 25, 430, 1256],
      route: "/categories",
      verb: "GET"
    },
    {
      errorPercent: "0.000",
      errorsCount: 40,
      inThroughput: 0,
      latency50: 0,
      latency99: 0,
      outThroughput: 29945110,
      requests: 0,
      requestsPerSecond_dygraph: {
        data: [
          ["Mon Nov 13 2017 17:22:58 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:03 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:08 GMT-0500 (EST)", 0]
        ],
        attributes: ["Time", "Requests"]
      },
      requestsPerSecond_sparkline: [0, 25, 430, 1256],
      route: "/topics",
      verb: "GET"
    }
  ]
};

let instancesProps = {
  items: [
    { name: "26d7cmoduw8w000000000", start_time: 134056421868 },
    { name: "52ikspsvqpo0000000000", start_time: 657503172351 },

    { name: "5uws9t7wpac0000000000", start_time: 31280519413 }
  ],
  type: "Instance",
  selectedServiceSlug:
    "authentication-management-transfer-odrive-gateway-statistics-up2-channel",
  status: "Warning"
};

describe("Table component", () => {
  beforeEach(() => {
    wrapper = mountWithIntl(<Table {...routesProps} />);
  });

  test("matches snapshot", () => {
    const tree = renderWithIntl(<Table {...routesProps} />);
    expect(tree).toMatchSnapshot();
  });

  test("renders correct header texts", () => {
    expect(
      wrapper
        .find(TableColHeader)
        .at(0)
        .text()
    ).toBe("Route");
    expect(
      wrapper
        .find(TableColHeader)
        .at(1)
        .text()
    ).toBe("Requests/sec");
    expect(
      wrapper
        .find(TableColHeader)
        .at(2)
        .text()
    ).toBe("Requests");
    expect(
      wrapper
        .find(TableColLatencyHeader)
        .text()
        .includes("Latency")
    ).toBe(true);
  });

  test("when provided routes data, renders <TableLineItem />", () => {
    expect(wrapper.find(TableLineItem).length).toEqual(2);
    expect(wrapper.find(GMServiceTableLineItem).length).toEqual(0);
  });

  test("passes correct data to <TableLineItem />", () => {
    const firstTableLine = wrapper.find(TableLineItem).at(0);
    const secondTableLine = wrapper.find(TableLineItem).at(1);

    expect(firstTableLine.props()).toEqual({
      item: "/categories",
      errorPercent: "0.000",
      latency50: 0,
      latency99: 3,
      relativeReqPercent: 100,
      requests: 399334,
      requestsPerSecond_dygraph: {
        data: [
          ["Mon Nov 13 2017 17:22:58 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:03 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:08 GMT-0500 (EST)", 0]
        ],
        attributes: ["Time", "Requests"]
      },
      requestsPerSecond_sparkline: [0, 25, 430, 1256],
      verb: "GET"
    });
    expect(secondTableLine.props()).toEqual({
      item: "/topics",
      errorPercent: "0.000",
      latency50: 0,
      latency99: 0,
      relativeReqPercent: 0,
      requests: 0,
      requestsPerSecond_dygraph: {
        data: [
          ["Mon Nov 13 2017 17:22:58 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:03 GMT-0500 (EST)", 0],
          ["Mon Nov 13 2017 17:23:08 GMT-0500 (EST)", 0]
        ],
        attributes: ["Time", "Requests"]
      },
      requestsPerSecond_sparkline: [0, 25, 430, 1256],
      verb: "GET"
    });
  });
});

describe("Table component with instances prop", () => {
  let firstGMServiceTableLineItem;
  beforeEach(() => {
    wrapper = shallowWithIntl(<Table {...instancesProps} />);
    firstGMServiceTableLineItem = wrapper
      .dive()
      .find(GMServiceTableLineItem)
      .at(0);
  });

  test("when provided instances data, renders <GMServiceTableLineItem />", () => {
    expect(wrapper.find(GMServiceTableLineItem).length).toEqual(3);
    expect(wrapper.find(TableLineItem).length).toEqual(0);
  });

  test("passes correct props to <GMServiceTableLineItem />", () => {
    expect(firstGMServiceTableLineItem.props()).toHaveProperty(
      "path",
      "/authentication-management-transfer-odrive-gateway-statistics-up2-channel/26d7cmoduw8w000000000"
    );
  });
});


text:
// Code generated by go-swagger; DO NOT EDIT.

// Copyright Authors of Cilium
// SPDX-License-Identifier: Apache-2.0

package policy

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"
	"github.com/go-openapi/strfmt"

	"github.com/cilium/cilium/api/v1/models"
)

// NewGetIdentityParams creates a new GetIdentityParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewGetIdentityParams() *GetIdentityParams {
	return &GetIdentityParams{
		timeout: cr.DefaultTimeout,
	}
}

// NewGetIdentityParamsWithTimeout creates a new GetIdentityParams object
// with the ability to set a timeout on a request.
func NewGetIdentityParamsWithTimeout(timeout time.Duration) *GetIdentityParams {
	return &GetIdentityParams{
		timeout: timeout,
	}
}

// NewGetIdentityParamsWithContext creates a new GetIdentityParams object
// with the ability to set a context for a request.
func NewGetIdentityParamsWithContext(ctx context.Context) *GetIdentityParams {
	return &GetIdentityParams{
		Context: ctx,
	}
}

// NewGetIdentityParamsWithHTTPClient creates a new GetIdentityParams object
// with the ability to set a custom HTTPClient for a request.
func NewGetIdentityParamsWithHTTPClient(client *http.Client) *GetIdentityParams {
	return &GetIdentityParams{
		HTTPClient: client,
	}
}

/*
GetIdentityParams contains all the parameters to send to the API endpoint

	for the get identity operation.

	Typically these are written to a http.Request.
*/
type GetIdentityParams struct {

	/* Labels.

	   List of labels

	*/
	Labels models.Labels

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithDefaults hydrates default values in the get identity params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetIdentityParams) WithDefaults() *GetIdentityParams {
	o.SetDefaults()
	return o
}

// SetDefaults hydrates default values in the get identity params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *GetIdentityParams) SetDefaults() {
	// no default values defined for this parameter
}

// WithTimeout adds the timeout to the get identity params
func (o *GetIdentityParams) WithTimeout(timeout time.Duration) *GetIdentityParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the get identity params
func (o *GetIdentityParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the get identity params
func (o *GetIdentityParams) WithContext(ctx context.Context) *GetIdentityParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the get identity params
func (o *GetIdentityParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the get identity params
func (o *GetIdentityParams) WithHTTPClient(client *http.Client) *GetIdentityParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the get identity params
func (o *GetIdentityParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithLabels adds the labels to the get identity params
func (o *GetIdentityParams) WithLabels(labels models.Labels) *GetIdentityParams {
	o.SetLabels(labels)
	return o
}

// SetLabels adds the labels to the get identity params
func (o *GetIdentityParams) SetLabels(labels models.Labels) {
	o.Labels = labels
}

// WriteToRequest writes these params to a swagger request
func (o *GetIdentityParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error
	if o.Labels != nil {
		if err := r.SetBodyParam(o.Labels); err != nil {
			return err
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
Light

    <form role="form" class="col-sm-12 col-md-12 form-horizontal" ng-submit="submitForm()">
        <input type="submit" hidden />

            Name

                <input id='light-name' type="text" ng-model="light.name" class="form-control"/>

            Status

                <input type="checkbox" toggle-checkbox data-size="small" data-on="Enabled" data-off="Disabled" data-onstyle="success" data-offstyle="default" ng-model="light.enabled" ng-true-value="1" ng-false-value="0">

            Device

                <input type="text" ng-model="light.device" class="form-control"
                       ng-class='{error: isInvalidDevice()}'/>

            Instance

                <input type="text" ng-model="light.instance" class="form-control"
                       ng-class='{error: isInvalidInstance()}'/>

            Host

                <input type="text" ng-model="light.controllerHost" class="form-control"/>

            Port

                <input type="number" ng-model="light.controllerPort" class="form-control"/>

    </form>

            ← Go back

            <button class='btn btn-primary' ng-click="submitForm()"> Save</button>


text:
go-nuodb
========

[NuoDB](http://www.nuodb.com) driver for [Go(golang)](http://www.golang.org) [database/sql](http://golang.org/pkg/database/sql/) interface.

It wraps the libNuoRemote.so C++ API with a custom C API and then uses Cgo for calling it.

## Setup

Installation requires NuoDB in /opt/nuodb and properly set $GOPATH.

```shell
$ go get -d github.com/tilinna/go-nuodb
$ make -C `go env GOPATH`/src/github.com/tilinna/go-nuodb install
```

## Usage

```go
package main

import (
  "database/sql"
	_ "github.com/tilinna/go-nuodb"
)

func main() {
	// func Open(driverName, dataSourceName string) (*DB, error)
	db, err := sql.Open("nuodb", "nuodb://robinh:crossbow@localhost:48004/tests?schema=abcd&timezone=UTC")
}
```

**dataSourceName url string**

Mandatory:

`nuodb://` `username` : `password` @ `broker_address` / `database`

Optional:

* schema=`default schema`
* timezone=`default timezone`
* preferred_address_family=`ipv6`

## Test

### 1. Configure NuoDB

```shell
$ java -jar /opt/nuodb/jar/nuoagent.jar --broker --domain go-nuodb --password archer &
$ /opt/nuodb/bin/nuodb --allow-non-durable --database tests --initialize --password archer --dba-user robinh --dba-password crossbow &
```

### 2. Run the tests

```shell
$ make -C `go env GOPATH`/src/github.com/tilinna/go-nuodb test
```


text:
package org.apache.flink.runtime.rest.messages.taskmanager;

import org.apache.flink.runtime.rest.messages.MessageParameters;
import org.apache.flink.runtime.rest.messages.MessagePathParameter;
import org.apache.flink.runtime.rest.messages.MessageQueryParameter;

import java.util.Collection;
import java.util.Collections;

/**
 * Message parameter for a TaskManager specific handler. The message parameters
 * define the TaskManager id as a path parameter.
 */
public class TaskManagerMessageParameters extends MessageParameters {

	public final TaskManagerIdPathParameter taskManagerIdParameter = new TaskManagerIdPathParameter();

	@Override
	public Collection<MessagePathParameter<?>> getPathParameters() {
		return Collections.singleton(taskManagerIdParameter);
	}

	@Override
	public Collection<MessageQueryParameter<?>> getQueryParameters() {
		return Collections.emptySet();
	}
}


text:
class CreateQuranDictionaryRootExamples < ActiveRecord::Migration[6.1]
  def change
    create_table :dictionary_root_examples do |t|
      t.string :word_arabic
      t.string :word_translation
      t.string :segment_arabic
      t.string :segment_translation

      t.integer :segment_first_word_id
      t.integer :segment_last_word_id
      t.integer :segment_first_word_timestamp
      t.integer :segment_last_word_timestamp

      t.integer :word_id
      t.integer :verse_id

      t.references :word_root, index: { name: :index_on_dict_word_example_id }
      t.index :word_id
      t.index :verse_id

      t.timestamps
    end
  end
end


text:
package com.cool.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cool.api.SysParamService;
import com.cool.base.BaseMapper;
import com.cool.base.BaseServiceImpl;
import com.cool.dao.SysParamMapper;
import com.cool.exception.ServiceException;
import com.cool.model.SysParam;
import com.github.pagehelper.PageInfo;
/**
 *
* @ClassName: SysParamServiceImpl
* @Description: 参数服务
* @author panlei
* @date 2017年7月27日 下午8:46:59
*
 */
@Service
public class SysParamServiceImpl extends BaseServiceImpl<SysParam> implements SysParamService{

	@Autowired
	private SysParamMapper sysParamMapper;

	@Override
	public PageInfo<SysParam> query(Map<String, Object> params) throws ServiceException {
		this.startPage(params);
		return getPageByDB(getMapper().queryForList(params));
	}

	@Override
	protected BaseMapper<SysParam> getMapper() {
		return sysParamMapper;
	}

	@Override
	public List<SysParam> validateSysParam(Map<String, Object> params) {
		return sysParamMapper.querySysParam(params);
	}

	@Override
	public SysParam queryByKey(String paramKey) {
		return sysParamMapper.queryByKey(paramKey);
	}

}


text:
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
import expect from 'expect';
import config from '../../config';
import * as actions from '../../actions/form_options';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const initialize_store = {
  isFetching: false,
  reporterCountries: [],
  partnerCountries: [],
  productGroups: [],
  flowTypes: [],
  tradeFlows: []
};

const form_options_response = {
  aggregations: {
    trade_flows: [{key: 'EXP'}, {key: 'IMP'}],
    flow_types: [{key: 'VALUE'}, {key: 'QTY'}]
  }
};

const trade_flow_response = {
  aggregations: {
    reporters: [{key: 'United States'}, {key: 'China'}]
  }
};
const reporter_response = {
  aggregations: {
    partners: [{key: 'Canada'}, {key: 'Mexico'}],
    product_groups: [{key: 'Flat Products'}, {key: 'Long Products'}]
  }
};

const { host, apiKey } = config.api.steel;

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll();
  });

  it('set trade flow and flow type options', () => {
    nock(host)
      .get(`?api_key=${apiKey}&size=1&`)
      .reply(200, form_options_response);

    const store = mockStore(initialize_store);
    const expected_actions = [
      {
        type: 'explorer/REQUEST_FORM_OPTIONS'
      },
      {
        type: 'explorer/SET_FORM_OPTIONS',
        trade_flows: [{label: 'Exports', value: 'EXP'}, {label: 'Imports', value: 'IMP'}],
        flow_types: [{label: 'Quantity (Metric Tons)', value: 'QTY'}, {label: 'Value (US Dollars)', value: 'VALUE'}]
      }
    ];
    return store.dispatch(actions.requestFormOptions()).then(() => {
      expect(store.getActions()).toEqual(expected_actions);
    });
  });

  it('set reporter country options from trade flow', () => {
    nock(host)
      .get(`?api_key=${apiKey}&size=1&trade_flow=IMP`)
      .reply(200, trade_flow_response);

    const store = mockStore(initialize_store);
    const expected_actions = [
      {
        type: 'explorer/REQUEST_FORM_OPTIONS'
      },
      {
        type: 'explorer/SET_TRADE_FLOW_SUBGROUPS',
        reporter_countries: [{label: 'China', value: 'China'}, {label: 'United States', value: 'United States'}]
      }
    ];
    return store.dispatch(actions.requestTradeFlowSubgroups('IMP')).then(() => {
      expect(store.getActions()).toEqual(expected_actions);
    });
  });

  it('set partner and product groups options from trade flow and reporter', () => {
    nock(host)
      .get(`?api_key=${apiKey}&size=1&trade_flow=IMP&reporter_countries=China`)
      .reply(200, reporter_response);

    const store = mockStore(initialize_store);
    const expected_actions = [
      {
        type: 'explorer/REQUEST_FORM_OPTIONS'
      },
      {
        type: 'explorer/SET_REPORTER_SUBGROUPS',
        partner_countries: [{label: 'Canada', value: 'Canada'}, {label: 'Mexico', value: 'Mexico'}],
        product_groups: [{label: 'Flat Products', value: 'Flat Products'}, {label: 'Long Products', value: 'Long Products'}]
      }
    ];

    return store.dispatch(actions.requestReporterSubgroups('IMP', 'China')).then(() => {
      expect(store.getActions()).toEqual(expected_actions);
    });
  });

});


text:
"""Tests."""

import unittest

from napalm_f5 import f5
from napalm_base.test.base import TestConfigNetworkDriver

class TestConfigF5Driver(unittest.TestCase, TestConfigNetworkDriver):
    """Group of tests that test Configuration related methods."""

    @classmethod
    def setUpClass(cls):
        """Run before starting the tests."""
        hostname = '10.144.129.58'
        username = 'admin'
        password = 'admin'
        cls.vendor = 'f5'

        optional_args = {'port': None, }
        cls.device = f5.F5Driver(hostname, username, password, timeout=60,
                                             optional_args=optional_args)
        cls.device.open()

        cls.device.load_replace_candidate(filename='%s/initial.conf' % cls.vendor)
        cls.device.commit_config()


text:
package hr.fer.zemris.jcms.model.planning;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

/**
 * Generirani raspored
 */

@Entity
@Table(name="schedules")
@NamedQueries({
    @NamedQuery(name="ScheduleDescriptor.listForPlan",query="select m from ScheduleDescriptor as m where m.parent.id = :planID")
})
public class ScheduleDescriptor implements Comparable<ScheduleDescriptor>{

	private static final long serialVersionUID = 1L;

	private Long id;
	private PlanningStorage data;
	private PlanDescriptor parent;
	private Date creationDate;
	private String parameters;
	private int version;

	public ScheduleDescriptor() {
	}

	/**
	 * Identifikator rasporeda
	 * @return
	 */
	@Id @GeneratedValue
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * Sadržaj generiranog rasporeda
	 * @return
	 */
	@OneToOne(fetch=FetchType.LAZY)
	public PlanningStorage getData() {
		return data;
	}
	public void setData(PlanningStorage data) {
		this.data = data;
	}

	/**
	 * Vrijeme i datum generiranja rasporeda
	 * @return
	 */
	@Temporal(TemporalType.TIMESTAMP)
	@Column(nullable=false)
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date date) {
		this.creationDate = date;
	}

	/**
	 * Plan kojem pripada raspored
	 * @return
	 */
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(nullable=false)
	@OnDelete(action=OnDeleteAction.CASCADE)
	public PlanDescriptor getParent() {
		return parent;
	}
	public void setParent(PlanDescriptor parent) {
		this.parent = parent;
	}

	/**
	 * Parametri algoritma za izradu rasporeda
	 * @return
	 */
	@Column(length=100,nullable=false)
	public String getParameters() {
		return parameters;
	}
	public void setParameters(String parameters) {
		this.parameters = parameters;
	}

	/**
	 * Version. Optimistic lock support.
	 * @return
	 */
	@Version
	public int getVersion() {
		return version;
	}
	public void setVersion(int version) {
		this.version = version;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof PlanDescriptor))
			return false;
		PlanDescriptor other = (PlanDescriptor) obj;
		if (getId() == null) {
			if (other.getId() != null)
				return false;
		} else if (!getId().equals(other.getId()))
			return false;
		return true;
	}

	@Override
	public int compareTo(ScheduleDescriptor o) {
		return this.getCreationDate().compareTo(o.getCreationDate());
	}

}