text:
namespace {

enum {
    FILE_COLUMN_NAME = 0,
    FILE_COLUMN_MTIME,
    FILE_COLUMN_SIZE,
    FILE_COLUMN_KIND,
    FILE_COLUMN_PROGRESS,
    FILE_MAX_COLUMN
};

const int kDefaultColumnWidth = 120;
const int kDefaultColumnHeight = 40;
const int kColumnIconSize = 28;
const int kFileNameColumnWidth = 200;
const int kExtraPadding = 30;
const int kDefaultColumnSum = kFileNameColumnWidth + kDefaultColumnWidth * 3 + kExtraPadding;
const int kLockIconSize = 16;

const int kRefreshProgressInterval = 1000;

const QColor kSelectedItemBackgroundcColor("#F9E0C7");
const QColor kItemBackgroundColor("white");
const QColor kItemBottomBorderColor("#f3f3f3");
const QColor kItemColor("black");
const QString kProgressBarStyle("QProgressBar "
        "{ border: 1px solid grey; border-radius: 2px; } "
        "QProgressBar::chunk { background-color: #f0f0f0; width: 20px; }");

enum {
    NOT_LOCKED = 0,
    LOCKED_BY_ME,
    LOCKED_BY_OTHERS
};

const int DirentLockStatusRole = Qt::UserRole + 1;
const int DirentLockOwnerRoler = Qt::UserRole + 2;

} // namespace

FileTableViewDelegate::FileTableViewDelegate(QObject *parent)
  : QStyledItemDelegate(parent) {
}

void FileTableViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    const FileTableModel *model = static_cast<const FileTableModel*>(index.model());

    // fix for the last item
    QRect option_rect = option.rect;
    if (index.column() == FILE_COLUMN_KIND) {
        option_rect.setSize(option_rect.size() - QSize(13, 0));
        // white the extra rect
        const QRect last_rect = QRect(option_rect.topRight(), QSize(13, option_rect.height()));
        painter->save();
        painter->fillRect(last_rect, kItemBackgroundColor);
        painter->restore();
    }

    // draw item's background
    painter->save();
    if (option.state & QStyle::State_Selected)
        painter->fillRect(option_rect, kSelectedItemBackgroundcColor);
    else
        painter->fillRect(option_rect, kItemBackgroundColor);
    painter->restore();

    //
    // draw item's border
    //

    // draw item's border for the first row only
    static const QPen borderPen(kItemBottomBorderColor, 1);
    if (index.row() == 0) {
        painter->save();
        painter->setPen(borderPen);
        painter->drawLine(option_rect.topLeft(), option_rect.topRight());
        painter->restore();
    }
    // draw item's border under the bottom
    painter->save();
    painter->setPen(borderPen);
    painter->drawLine(option_rect.bottomLeft(), option_rect.bottomRight());
    painter->restore();

    //
    // draw item
    //

    QSize size = model->data(index, Qt::SizeHintRole).value<QSize>();
    QString text = model->data(index, Qt::DisplayRole).value<QString>();
    switch (index.column()) {
    case FILE_COLUMN_NAME:
    {
        // draw icon
        QPixmap pixmap = model->data(index, Qt::DecorationRole).value<QPixmap>();
        int alignX = 4; // AlignLeft
        int alignY = (size.height() - kColumnIconSize) / 2; //AlignVCenter
        painter->save();
        painter->drawPixmap(option_rect.topLeft() + QPoint(alignX, alignY - 2), pixmap);
        painter->restore();

        int lock_status = model->data(index, DirentLockStatusRole).toInt();
        if (lock_status != NOT_LOCKED) {
            painter->save();
            QString image = QString(":/images/filebrowser/%1.png").arg(
                lock_status == LOCKED_BY_ME ? "locked-by-me" : "locked");
            QPixmap locked_pixmap = QIcon(image).pixmap(kLockIconSize, kLockIconSize);
            int alignX = (kColumnIconSize / 2) + 3;
            int alignY = (kColumnIconSize / 2) + 2;
            painter->drawPixmap(option_rect.topLeft() + QPoint(alignX, alignY), locked_pixmap);
            painter->restore();
        }

        // draw text
        QFont font = model->data(index, Qt::FontRole).value<QFont>();
        QRect rect(option_rect.topLeft() + QPoint(alignX * 2 + kColumnIconSize, -2), size - QSize(kColumnIconSize, 0));
        painter->setPen(kItemColor);
        painter->setFont(font);
        painter->drawText(rect,
                          Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine,
                          fitTextToWidth(text, option.font, rect.width() - 20));
    }
    break;
    case FILE_COLUMN_SIZE:
    {
        // if we has progress, draw the progress bar
        QString text_progress = model->data(model->index(index.row(), FILE_COLUMN_PROGRESS), Qt::DisplayRole).value<QString>();
        if (!text_progress.isEmpty()) {
            // get the progress value from the Model
            if (text_progress.endsWith('%'))
                text_progress.resize(text_progress.size() - 1);
            const int progress = text_progress.toInt();

            // Customize style using style-sheet..
            QProgressBar progressBar;
            progressBar.resize(QSize(size.width() - 10, size.height() / 2 - 4));
            progressBar.setMinimum(0);
            progressBar.setMaximum(100);
            progressBar.setValue(progress);
            progressBar.setAlignment(Qt::AlignCenter);
            progressBar.setStyleSheet(kProgressBarStyle);
            painter->save();
            painter->translate(option_rect.topLeft() + QPoint(0, size.height() / 4 - 1));
            progressBar.render(painter);
            painter->restore();
            break;
        }
        // else, draw the text only
    }
    // FILE_COLUMN_SIZE comes here
        if (!text.isEmpty())
            text = ::readableFileSize(model->data(index, Qt::DisplayRole).value<quint64>());
    // no break, continue
    case FILE_COLUMN_MTIME:
        if (index.column() == FILE_COLUMN_MTIME)
            text = ::translateCommitTime(model->data(index, Qt::DisplayRole).value<quint64>());
    // no break, continue
    case FILE_COLUMN_KIND:
    {
        if (index.column() == FILE_COLUMN_KIND) {
            text = model->data(index, Qt::UserRole).toString();
        }
        QFont font = model->data(index, Qt::FontRole).value<QFont>();
        QRect rect(option_rect.topLeft() + QPoint(4, -2), size - QSize(10, 0));
        painter->save();
        painter->setPen(kItemColor);
        painter->setFont(font);
        painter->drawText(rect, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, text);
        painter->restore();
    }
    break;
    case FILE_COLUMN_PROGRESS:
    // don't do anything
    break;
    default:
    // never reached here
    // QStyledItemDelegate::paint(painter, option, index);
    qWarning() << "invalid item (row)";
    break;
    }
}

FileTableView::FileTableView(QWidget *parent)
    : QTableView(parent),
      parent_(qobject_cast<FileBrowserDialog*>(parent)),
      source_model_(NULL),
      proxy_model_(NULL)
{
    verticalHeader()->hide();
    verticalHeader()->setDefaultSectionSize(36);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
    horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
#endif
    horizontalHeader()->setStretchLastSection(true);
    horizontalHeader()->setCascadingSectionResizes(true);
    horizontalHeader()->setHighlightSections(false);
    horizontalHeader()->setSortIndicatorShown(true);
    horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    setGridStyle(Qt::NoPen);
    setShowGrid(false);
    setContentsMargins(0, 0, 0, 0);
    setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);

    setSelectionBehavior(QAbstractItemView::SelectRows);
    setSelectionMode(QAbstractItemView::ExtendedSelection);

    setMouseTracking(true);
    setAcceptDrops(true);
    setDragDropMode(QAbstractItemView::DropOnly);
    setItemDelegate(new FileTableViewDelegate(this));

    connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
            this, SLOT(onItemDoubleClicked(const QModelIndex&)));

    setupContextMenu();
}

void FileTableView::setModel(QAbstractItemModel *model)
{
    source_model_ = qobject_cast<FileTableModel*>(model);
    if (!source_model_)
        return;
    proxy_model_ = new FileTableSortFilterProxyModel(source_model_);
    proxy_model_->setSourceModel(source_model_);
    QTableView::setModel(proxy_model_);

    setColumnHidden(FILE_COLUMN_PROGRESS, true);
    connect(model, SIGNAL(modelAboutToBeReset()), this, SLOT(onAboutToReset()));
    setSortingEnabled(true);

    // set default sort by folder
    sortByColumn(FILE_COLUMN_NAME, Qt::AscendingOrder);
}

const SeafDirent *FileTableView::getSelectedItemFromSource()
{
    QItemSelectionModel *selections = this->selectionModel();
    QModelIndexList selected = selections->selectedRows();
    if (selected.size() == 1)
        return source_model_->direntAt(proxy_model_->mapToSource(selected.front()).row());
    return NULL;
}

QList<const SeafDirent *> FileTableView::getSelectedItemsFromSource()
{
    QList<const SeafDirent *> results;
    QItemSelectionModel *selections = this->selectionModel();
    QModelIndexList selected = selections->selectedRows();
    results.reserve(selected.size());
    for (int i = 0; i != selected.size() ; i++) {
        results.push_back(source_model_->direntAt(proxy_model_->mapToSource(selected[i]).row()));
    }
    return results;
}

void FileTableView::setupContextMenu()
{
    context_menu_ = new QMenu(this);
    connect(parent_, SIGNAL(aboutToClose()),
            context_menu_, SLOT(close()));
    download_action_ = new QAction(tr("&Open"), this);
    connect(download_action_, SIGNAL(triggered()),
            this, SLOT(onOpen()));
    download_action_->setShortcut(QKeySequence::InsertParagraphSeparator);

    saveas_action_ = new QAction(tr("&Save As..."), this);
    connect(saveas_action_, SIGNAL(triggered()),
            this, SLOT(onSaveAs()));
    saveas_action_->setShortcut(Qt::ALT + Qt::Key_S);

    lock_action_ = new QAction(tr("&Lock"), this);
    connect(lock_action_, SIGNAL(triggered()), this, SLOT(onLock()));
    lock_action_->setShortcut(Qt::ALT + Qt::Key_L);
    if (!parent_->account_.isAtLeastProVersion(4, 2, 0)) {
        lock_action_->setEnabled(false);
        lock_action_->setToolTip(tr("This feature is available in pro version only\n"));
    }

    rename_action_ = new QAction(tr("&Rename"), this);
    connect(rename_action_, SIGNAL(triggered()),
            this, SLOT(onRename()));
    rename_action_->setShortcut(Qt::ALT + Qt::Key_R);

    remove_action_ = new QAction(tr("&Delete"), this);
    connect(remove_action_, SIGNAL(triggered()),
            this, SLOT(onRemove()));
    remove_action_->setShortcut(QKeySequence::Delete);

    share_action_ = new QAction(tr("&Generate Share Link"), this);
    connect(share_action_, SIGNAL(triggered()),
            this, SLOT(onShare()));
    share_action_->setShortcut(Qt::ALT + Qt::Key_G);

    share_seafile_action_ = new QAction(tr("G&enerate Seafile Internal Link"), this);
    connect(share_seafile_action_, SIGNAL(triggered()),
            this, SLOT(onShareSeafile()));
    share_seafile_action_->setShortcut(Qt::ALT + Qt::Key_E);

    if (parent_->repo_.encrypted) {
        share_action_->setEnabled(false);
    }

    update_action_ = new QAction(tr("&Update"), this);
    connect(update_action_, SIGNAL(triggered()), this, SLOT(onUpdate()));
    update_action_->setShortcut(Qt::ALT + Qt::Key_U);

    copy_action_ = new QAction(tr("&Copy"), this);
    connect(copy_action_, SIGNAL(triggered()), this, SLOT(onCopy()));
    copy_action_->setShortcut(QKeySequence::Copy);

    move_action_ = new QAction(tr("Cu&t"), this);
    connect(move_action_, SIGNAL(triggered()), this, SLOT(onMove()));
    move_action_->setShortcut(QKeySequence::Cut);

    paste_action_ = new QAction(tr("&Paste"), this);
    connect(paste_action_, SIGNAL(triggered()), this, SIGNAL(direntPaste()));
    paste_action_->setShortcut(QKeySequence::Paste);

    if (parent_->current_readonly_) {
        move_action_->setEnabled(false);
        paste_action_->setEnabled(false);
    }

    cancel_download_action_ = new QAction(tr("Canc&el Download"), this);
    connect(cancel_download_action_, SIGNAL(triggered()),
            this, SLOT(onCancelDownload()));
    cancel_download_action_->setShortcut(Qt::ALT + Qt::Key_C);

    sync_subdirectory_action_ = new QAction(tr("&Sync this folder"), this);
    connect(sync_subdirectory_action_, SIGNAL(triggered()),
            this, SLOT(onSyncSubdirectory()));
    sync_subdirectory_action_->setShortcut(Qt::ALT + Qt::Key_S);
    if (!parent_->account_.isAtLeastProVersion(4, 1, 0)) {
        sync_subdirectory_action_->setEnabled(false);
        sync_subdirectory_action_->setToolTip(tr("This feature is available in pro version only\n"));
    }

    context_menu_->setDefaultAction(download_action_);
    context_menu_->addAction(download_action_);
    context_menu_->addAction(saveas_action_);
    context_menu_->addAction(share_action_);
    context_menu_->addAction(share_seafile_action_);
    context_menu_->addSeparator();
    context_menu_->addAction(move_action_);
    context_menu_->addAction(copy_action_);
    context_menu_->addAction(paste_action_);
    context_menu_->addSeparator();
    context_menu_->addAction(lock_action_);
    context_menu_->addAction(rename_action_);
    context_menu_->addAction(remove_action_);
    context_menu_->addSeparator();
    context_menu_->addAction(update_action_);
    context_menu_->addAction(cancel_download_action_);
    context_menu_->addAction(sync_subdirectory_action_);

    this->addAction(download_action_);
    this->addAction(saveas_action_);
    this->addAction(share_action_);
    this->addAction(share_seafile_action_);
    this->addAction(move_action_);
    this->addAction(copy_action_);
    this->addAction(paste_action_);
    this->addAction(lock_action_);
    this->addAction(rename_action_);
    this->addAction(remove_action_);
    this->addAction(update_action_);
    this->addAction(cancel_download_action_);
    this->addAction(sync_subdirectory_action_);

    paste_only_menu_ = new QMenu(this);
    paste_only_menu_->addAction(paste_action_);
}

void FileTableView::contextMenuEvent(QContextMenuEvent *event)
{
    QPoint position = event->pos();
    const QModelIndex proxy_index = indexAt(position);
    position = viewport()->mapToGlobal(position);

    //
    // show paste only menu for no items
    // paste-dedicated menu
    //
    if (!proxy_index.isValid()) {
        if (parent_->hasFilesToBePasted()) {
            paste_only_menu_->exec(position);
        }
        return;
    }

    //
    // paste_action shows only if there are files in the clipboard
    // and is enabled only if it comes from the same account
    //
    paste_action_->setVisible(parent_->hasFilesToBePasted());
    paste_action_->setEnabled(!parent_->current_readonly_ &&
        parent_->account_to_be_pasted_from_ == parent_->account_);

    //
    // map back to the source index from FileTableModel
    //
    const QModelIndex index = proxy_model_->mapToSource(proxy_index);
    const int row = index.row();
    const SeafDirent *dirent = source_model_->direntAt(row);
    // if invalid dirent? no sure why it comes
    if (!dirent)
        return;

    //
    // find if the item is in the selection
    // get selections
    QItemSelectionModel *selections = this->selectionModel();
    QModelIndexList selected = selections->selectedRows();
    int pos;
    for (pos = 0; pos < selected.size(); pos++)
    {
        if (row == proxy_model_->mapToSource(selected[pos]).row())
            break;
    }
    //
    // if the item is in the selection
    // but it is a multi-selection
    //
    // the situation is different from the single-selection
    // supports: download only (and cancel download action perhaps?)
    //
    if (pos != selected.size() && selected.size() != 1) {
        item_.reset(NULL);

        bool has_dir = false;
        for (int i = 0; i != selected.size() ; i++) {
            if (source_model_->direntAt(proxy_model_->mapToSource(selected[i]).row())->isDir()) {
                has_dir = true;
                break;
            }
        }

        download_action_->setVisible(true);
        saveas_action_->setText(tr("&Save As To..."));
        saveas_action_->setEnabled(!has_dir);
        download_action_->setText(tr("D&ownload"));
        lock_action_->setVisible(false);
        rename_action_->setVisible(false);
        share_action_->setVisible(false);
        share_seafile_action_->setVisible(false);
        update_action_->setVisible(false);
        cancel_download_action_->setVisible(false);
        sync_subdirectory_action_->setVisible(false);

        context_menu_->exec(position);

        return;
    }

    //
    // if the item is not in the selection
    // and it is the single-selection situation
    //
    // it is the most common case
    //

    item_.reset(new SeafDirent(*dirent));

    saveas_action_->setText(tr("&Save As..."));
    rename_action_->setVisible(true);
    share_action_->setVisible(true);
    share_seafile_action_->setVisible(true);
    update_action_->setVisible(true);
    cancel_download_action_->setVisible(true);
    download_action_->setVisible(true);
    cancel_download_action_->setVisible(false);
    if (item_->readonly) {
        move_action_->setEnabled(false);
        rename_action_->setEnabled(false);
        update_action_->setEnabled(false);
        remove_action_->setEnabled(false);
    } else {
        move_action_->setEnabled(true);
        rename_action_->setEnabled(true);
        update_action_->setEnabled(true);
        remove_action_->setEnabled(true);
    }

    if (item_->isDir()) {
        lock_action_->setVisible(false);
        update_action_->setVisible(false);
        download_action_->setText(tr("&Open"));
        saveas_action_->setEnabled(false);
        sync_subdirectory_action_->setVisible(true);
    } else {
        if (item_->locked_by_me) {
            lock_action_->setText(tr("Un&lock"));
            lock_action_->setVisible(true);
        } else if (item_->is_locked || item_->readonly) {
            lock_action_->setVisible(false);
        } else {
            lock_action_->setText(tr("&Lock"));
            lock_action_->setVisible(true);
        }

        update_action_->setVisible(true);
        download_action_->setText(tr("D&ownload"));
        saveas_action_->setEnabled(true);
        sync_subdirectory_action_->setVisible(false);

        if (TransferManager::instance()->getDownloadTask(parent_->repo_.id,
            ::pathJoin(parent_->current_path_, dirent->name))) {
            cancel_download_action_->setVisible(true);
            download_action_->setVisible(false);
            saveas_action_->setVisible(false);
        }
    }

    context_menu_->exec(position); // synchronously

    //
    // reset it to NULL, when the menu exec is done
    //
    item_.reset(NULL);
}

void FileTableView::onAboutToReset()
{
    item_.reset(NULL);
}

void FileTableView::onItemDoubleClicked(const QModelIndex& index)
{
    const SeafDirent *dirent =
      source_model_->direntAt(proxy_model_->mapToSource(index).row());

    if (dirent == NULL)
        return;

    emit direntClicked(*dirent);
}

void FileTableView::onOpen()
{
    if (item_ == NULL) {
        const QList<const SeafDirent*> dirents = getSelectedItemsFromSource();
        // if we are going to open a directory
        if (dirents.size() == 1 &&
            dirents.front()->isDir()) {
            emit direntClicked(*dirents.front());
            return;
        }
        // in other cases, download files only
        for (int i = 0; i < dirents.size(); i++) {
            // ignore directories since we have no support for them
            if (dirents[i]->isDir())
                continue;

            emit direntClicked(*dirents[i]);
        }
        return;
    }

    emit direntClicked(*item_);
}

void FileTableView::onSaveAs()
{
    if (item_ == NULL) {
        const QList<const SeafDirent*> dirents = getSelectedItemsFromSource();
        emit direntSaveAs(dirents);
        return;
    }

    QList<const SeafDirent*> dirents;
    dirents.push_back(item_.data());
    emit direntSaveAs(dirents);
}

void FileTableView::onLock()
{
    const SeafDirent * item = item_.data();
    if (item == NULL)
        item = getSelectedItemFromSource();
    if (!item || item->isDir() || item->readonly)
        return;

    emit direntLock(*item);
}

void FileTableView::onRename()
{
    if (item_ == NULL) {
        const SeafDirent *selected_item = getSelectedItemFromSource();
        if (selected_item && !selected_item->readonly)
            emit direntRename(*selected_item);
        return;
    }

    if (!item_->readonly)
        emit direntRename(*item_);
}

void FileTableView::onRemove()
{
    bool has_readonly = false;
    if (item_ == NULL) {
        const QList<const SeafDirent*> dirents = getSelectedItemsFromSource();
        Q_FOREACH(const SeafDirent* dirent, dirents)
        {
            if (dirent->readonly) {
                has_readonly = true;
                break;
            }
        }
        if (!has_readonly) {
            emit direntRemove(dirents);
            return;
        }
    }
    if (has_readonly || item_->readonly) {
        seafApplet->messageBox(tr("Unable to remove readonly files"), this);
    }

    emit direntRemove(*item_);
}

void FileTableView::onShare()
{
    if (item_ == NULL) {
        const SeafDirent *selected_item = getSelectedItemFromSource();
        if (selected_item && selected_item->isFile())
            emit direntShare(*selected_item);
        return;
    }
    emit direntShare(*item_);
}

void FileTableView::onShareSeafile()
{
    if (item_ == NULL) {
        const SeafDirent *selected_item = getSelectedItemFromSource();
        if (selected_item && selected_item->isFile())
            emit direntShareSeafile(*selected_item);
        return;
    }
    emit direntShareSeafile(*item_);
}

void FileTableView::onUpdate()
{
    if (item_ == NULL) {
        const SeafDirent *selected_item = getSelectedItemFromSource();
        if (selected_item && selected_item->isFile() && !selected_item->readonly)
            emit direntUpdate(*selected_item);
        return;
    }
    if (!item_->readonly)
        emit direntUpdate(*item_);
}

void FileTableView::onCopy()
{
    QStringList file_names;

    if (item_ == NULL) {
        const QList<const SeafDirent*> dirents = getSelectedItemsFromSource();
        for (int i = 0; i < dirents.size(); i++) {
            file_names.push_back(dirents[i]->name);
        }
    } else {
        file_names.push_back(item_->name);
    }

    parent_->setFilesToBePasted(true, file_names);
}

void FileTableView::onMove()
{
    QStringList file_names;
    bool has_readonly = false;

    if (item_ == NULL) {
        const QList<const SeafDirent*> dirents = getSelectedItemsFromSource();
        for (int i = 0; i < dirents.size(); i++) {
            // unable to move readonly files
            if (dirents[i]->readonly) {
                has_readonly = true;
                break;
            }
            file_names.push_back(dirents[i]->name);
        }
    } else {
        if (item_->readonly) {
            has_readonly = true;
        } else {
            file_names.push_back(item_->name);
        }
    }

    if (has_readonly) {
        seafApplet->messageBox(tr("Unable to cut readonly files"), this);
        return;
    }

    parent_->setFilesToBePasted(false, file_names);
}

void FileTableView::onCancelDownload()
{
    if (item_ == NULL) {
        const QList<const SeafDirent*> dirents = getSelectedItemsFromSource();
        for (int i = 0; i < dirents.size(); i++) {
            emit cancelDownload(*dirents[i]);
        }
        return;
    }
    emit cancelDownload(*item_);
}

void FileTableView::onSyncSubdirectory()
{
    if (item_ && item_->isDir())
        emit syncSubdirectory(item_->name);
}

void FileTableView::dropEvent(QDropEvent *event)
{
    // only handle external source currently
    if(event->source() != NULL)
        return;

    QList<QUrl> urls = event->mimeData()->urls();

    if(urls.isEmpty())
        return;

    QStringList paths;
    Q_FOREACH(const QUrl& url, urls)
    {
        QString path = url.toLocalFile();
#if defined(Q_OS_MAC) && (QT_VERSION <= QT_VERSION_CHECK(5, 4, 0))
        path = utils::mac::fix_file_id_url(path);
#endif

        if(path.isEmpty())
            continue;
        paths.push_back(path);
    }

    event->accept();

    emit dropFile(paths);
}

void FileTableView::dragMoveEvent(QDragMoveEvent *event)
{
    // this is needed
    event->accept();
}

void FileTableView::dragEnterEvent(QDragEnterEvent *event)
{
    // only handle external source currently
    if(event->source() != NULL)
        return;

    // Otherwise it might be a MoveAction which is unacceptable
    event->setDropAction(Qt::CopyAction);

    // trivial check
    if(event->mimeData()->hasFormat("text/uri-list"))
        event->accept();
}

void FileTableView::resizeEvent(QResizeEvent *event)
{
    QTableView::resizeEvent(event);
    if (source_model_)
        source_model_->onResize(event->size());
}

FileTableModel::FileTableModel(QObject *parent)
    : QAbstractTableModel(parent),
    name_column_width_(kFileNameColumnWidth)
{
    task_progress_timer_ = new QTimer(this);
    connect(task_progress_timer_, SIGNAL(timeout()),
            this, SLOT(updateDownloadInfo()));
    task_progress_timer_->start(kRefreshProgressInterval);
}

void FileTableModel::setDirents(const QList<SeafDirent>& dirents)
{
    beginResetModel();
    dirents_ = dirents;
    progresses_.clear();
    endResetModel();
}

int FileTableModel::rowCount(const QModelIndex& parent) const
{
    return dirents_.size();
}

int FileTableModel::columnCount(const QModelIndex& parent) const
{
    return FILE_MAX_COLUMN;
}

QVariant FileTableModel::data(const QModelIndex & index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    const int column = index.column();
    const int row = index.row();
    const SeafDirent& dirent = dirents_[row];

    if (role == Qt::DecorationRole && column == FILE_COLUMN_NAME) {
      QIcon icon;
      if (dirent.isDir())
          icon = dirent.readonly
                     ? QIcon(":/images/files_v2/file_folder_readonly.png")
                     : QIcon(":/images/files_v2/file_folder.png");
      else
          icon = QIcon(getIconByFileNameV2(dirent.name));
      return icon.pixmap(kColumnIconSize, kColumnIconSize);
    }

    if (role == Qt::SizeHintRole) {
        QSize qsize(kDefaultColumnWidth, kDefaultColumnHeight);
        switch (column) {
        case FILE_COLUMN_NAME:
            qsize.setWidth(name_column_width_);
            break;
        case FILE_COLUMN_PROGRESS:
        case FILE_COLUMN_SIZE:
        case FILE_COLUMN_MTIME:
        case FILE_COLUMN_KIND:
        default:
            break;
        }
        return qsize;
    }

    if (role == Qt::UserRole && column == FILE_COLUMN_KIND) {
        return dirent.isDir() ? readableNameForFolder() : readableNameForFile(dirent.name);
    }

    if (role == DirentLockStatusRole && column == FILE_COLUMN_NAME) {
        if (dirent.locked_by_me) {
            return (int)LOCKED_BY_ME;
        } else if (dirent.is_locked) {
            return (int)LOCKED_BY_OTHERS;
        } else
            return NOT_LOCKED;
    }

    if (role == DirentLockOwnerRoler && column == FILE_COLUMN_NAME) {
        return dirent.lock_owner;
    }

    if (role == Qt::ToolTipRole && column == FILE_COLUMN_NAME && !dirent.lock_owner.isEmpty()) {
        return tr("locked by %1").arg(dirent.lock_owner);
    }

    if (role != Qt::DisplayRole) {
        return QVariant();
    }

    // DisplayRole

    switch (column) {
    case FILE_COLUMN_NAME:
        return dirent.name;
    case FILE_COLUMN_SIZE:
        if (dirent.isDir())
            return "";
        return dirent.size;
    case FILE_COLUMN_MTIME:
        return dirent.mtime;
    case FILE_COLUMN_KIND:
        // workaround with sorting
        return dirent.isDir() ? "" : iconPrefixFromFileName(dirent.name);
    case FILE_COLUMN_PROGRESS:
        return getTransferProgress(dirent);
    default:
        return QVariant();
    }
}

QString FileTableModel::getTransferProgress(const SeafDirent& dirent) const
{
    return progresses_[dirent.name];
}

QVariant FileTableModel::headerData(int section,
                                    Qt::Orientation orientation,
                                    int role) const
{
    if (orientation == Qt::Vertical)
        return QVariant();

    if (role == Qt::TextAlignmentRole)
        return Qt::AlignLeft + Qt::AlignVCenter;

    if (role != Qt::DisplayRole)
        return QVariant();

    switch (section) {
    case FILE_COLUMN_NAME:
        return tr("Name");
    case FILE_COLUMN_SIZE:
        return tr("Size");
    case FILE_COLUMN_MTIME:
        return tr("Last Modified");
    case FILE_COLUMN_KIND:
        return tr("Kind");
    default:
        return QVariant();
    }
}

const SeafDirent* FileTableModel::direntAt(int row) const
{
    if (row >= dirents_.size())
        return NULL;

    return &dirents_[row];
}

void FileTableModel::replaceItem(const QString &name, const SeafDirent &dirent)
{
    for (int pos = 0; pos != dirents_.size() ; pos++)
        if (dirents_[pos].name == name) {
            dirents_[pos] = dirent;
            emit dataChanged(index(pos, 0), index(pos , FILE_MAX_COLUMN - 1));
            break;
        }
}

void FileTableModel::insertItem(int pos, const SeafDirent &dirent)
{
    if (pos > dirents_.size())
        return;
    beginInsertRows(QModelIndex(), pos, pos);
    dirents_.insert(pos, dirent);
    endInsertRows();
}

void FileTableModel::removeItemNamed(const QString &name)
{
    for (int pos = 0; pos != dirents_.size() ; pos++)
        if (dirents_[pos].name == name) {
            beginRemoveRows(QModelIndex(), pos, pos);
            dirents_.removeAt(pos);
            endRemoveRows();
            break;
        }
}

void FileTableModel::renameItemNamed(const QString &name, const QString &new_name)
{
    for (int pos = 0; pos != dirents_.size() ; pos++)
        if (dirents_[pos].name == name) {
            dirents_[pos].name = new_name;
            emit dataChanged(index(pos, 0), index(pos , FILE_MAX_COLUMN - 1));
            break;
        }
}

void FileTableModel::onResize(const QSize &size)
{
    name_column_width_ = size.width() - kDefaultColumnSum + kFileNameColumnWidth;
    // name_column_width_ should be always larger than kFileNameColumnWidth
    if (dirents_.empty())
        return;
    emit dataChanged(index(0, FILE_COLUMN_NAME),
                     index(dirents_.size()-1 , FILE_COLUMN_NAME));
}

void FileTableModel::updateDownloadInfo()
{
    FileBrowserDialog *dialog = (FileBrowserDialog *)(QObject::parent());
    QList<FileDownloadTask*> tasks= TransferManager::instance()->getDownloadTasks(
        dialog->repo_.id, dialog->current_path_);

    progresses_.clear();

    Q_FOREACH (FileDownloadTask *task, tasks) {
        QString progress = task->progress().toString();
        progresses_[::getBaseName(task->path())] = progress;
    }

    if (dirents_.empty())
        return;
    emit dataChanged(index(0, FILE_COLUMN_SIZE),
                     index(dirents_.size() - 1 , FILE_COLUMN_SIZE));
}


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.doneButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonDidTouch:)];
    self.editingButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editingButtonDidTouch:)];
    self.navigationBar.topItem.rightBarButtonItem = self.editingButtonItem;
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
	if (editing == self.editing) return;

    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    self.navigationBar.topItem.rightBarButtonItem = editing ? self.doneButtonItem : self.editingButtonItem;
}

#pragma mark - UITableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.textLabel.text = @"test";
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.isEditing ? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (editingStyle == UITableViewCellEditingStyleDelete)
    {
		NSLog(@"Delete cell: %@", indexPath);
	}
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
		NSLog(@"Insert cell: %@", indexPath);
	}
}

- (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self setEditing:YES animated:YES];
}

- (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self setEditing:NO animated:YES];
}

#pragma mark - Action

- (IBAction)editingButtonDidTouch:(id)sender
{
    [self setEditing:!self.editing animated:YES];
}

- (IBAction)doneButtonDidTouch:(id)sender
{
    [self setEditing:!self.editing animated:YES];
}

@end

redpajama_set_name: RedPajamaGithub


text:
namespace clblast {
namespace database {

extern const DatabaseEntry PadtransposeHalf;
extern const DatabaseEntry PadtransposeSingle;
extern const DatabaseEntry PadtransposeComplexSingle;
extern const DatabaseEntry PadtransposeDouble;
extern const DatabaseEntry PadtransposeComplexDouble;

} // namespace database
} // namespace clblast


text:
package com.spotify.helios;

import com.google.common.base.Throwables;
import com.google.common.net.HostAndPort;

import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerCertificates;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.HostInfo;
import com.spotify.helios.common.descriptors.HostStatus;
import com.spotify.helios.testing.Prober;
import com.spotify.helios.testing.TemporaryJob;
import com.spotify.helios.testing.TemporaryJobBuilder;
import com.spotify.helios.testing.TemporaryJobs;

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.net.Socket;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static com.google.common.base.Optional.fromNullable;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.spotify.helios.Utils.soloImage;
import static com.spotify.helios.system.SystemTestBase.ALPINE;
import static com.spotify.helios.system.SystemTestBase.BUSYBOX;
import static com.spotify.helios.system.SystemTestBase.IDLE_COMMAND;
import static com.spotify.helios.system.SystemTestBase.NGINX;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;

public class HeliosSoloIT {

  @Rule
  public final TemporaryJobs temporaryJobs = TemporaryJobs.create();

  private static final String TEST_USER = "HeliosIT";
  private static final String TEST_HOST = "solo.local";

  private static HeliosClient soloClient;

  @Before
  public void setup() throws Exception {
    // fun times. we're going to start helios-solo as a temporary job in helios.

    // use a probe container to inspect the helios agent environment. we need to inject the same
    // environment into the helios-solo job so that it can find Docker, etc.
    final TemporaryJob probe = temporaryJobs.job()
        .image(BUSYBOX)
        .command(IDLE_COMMAND)
        .deploy();
    final HostStatus hostStatus = temporaryJobs.client()
        .hostStatus(probe.hosts().get(0)).get();
    final Map<String, String> hostEnvironment = hostStatus.getEnvironment();
    final HostInfo hostInfo = hostStatus.getHostInfo();
    probe.undeploy();

    // get values from the agent environment
    final String hostAddress = fromNullable(hostEnvironment.get("HELIOS_HOST_ADDRESS"))
        .or(probe.hosts().get(0));
    String dockerHost = hostInfo.getDockerHost();
    String certPath = hostInfo.getDockerCertPath();

    boolean useUnixSocketEndpoint = false;
    if (isNullOrEmpty(dockerHost)) {
      // no docker host specified, so fall back to the unix socket endpoint.
      useUnixSocketEndpoint = true;
    } else if (!dockerHost.startsWith("unix:///")) {
      if (dockerHost.contains("127.0.0.1")) {
        // the docker host is localhost. this can't be reached from within the helios-solo container
        // so try to fallback to the unix socket endpoint instead.
        useUnixSocketEndpoint = true;
      } else {
        // check if the docker instance used by the agent is Boot2Docker. if so use the unix socket
        // endpoint to avoid having to deal with Boot2Docker TLS certificate messiness.
        final String dockerUri = dockerHost.replace("tcp://", (isNullOrEmpty(certPath) ?
                                                               "http://" : "https://"));
        final DefaultDockerClient.Builder docker = DefaultDockerClient.builder().uri(dockerUri);
        if (!isNullOrEmpty(certPath)) {
          docker.dockerCertificates(new DockerCertificates(Paths.get(certPath)));
        }
        if (docker.build().info().operatingSystem().contains("Boot2Docker")) {
          // using boot2docker, so use the unix socket endpoint
          useUnixSocketEndpoint = true;
        }
      }
    }

    if (useUnixSocketEndpoint) {
      dockerHost = DefaultDockerClient.DEFAULT_UNIX_ENDPOINT;
      certPath = null;
    }

    // build the helios-solo job
    final TemporaryJobBuilder solo = temporaryJobs.job()
        .image(soloImage())
        .prober(new SoloStatusProber())
        .port("helios", 5801, 55801)
        .env("HELIOS_ID", "solo_it")
        .env("HELIOS_NAME", TEST_HOST)
        .env("HOST_ADDRESS", hostAddress)
        .env("DOCKER_HOST", dockerHost)
        .env("REGISTRAR_HOST_FORMAT", "_${service}._${protocol}.services.${domain}");

    if (!isNullOrEmpty(certPath)) {
      solo.env("DOCKER_CERT_PATH", "/certs")
          .volume("/certs", certPath);
    }

    if (dockerHost.startsWith("unix:///")) {
      solo.volume("/var/run/docker.sock", dockerHost.replace("unix://", ""));
    }

    // deploy the helios-solo job and create a Helios client for talking to it
    final String masterEndpoint = "http://" + solo.deploy().address("helios").toString();
    soloClient = HeliosClient.newBuilder()
        .setEndpoints(masterEndpoint)
        .setUser(TEST_USER)
        .build();
  }

  @Test
  public void soloTest() throws Exception {
    // run some jobs on the helios-solo cluster that we just brought up (inception/mind blown)
    assertThat(testResult(HeliosSoloITImpl.class), isSuccessful());
    assertTrue("jobs are running that should not be",
               soloClient.jobs().get(15, SECONDS).isEmpty());
  }

  public static class HeliosSoloITImpl {

    private TemporaryJob alpine;

    @Rule
    public final TemporaryJobs soloTemporaryJobs = TemporaryJobs.builder("local")
        .hostFilter(TEST_HOST)
        .client(soloClient)
        .prefixDirectory("/tmp/helios-solo-jobs")
        .build();

    @Before
    public void setup() throws Exception {
      // start a container that runs nginx and registers with SkyDNS
      soloTemporaryJobs.job()
          .image(NGINX)
          .port("http", 80, 59980)
          .registration("nginx", "http", "http")
          .deploy();

      // run a container that does SRV lookup to find the nginx service and then curl's it
      alpine = soloTemporaryJobs.job()
          .image(ALPINE)
          .port("nc", 4711, 54711)
          .command("sh", "-c",
                   "apk-install bind-tools " +
                   "&& export SRV=$(dig -t SRV +short _nginx._http.services.$SPOTIFY_DOMAIN) " +
                   "&& export HOST=$(echo $SRV | cut -d' ' -f4) " +
                   "&& export PORT=$(echo $SRV | cut -d' ' -f3) " +
                   "&& nc -lk -p 4711 -e curl http://$HOST:$PORT"
          )
          .deploy();
    }

    @Test
    public void test() throws Exception {
      final HostAndPort alpineAddress = alpine.address("nc");

      // Connect to alpine container to get the curl response. If we get back the nginx welcome page
      // we know that helios properly registered the nginx service in SkyDNS.
      try (final Socket s = new Socket(alpineAddress.getHostText(), alpineAddress.getPort())) {
        final String result = IOUtils.toString(s.getInputStream()).trim();
        assertThat(result, containsString("Welcome to nginx!"));
      }
    }
  }

  private class SoloStatusProber implements Prober {
    @Override
    public boolean probe(String host, int port) {
      try {
        final HeliosClient soloClient = HeliosClient.newBuilder()
            .setEndpoints("http://" + host + ":" + port)
            .setUser(TEST_USER)
            .build();

        final HostStatus hostStatus = soloClient.hostStatus(TEST_HOST).get(30, TimeUnit.SECONDS);
        return hostStatus != null && hostStatus.getStatus() == HostStatus.Status.UP;
      } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw Throwables.propagate(e);
      }
    }
  }

}


text:
/* $NetBSD: haltwovar.h,v 1.1 2003/09/25 16:35:50 lonewolf Exp $ */

/*
 * Copyright (c) 2003 Ilpo Ruotsalainen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * <<Id: LICENSE_GC,v 1.1 2001/10/01 23:24:05 cgd Exp>>
 */

#ifndef _ARCH_SGIMIPS_HPC_HALTWOVAR_H_
#define _ARCH_SGIMIPS_HPC_HALTWOVAR_H_

/* XXX Quite arbitrary? XXX */
#define HALTWO_MAX_DMASEGS	16

/* Mixer indices */
#define HALTWO_MASTER_VOL	0
#define HALTWO_OUTPUT_CLASS	1

struct haltwo_dmabuf {
	bus_dmamap_t dma_map;
	bus_dma_segment_t dma_segs[HALTWO_MAX_DMASEGS];
	int dma_segcount;
	size_t size;
	caddr_t kern_addr;

	struct haltwo_dmabuf *next;
};

struct haltwo_codec {
	bus_dmamap_t dma_map;
	bus_dma_segment_t dma_seg;

	struct hpc_dma_desc *dma_descs;

	void (*intr)(void *);
	void *intr_arg;
};

struct haltwo_softc {
	struct device sc_dev;

	bus_space_tag_t sc_st;

	bus_space_handle_t sc_dma_sh;

	bus_dma_tag_t sc_dma_tag;

	struct haltwo_dmabuf *sc_dma_bufs;

	struct haltwo_codec sc_dac;
#if 0
	struct haltwo_codec sc_adc;
#endif
	uint8_t sc_vol_left;
	uint8_t sc_vol_right;

	bus_space_handle_t sc_ctl_sh;
	bus_space_handle_t sc_aes_sh;
	bus_space_handle_t sc_vol_sh;
	bus_space_handle_t sc_syn_sh;
};

#endif


text:
package com.microsoft.azure.management.datafactory.v2018_06_01;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * Json write settings.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = JsonWriteSettings.class)
@JsonTypeName("JsonWriteSettings")
public class JsonWriteSettings extends FormatWriteSettings {
    /**
     * File pattern of JSON. This setting controls the way a collection of JSON
     * objects will be treated. The default value is 'setOfObjects'. It is
     * case-sensitive. Possible values include: 'setOfObjects',
     * 'arrayOfObjects'.
     */
    @JsonProperty(value = "filePattern")
    private JsonWriteFilePattern filePattern;

    /**
     * Get file pattern of JSON. This setting controls the way a collection of JSON objects will be treated. The default value is 'setOfObjects'. It is case-sensitive. Possible values include: 'setOfObjects', 'arrayOfObjects'.
     *
     * @return the filePattern value
     */
    public JsonWriteFilePattern filePattern() {
        return this.filePattern;
    }

    /**
     * Set file pattern of JSON. This setting controls the way a collection of JSON objects will be treated. The default value is 'setOfObjects'. It is case-sensitive. Possible values include: 'setOfObjects', 'arrayOfObjects'.
     *
     * @param filePattern the filePattern value to set
     * @return the JsonWriteSettings object itself.
     */
    public JsonWriteSettings withFilePattern(JsonWriteFilePattern filePattern) {
        this.filePattern = filePattern;
        return this;
    }

}


text:
import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  TouchableHighlight,
  Navigator
} from 'react-native';
import {
  Router
} from 'react-native-router-flux';
import scenes from './routes/index.js';

class App extends Component {
  render() {
    return (
      <Router scenes={scenes} />
    );
  }
}
export default App;


text:
package com.swfarm.biz.wish.dao;

import com.swfarm.biz.wish.bo.WishSkuMapping;
import com.swfarm.pub.framework.dao.GenericDao;

public interface WishSkuMappingDao extends GenericDao<WishSkuMapping, Long> {
}


text:
<!DOCTYPE html>
<html>
  <body>
    <svg>
      <rect id="first" x="10" y="110" width="100" height="10" fill="blue"/>
      <rect id="second" x="10" y="120" width="200" height="10" fill="blue"/>
      <rect id="third" x="10" y="130" width="300" height="10" fill="blue"/>
    </svg>
    <script src="../web-animations.js"></script>
    <script>
      'use strict';
      var first = document.getElementById('first');
      var second = document.getElementById('second');
      var third = document.getElementById('third');
      first.animate([{fill: 'red'}, {fill: 'red'}], {duration: 1000});
      second.animate([{fill: 'red'}, {fill: 'red'}], {duration: 2000});
      third.animate([{fill: 'red'}, {fill: 'red'}], {duration: 3000});
    </script>
  </body>
</html>


text:
package com.perm.kate.api;

import java.io.Serializable;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Attachment implements Serializable {
    private static final long serialVersionUID = 1L;
    public long id;//used only for wall post attached to message
    public String type; //photo,posted_photo,video,audio,link,note,app,poll,doc,geo,message,page,album
    public Photo photo;
    //public Photo posted_photo;
    public Video video;
    public Audio audio;
    public Link link;
    public Note note;
    public Graffiti graffiti;
    public VkApp app;
    public VkPoll poll;
    public Geo geo;
    public Document document;
    public Message message;
    public WallMessage wallMessage;
    public Page page;
    public Gift gift;
    public Album album;

    public static ArrayList<Attachment> parseAttachments(JSONArray attachments, long from_id, long copy_owner_id, JSONObject geo_json) throws JSONException {
        ArrayList<Attachment> attachments_arr=new ArrayList<Attachment>();
        if(attachments!=null){
            int size=attachments.length();
            for(int j=0;j<size;++j){
                Object att=attachments.get(j);
                if(att instanceof JSONObject==false)
                    continue;
                JSONObject json_attachment=(JSONObject)att;
                Attachment attachment=new Attachment();
                attachment.type=json_attachment.getString("type");
                if(attachment.type.equals("photo") || attachment.type.equals("posted_photo")){
                    JSONObject x=json_attachment.optJSONObject("photo");
                    if(x!=null)
                        attachment.photo=Photo.parse(x);
                }
                else if(attachment.type.equals("graffiti"))
                    attachment.graffiti=Graffiti.parse(json_attachment.getJSONObject("graffiti"));
                else if(attachment.type.equals("link"))
                    attachment.link=Link.parse(json_attachment.getJSONObject("link"));
                else if(attachment.type.equals("audio"))
                    attachment.audio=Audio.parse(json_attachment.getJSONObject("audio"));
                else if(attachment.type.equals("note"))
                    attachment.note=Note.parse(json_attachment.getJSONObject("note"));
                else if(attachment.type.equals("video"))
                    attachment.video=Video.parseForAttachments(json_attachment.getJSONObject("video"));
                else if(attachment.type.equals("poll")){
                    attachment.poll=VkPoll.parse(json_attachment.getJSONObject("poll"));
                    if(attachment.poll.owner_id==0){
                        //это устарело потому что поля copy_owner_id больше нет при парсинге
                        //if(copy_owner_id!=0)
                        //    attachment.poll.owner_id=copy_owner_id;
                        //else
                        attachment.poll.owner_id=from_id;
                    }
                }
                else if(attachment.type.equals("doc"))
                    attachment.document=Document.parse(json_attachment.getJSONObject("doc"));
                else if(attachment.type.equals("wall"))
                    attachment.wallMessage=WallMessage.parse(json_attachment.getJSONObject("wall"));
                else if(attachment.type.equals("page"))
                    attachment.page=Page.parseFromAttachment(json_attachment.getJSONObject("page"));
                else if(attachment.type.equals("gift"))
                    attachment.gift=Gift.parse(json_attachment.getJSONObject("gift"));
                else if(attachment.type.equals("album"))
                    attachment.album=Album.parseFromAttachment(json_attachment.getJSONObject("album"));
                attachments_arr.add(attachment);
            }
        }

        //Geo тоже добавляем в attacmnets если он есть
        if(geo_json!=null){
            Attachment a=new Attachment();
            a.type="geo";
            a.geo=Geo.parse(geo_json);
            attachments_arr.add(a);
        }
        return attachments_arr;
    }
}


text:
namespace Microsoft.Azure.Management.RecoveryServices.Backup.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// SQL specific recoverypoint, specifically encapsulates full/diff
    /// recoverypoint along with extended info
    /// </summary>
    public partial class AzureWorkloadSQLRecoveryPoint : AzureWorkloadRecoveryPoint
    {
        /// <summary>
        /// Initializes a new instance of the AzureWorkloadSQLRecoveryPoint
        /// class.
        /// </summary>
        public AzureWorkloadSQLRecoveryPoint()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the AzureWorkloadSQLRecoveryPoint
        /// class.
        /// </summary>
        /// <param name="recoveryPointTimeInUTC">UTC time at which recovery
        /// point was created</param>
        /// <param name="type">Type of restore point. Possible values include:
        /// 'Invalid', 'Full', 'Log', 'Differential'</param>
        /// <param name="extendedInfo">Extended Info that provides data
        /// directory details. Will be populated in two cases:
        /// When a specific recovery point is accessed using GetRecoveryPoint
        /// Or when ListRecoveryPoints is called for Log RP only with
        /// ExtendedInfo query filter</param>
        public AzureWorkloadSQLRecoveryPoint(System.DateTime? recoveryPointTimeInUTC = default(System.DateTime?), string type = default(string), AzureWorkloadSQLRecoveryPointExtendedInfo extendedInfo = default(AzureWorkloadSQLRecoveryPointExtendedInfo))
            : base(recoveryPointTimeInUTC, type)
        {
            ExtendedInfo = extendedInfo;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets extended Info that provides data directory details.
        /// Will be populated in two cases:
        /// When a specific recovery point is accessed using GetRecoveryPoint
        /// Or when ListRecoveryPoints is called for Log RP only with
        /// ExtendedInfo query filter
        /// </summary>
        [JsonProperty(PropertyName = "extendedInfo")]
        public AzureWorkloadSQLRecoveryPointExtendedInfo ExtendedInfo { get; set; }

    }
}


text:
USING_NS_CC;

Scene* Cocos2dx1pxScene::createScene()
{
    return Cocos2dx1pxScene::create();
}

static void problemLoading(const char* filename)
{
    printf("Error while loading: %s\n", filename);
    printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in Cocos2dx1pxScene.cpp\n");
}

void clear_buf(uint8_t * buf, const size_t &buf_size, const uint8_t &r, const uint8_t &g, const uint8_t &b, const uint8_t &a)
{
	for (size_t i = 0; i < buf_size; i += 4) {
		buf[i + 0] = r;
		buf[i + 1] = g;
		buf[i + 2] = b;
		buf[i + 3] = a;
	}
}

void set_pixel(uint8_t * buf, const Size &size, const int &x, const int &y, const uint8_t &r, const uint8_t &g, const uint8_t &b, const uint8_t &a)
{
	uint8_t *p = buf + (x * 4) + (y * 4 * (int)size.width);
	*(p + 0) = r;
	*(p + 1) = g;
	*(p + 2) = b;
	*(p + 3) = a;
}

bool Cocos2dx1pxScene::init()
{
    if ( !Scene::init() )
    {
        return false;
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

	Size size = Size(200, 200);
	size_t buf_size = size.width * size.height * 4;
	uint8_t * buf = (uint8_t *)malloc(buf_size);

	//
	// memo : Sprite <-- SpriteFrame(s) <-- Texture
	//

	// create SpriteFrame(s)
	Vector<SpriteFrame*> sprite_frames;
	for (int i = 0; i < 4; ++i) {
		clear_buf(buf, buf_size, 0, 0, 0, 255);

		switch (i) {
		case 0:
			set_pixel(buf, size, 100, 100, 255, 0, 0, 255);
			break;
		case 1:
			set_pixel(buf, size, 100, 100, 0, 255, 0, 255);
			break;
		case 2:
			set_pixel(buf, size, 100, 100, 0, 0, 255, 255);
			break;
		default:
			break;
		}

		Texture2D* texture = new Texture2D();
		if (!texture->initWithData(buf, buf_size, Texture2D::PixelFormat::RGBA8888, size.width, size.height, size)) {
			CCLOG("Could not create texture");
			delete texture;
			texture = NULL;
		}
		texture->setAliasTexParameters();

		SpriteFrame* sprite_frame = SpriteFrame::createWithTexture(texture, Rect(0, 0, size.width, size.height));
		texture->autorelease();

		sprite_frames.pushBack(sprite_frame);
	}

	free(buf);

	// Create Sprite from SpriteFrame(s)
	auto sprite = Sprite::createWithSpriteFrame(sprite_frames.front());
	sprite->setScale(1.0);
	this->addChild(sprite);
	sprite->setPosition(100, 100);

	// set Animation
	auto animation = Animation::createWithSpriteFrames(sprite_frames, 1.0f / 4);
	sprite->runAction(RepeatForever::create(Animate::create(animation)));

	// press escape key to exit
	auto listeiner = EventListenerKeyboard::create();
	listeiner->onKeyReleased = [this](EventKeyboard::KeyCode keyCode, Event *event) {
		switch (keyCode) {
		case EventKeyboard::KeyCode::KEY_ESCAPE:
			log("Escape");
			auto director = Director::getInstance();
			director->end();
			break;
		}
	};
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listeiner, this);

	return true;
}

void Cocos2dx1pxScene::menuCloseCallback(Ref* pSender)
{
    Director::getInstance()->end();
}


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (MPLS is hanging on in this SD-WAN world)
[#]: via: (https://www.networkworld.com/article/3409070/mpls-is-hanging-on-in-this-sd-wan-world.html)
[#]: author: (Andy Patrizio https://www.networkworld.com/author/Andy-Patrizio/)

MPLS is hanging on in this SD-WAN world
======
The legacy networking protocol is still viable and there is no need to replace it in certain use cases, argues one cloud provider.
![jamesteohart][1]

The [SD-WAN networking market is booming and is expected to grow][2] to $17 billion by 2025, and no wonder. Software-defined wide-area networking eliminates the need for expensive routers and does all the network connectivity in the cloud.

Among its advantages is the support for secure cloud connectivity, one area where multiprotocol label switching (MPLS) falls short. MPLS is a data protocol from before the internet took off and while ideal for communications within the corporate firewall, it doesn't lend itself to cloud and outside communications well.

You would think that would seal MPLS's fate, but just like IPv6 is ever so slowly replacing IPv4, MPLS is hanging on and some IT pros are even increasing their investment.

**[ Related: [MPLS explained – What you need to know about multi-protocol label switching][3] ]**

Avant Communications, a cloud services provider that specializes in SD-WAN, recently issued a report entitled [State of Disruption][4] that found that 83% of enterprises that use or are familiar with MPLS plan to increase their MPLS network infrastructure this year, and 40% say they will "significantly increase" their use of it.

The report did not find one protocol winning that the expense of another. Just as 83% plan to use MPLS, 78% acknowledged plans to use SD-WAN in their corporate networks by the end of the year. Although SD-WAN is on the rise, MPLS is clearly not going away anytime soon. Both SD-WAN and MPLS can live together in harmony, adding value to each other.

"SD-WAN is the most disruptive technology in our study. It's not surprising that adoption of new technologies is slowest among the largest companies. The wave of SD-WAN disruption has not fully hit larger companies yet, but our belief is that it is moving quickly upmarket," the report stated.

While SD-WAN is much better suited for the job of cloud connectivity, 50% of network traffic is still staying within the corporate firewall. So while SD-WAN can solve the connection issues, so can MPLS. And if you have it deployed, rip and replace makes no sense.

"MPLS continues to have a strong role in modern networks, and we expect that to continue," the report stated. "This is especially true among larger enterprises that have larger networks depending on MPLS. While you'll find MPLS at the core for a long time to come, we expect to see a shared environment with SD-WAN at the edge, enabled by broadband Internet and other lower cost networks. "

And MPLS isn't without its advantages, most notably it can [guarantee performance][5] while SD-WAN, at the mercy of the public internet, cannot.

As broadband networks continue to improve in performance, SD-WAN will allow companies to reduce their reliance on MPLS, especially as equipment ages and is replaced. Avant expects that, for the foreseeable future, there will continue to be a very viable role for both.

**More about SD-WAN:**

  * [How to buy SD-WAN technology: Key questions to consider when selecting a supplier][6]
  * [How to pick an off-site data-backup method][7]
  * [SD-Branch: What it is and why you'll need it][8]
  * [What are the options for security SD-WAN?][9]

Join the Network World communities on [Facebook][10] and [LinkedIn][11] to comment on topics that are top of mind.

--------------------------------------------------------------------------------

via: https://www.networkworld.com/article/3409070/mpls-is-hanging-on-in-this-sd-wan-world.html

作者:[Andy Patrizio][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://www.networkworld.com/author/Andy-Patrizio/
[b]: https://github.com/lujun9972
[1]: https://images.idgesg.net/images/article/2019/07/the-latest-in-innovation-in-the-sd-wan-managed-services-market1400-100801684-large.jpg
[2]: https://www.prnewswire.com/news-releases/software-defined-wide-area-network-sd-wan-market-to-hit-17bn-by-2025-global-market-insights-inc-300795304.html
[3]: https://www.networkworld.com/article/2297171/sd-wan/network-security-mpls-explained.html
[4]: https://www.goavant.net/Disruption
[5]: https://www.networkworld.com/article/2297171/network-security-mpls-explained.html
[6]: https://www.networkworld.com/article/3323407/sd-wan/how-to-buy-sd-wan-technology-key-questions-to-consider-when-selecting-a-supplier.html
[7]: https://www.networkworld.com/article/3328488/backup-systems-and-services/how-to-pick-an-off-site-data-backup-method.html
[8]: https://www.networkworld.com/article/3250664/lan-wan/sd-branch-what-it-is-and-why-youll-need-it.html
[9]: https://www.networkworld.com/article/3285728/sd-wan/what-are-the-options-for-securing-sd-wan.html?nsdr=true
[10]: https://www.facebook.com/NetworkWorld/
[11]: https://www.linkedin.com/company/network-world


text:
<?php

namespace Drupal\Tests\shortcut\Unit\Menu;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Tests\Core\Menu\LocalTaskIntegrationTestBase;

/**
 * Tests existence of shortcut local tasks.
 *
 * @group shortcut
 */
class ShortcutLocalTasksTest extends LocalTaskIntegrationTestBase {

  protected function setUp(): void {
    $this->directoryList = [
      'shortcut' => 'core/modules/shortcut',
      'user' => 'core/modules/user',
    ];
    parent::setUp();

    // Add services required for user local tasks.
    $entity_type_manager = $this->createMock(EntityTypeManagerInterface::class);
    $entity_type_manager->expects($this->any())
      ->method('getDefinitions')
      ->will($this->returnValue([]));
    $this->container->set('entity_type.manager', $entity_type_manager);
    $this->container->set('string_translation', $this->getStringTranslationStub());
  }

  /**
   * Checks shortcut listing local tasks.
   *
   * @dataProvider getShortcutPageRoutes
   */
  public function testShortcutPageLocalTasks($route) {
    $tasks = [
      0 => ['shortcut.set_switch', 'entity.user.canonical', 'entity.user.edit_form'],
    ];
    $this->assertLocalTasks($route, $tasks);
  }

  /**
   * Provides a list of routes to test.
   */
  public function getShortcutPageRoutes() {
    return [
      ['entity.user.canonical'],
      ['entity.user.edit_form'],
      ['shortcut.set_switch'],
    ];
  }

}


text:
"use strict";
var url = "http://localhost:5000";
function resetPW(user,pass) {
  var resetPasswordData = {
      method: "POST",
      headers: {
          'content-type': 'application/json'
      },
      body: JSON.stringify({
          email: user,
          pass: pass
      })
  }
  fetch(url+"/reset-password", resetPasswordData)
  .then(function(res){
      if(res.ok){
          //reset password
          location.href = "../HTML/index.html";
          console.log("password reset done");
      }
      else{
          //alert incorrect
          console.log("incorrect email/password");
      }
  })
  .catch(function(err){
      console.log("POST request failed", err);
  });
}


text:
using FluentAssertions;
using NUnit.Framework;
using SampleService;

namespace SampleTest
{
    [TestFixture]
    public class SampleTest
    {
        #region SetUp / TearDown

        private CarService _service;

        [SetUp]
        public void Init()
        {
            this._service = new CarService();
        }

        [TearDown]
        public void Dispose()
        {
            this._service.Dispose();
        }

        #endregion SetUp / TearDown

        #region Tests

        [Test]
        public void GetAllCars()
        {
            var results1 = this._service.GetAllCars1();
            var results2 = this._service.GetAllCars2();

            results1.Count.Should().Be(results2.Count);
        }

        [Test]
        public void GetMaxMinPricesByManufacturer()
        {
            var results1 = this._service.GetMaxMinMinPricesByManufacturer1();
            var results2 = this._service.GetMaxMinMinPricesByManufacturer2();

            results1.Count.Should().Be(results2.Count);
        }

        [Test]
        public void GetMaxMinPricesByManufacturerName()
        {
            var results1 = this._service.GetMaxMinMinPricesByManufacturerName1();
            var results2 = this._service.GetMaxMinMinPricesByManufacturerName2();

            results1.Count.Should().Be(results2.Count);
        }

        [Test]
        public void GetMaxMinPricesByManufacturerNameWithYear()
        {
            var results1 = this._service.GetMaxMinMinPricesByManufacturerNameWithYear1();
            var results2 = this._service.GetMaxMinMinPricesByManufacturerNameWithYear2();

            results1.Count.Should().Be(results2.Count);
        }

        [Test]
        public void GetMaxMinPricesByManufacturerNameWithYearMoreThanOne()
        {
            var results1 = this._service.GetMaxMinMinPricesByManufacturerNameWithYearMoreThanOne1();
            var results2 = this._service.GetMaxMinMinPricesByManufacturerNameWithYearMoreThanOne2();

            results1.Count.Should().Be(results2.Count);
        }

        #endregion Tests
    }
}


text:
class Profile;

namespace bookmarks {
class BookmarkNode;
struct BookmarkNodeData;
}

namespace content {
class WebContents;
}

namespace ui {
class OSExchangeData;
}

namespace chrome {

// Callback for implementing a system drag based on gathered bookmark drag data.
// Used in testing.
using DoBookmarkDragCallback =
    base::OnceCallback<void(std::unique_ptr<ui::OSExchangeData> drag_data,
                            gfx::NativeView native_view,
                            ui::mojom::DragEventSource source,
                            gfx::Point start_point,
                            int operation)>;

struct BookmarkDragParams {
  BookmarkDragParams(std::vector<const bookmarks::BookmarkNode*> nodes,
                     int drag_node_index,
                     content::WebContents* web_contents,
                     ui::mojom::DragEventSource source,
                     gfx::Point start_point);
  ~BookmarkDragParams();

  // The bookmark nodes to be dragged.
  std::vector<const bookmarks::BookmarkNode*> nodes;

  // The index of the main dragged node.
  int drag_node_index;

  // The web contents that initiated the drag.
  raw_ptr<content::WebContents> web_contents;

  // The source of the drag.
  ui::mojom::DragEventSource source;

  // The point the drag started.
  gfx::Point start_point;
};

// Starts the process of dragging a folder of bookmarks.
void DragBookmarks(Profile* profile, const BookmarkDragParams& params);

void DragBookmarksForTest(Profile* profile,
                          const BookmarkDragParams& params,
                          DoBookmarkDragCallback do_drag_callback);

// Drops the bookmark nodes that are in |data| onto |parent_node| at |index|.
// |copy| indicates the source operation: if true then the bookmarks in |data|
// are copied, otherwise they are moved if they belong to the same |profile|.
// Returns the drop type used.
ui::mojom::DragOperation DropBookmarks(
    Profile* profile,
    const bookmarks::BookmarkNodeData& data,
    const bookmarks::BookmarkNode* parent_node,
    size_t index,
    bool copy);

}  // namespace chrome

#endif  // CHROME_BROWSER_UI_BOOKMARKS_BOOKMARK_DRAG_DROP_H_


text:
WScript.Echo('hello');
var a = WScript.GetWorkingSet();
WScript.Echo("workingset = " + a.workingSet);
WScript.Echo("maxworkingset = " + a.maxWorkingSet);
WScript.Echo("pagefaultcount = " + a.pageFault);
WScript.Echo("private usage = " + a.privateUsage);

function print(obj, name)
{
  WScript.Echo("print object " + name);
  for (i in obj)
  {
    WScript.Echo(i + ' = ' + obj[i]);
  }
}

var c = Debug.getHostInfo();
print(c, "hostinfo");

var d = Debug.getMemoryInfo();
for (i in d)
{
print(d[i], i);
}

var b = Debug.getWorkingSet();
WScript.Echo("workingset = " + b.workingSet);
WScript.Echo("maxworkingset = " + b.maxWorkingSet);
WScript.Echo("pagefaultcount = " + b.pageFault);
WScript.Echo("private usage = " + b.privateUsage);


text:
/**
 * Generate Release
 * Written by Kevin Gravier <kevin@mrkmg.com>
 * MIT License 2018
 */

import Chai = require("chai");
import * as childProcess from "child_process";
import {SinonStub, stub} from "sinon";
import {GitCommands} from "../../../src/lib/GitCommands";
import {setupGitFlowTestRepo} from "../../helpers/setupTestRepo";
import {path as tempPath} from "temp";
import * as rimraf from "rimraf";
// tslint:disable-next-line:no-var-requires
Chai.use(require("chai-as-promised"));
const assert = Chai.assert;

describe("GitCommands - Git Flow", () => {
    let settings: any;
    let spawnSyncStub: SinonStub;
    let gitCommands: GitCommands;
    let startingDir: string;
    let tmpPath: string;

    before(() => {
        settings = {
            currentVersion: "test_current_version",
            nextVersion: "test_next_version",
            releaseMessage: "test_release_message",
            remote: "test_remote",
        };
        startingDir = process.cwd();
        tmpPath = tempPath();
        setupGitFlowTestRepo(tmpPath);
        spawnSyncStub = stub(childProcess, "spawnSync").callsFake(() => ({status: 0}));
    });

    beforeEach(() => {
        gitCommands = new GitCommands(settings);
    });

    afterEach(() => {
        spawnSyncStub.resetHistory();
    });

    after((cb) => {
        spawnSyncStub.restore();
        process.chdir(startingDir);
        rimraf(tmpPath, cb);
    });

    it("pull", () => {
        gitCommands.pull();

        assert.deepEqual(spawnSyncStub.args[0][1], ["fetch", "test_remote"]);
        assert.deepEqual(spawnSyncStub.args[1][1], ["checkout", "develop"]);
        assert.deepEqual(spawnSyncStub.args[2][1], ["pull", "test_remote", "develop", "--rebase"]);
        assert.deepEqual(spawnSyncStub.args[3][1], ["checkout", "master"]);
        assert.deepEqual(spawnSyncStub.args[4][1], ["reset", "--hard", "test_remote/master"]);
    });

    it("push", () => {
        gitCommands.push();
        assert.deepEqual(spawnSyncStub.args[0][1], ["push", "test_remote", "develop"]);
        assert.deepEqual(spawnSyncStub.args[1][1], ["push", "test_remote", "master"]);
        assert.deepEqual(spawnSyncStub.args[2][1], ["push", "test_remote", "--tags"]);
    });

    it("reset", () => {
        gitCommands.reset();
        assert.deepEqual(spawnSyncStub.args[0][1], ["checkout", "develop"]);
        assert.deepEqual(spawnSyncStub.args[1][1], ["reset", "--hard", "HEAD"]);
        assert.deepEqual(spawnSyncStub.args[2][1], ["branch", "-D", "release/test_next_version"]);
    });

    it("start", () => {
        gitCommands.start();
        assert.deepEqual(spawnSyncStub.args[0][1], ["checkout", "develop"]);
        assert.deepEqual(spawnSyncStub.args[1][1], ["flow", "release", "start", "test_next_version"]);
    });

    it("commit", () => {
        gitCommands.commit(["test_file"]);
        assert.deepEqual(spawnSyncStub.args[1][1], ["add", "test_file"]);
        assert.deepEqual(spawnSyncStub.args[2][1], ["commit", "-m", "test_release_message"]);
    });

    it("finish", () => {
        gitCommands.isAvh = false;
        gitCommands.finish();
        assert.deepEqual(spawnSyncStub.args[0][1], [
            "flow", "release", "finish", "-m", "test_release_message", "test_next_version",
        ]);
    });
});


text:
            Title
            Date
            Url
            Authors
            Categories

            {{article.Title}}
            {{article.PublicationDate}}
            Link
            {{formatAuthors(article)}}
            {{formatCategories(article)}}


text:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory android:title="MQTT details">

        <EditTextPreference
            android:defaultValue=""
            android:key="mqtt_broker_address"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="MQTT broker address" />

        <EditTextPreference
            android:defaultValue="1883"
            android:key="mqtt_broker_port"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="MQTT broker port"
            android:inputType="number" />

        <SwitchPreference
            android:defaultValue="true"
            android:key="mqtt_authentication_switch"
            android:title="Use MQTT authentication" />

        <EditTextPreference
            android:defaultValue=""
            android:key="mqtt_username"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="MQTT username"
            android:dependency="mqtt_authentication_switch" />

        <EditTextPreference
            android:defaultValue=""
            android:key="mqtt_password"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="MQTT password"
            android:inputType="textPassword"
            android:dependency="mqtt_authentication_switch" />

        <SwitchPreference
            android:defaultValue="false"
            android:key="mqtt_autoconnect_switch"
            android:title="Persistent MQTT connection" />
    </PreferenceCategory>

    <PreferenceCategory android:title="Homie details">

        <EditTextPreference
            android:defaultValue="devices/"
            android:key="homie_base_topic"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="Homie base topic" />

        <SwitchPreference
            android:defaultValue="false"
            android:key="ota_switch"
            android:title="Enable OTA" />

        <EditTextPreference
            android:defaultValue=""
            android:key="ota_host"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="OTA server host"
            android:dependency="ota_switch" />

        <EditTextPreference
            android:defaultValue="80"
            android:key="ota_port"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="OTA server port"
            android:inputType="number"
            android:dependency="ota_switch" />

        <EditTextPreference
            android:defaultValue="/ota"
            android:key="ota_path"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="OTA HTTP path"
            android:dependency="ota_switch" />

    </PreferenceCategory>

    <PreferenceCategory android:title="Default network details">

        <EditTextPreference
            android:defaultValue=""
            android:key="wifi_ssid"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="Wifi network name" />

        <EditTextPreference
            android:defaultValue=""
            android:key="wifi_password"
            android:maxLines="1"
            android:selectAllOnFocus="true"
            android:singleLine="true"
            android:title="Wifi password"
            android:inputType="textPassword" />
    </PreferenceCategory>

</PreferenceScreen>


text:
<title>Отказ в доступе.</title>
<META http-equiv=Content-Type content="text/html; charset=utf-8">

BgColor" text="$this->TextColor" link="$this->LinkColor" vlink="$this->VlinkColor" alink="$this->LinkColor">

<LINK href="javascript/style$this->browser.css" rel="stylesheet" type="text/css">

Имя пользователя $var['user'] зарезервировано

Учетная запись которую Вы пытаетесь использовать зарезервирована. Вернитесь назад и попытайтесь позднее.

Выберите другое имя пользователя из других символов.

Спросите у Администратора об возобновлении пользования зарезервированных имен пользователя в настройках WebAdmin


text:
(function() {

  "use strict";

  angular
    .module('ngClassifieds')
    .controller('classifiedsController', function($scope, $mdToast, $mdSidenav, $mdDialog, $state, $stateParams, classifiedsFactory) {

      var vm = this;

      vm.openSidebar = openSidebar;
      vm.editClassified = editClassified;
      vm.deleteClassified = deleteClassified;
      vm.showSearchBar = false;
      vm.showFilters = false;

      classifiedsFactory.getClassifieds().then(function(data) {
        vm.classifieds = data.data;
        vm.categories = getCategories(vm.classifieds);
      });

      $scope.$on('newClassified', function(event, data) {
        data.id = vm.classifieds.length + 1;
        vm.classifieds.push(data);
        showToast('Classified Saved');
      });

      $scope.$on('editSaved', function(event, message) {
        showToast(message);
      });

      vm.sidebarTitle;

      function showToast(message) {
        $mdToast.show(
          $mdToast.simple()
            .content(message)
            .position('top, right')
            .hideDelay(3000)
        );
      }

      function openSidebar() {
        vm.sidebarTitle = 'Add a Classified';
        $state.go('classifieds.new');
      }

      function editClassified(classified) {
        vm.editing = true;
        vm.sidebarTitle = 'Edit Classified';
        vm.classified = classified;
        $state.go('classifieds.edit', { id: classified.id, classified: classified });
      }

      function deleteClassified(event, classified) {
        var confirm = $mdDialog.confirm()
            .title('Are you sure you want to delete ' + classified.title + '?')
            .targetEvent(event)
            .ok('Yes')
            .cancel('No');
        $mdDialog.show(confirm).then(function() {
          console.log(event);
          var index = vm.classifieds.indexOf(classified);
          vm.classifieds.splice(index, 1);
          showToast('Classified Deleted');
        }, function() {
          vm.status = classified.title + ' is still here.';
        });
      }

      function getCategories(classifieds) {

        var categories = [];

        angular.forEach(classifieds, function(ad) {
          angular.forEach(ad.categories, function(category) {
            categories.push(category);
          });
        });

        return _.uniq(categories);
      }

    });

})();


text:
<!--
  Copyright (C) FuseSource, Inc.
  http://fusesource.com

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>io.fabric8</groupId>
    <artifactId>fabric-examples</artifactId>
    <version>1.0.0.redhat-379</version>
  </parent>

  <groupId>org.fusesource.examples</groupId>
  <artifactId>fabric-camel-eca</artifactId>
  <packaging>bundle</packaging>

  <name>[TODO]Fabric8 :: Example :: Camel ECA</name>

  <properties>
    <felix-plugin.version>2.1.0</felix-plugin.version>
    <fuse.osgi.export>org.fusesource.example.*;-noimport:=true</fuse.osgi.export>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.fusesource.eca</groupId>
      <artifactId>eca-core</artifactId>
      <version>1.0.0.redhat-379</version>
    </dependency>

    <dependency>
      <groupId>org.apache.camel</groupId>
      <artifactId>camel-spring</artifactId>
      <version>${camel-version}</version>
    </dependency>

    <!-- logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j-version}</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j-version}</version>
    </dependency>

  </dependencies>

  <build>
    <defaultGoal>install</defaultGoal>

    <plugins>
      <!-- allows the route to be ran via 'mvn camel:run' -->
      <plugin>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-maven-plugin</artifactId>
        <version>${camel-version}</version>
      </plugin>

      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>${felix-plugin.version}</version>
      </plugin>

    </plugins>

  </build>

</project>


text:
var AwesomeAngularMVCApp = angular.module('AwesomeAngularMVCApp', []);

AwesomeAngularMVCApp.controller('LandingPageController', LandingPageController);


text:
/*
 * This file is generated by jOOQ.
 */
package com.rpkit.stores.bukkit.database.jooq.rpkit.tables;

import com.rpkit.stores.bukkit.database.jooq.rpkit.Indexes;
import com.rpkit.stores.bukkit.database.jooq.rpkit.Keys;
import com.rpkit.stores.bukkit.database.jooq.rpkit.Rpkit;
import com.rpkit.stores.bukkit.database.jooq.rpkit.tables.records.RpkitConsumableStoreItemRecord;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Index;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.11.5"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class RpkitConsumableStoreItem extends TableImpl<RpkitConsumableStoreItemRecord> {

    private static final long serialVersionUID = -212083527;

    /**
     * The reference instance of rpkit.rpkit_consumable_store_item
     */
    public static final RpkitConsumableStoreItem RPKIT_CONSUMABLE_STORE_ITEM = new RpkitConsumableStoreItem();

    /**
     * The class holding records for this type
     */
    @Override
    public Class<RpkitConsumableStoreItemRecord> getRecordType() {
        return RpkitConsumableStoreItemRecord.class;
    }

    /**
     * The column rpkit.rpkit_consumable_store_item.id.
     */
    public final TableField<RpkitConsumableStoreItemRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false).identity(true), this, "");

    /**
     * The column rpkit.rpkit_consumable_store_item.store_item_id.
     */
    public final TableField<RpkitConsumableStoreItemRecord, Integer> STORE_ITEM_ID = createField("store_item_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");

    /**
     * The column rpkit.rpkit_consumable_store_item.uses.
     */
    public final TableField<RpkitConsumableStoreItemRecord, Integer> USES = createField("uses", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");

    /**
     * Create a rpkit.rpkit_consumable_store_item table reference
     */
    public RpkitConsumableStoreItem() {
        this(DSL.name("rpkit_consumable_store_item"), null);
    }

    /**
     * Create an aliased rpkit.rpkit_consumable_store_item table reference
     */
    public RpkitConsumableStoreItem(String alias) {
        this(DSL.name(alias), RPKIT_CONSUMABLE_STORE_ITEM);
    }

    /**
     * Create an aliased rpkit.rpkit_consumable_store_item table reference
     */
    public RpkitConsumableStoreItem(Name alias) {
        this(alias, RPKIT_CONSUMABLE_STORE_ITEM);
    }

    private RpkitConsumableStoreItem(Name alias, Table<RpkitConsumableStoreItemRecord> aliased) {
        this(alias, aliased, null);
    }

    private RpkitConsumableStoreItem(Name alias, Table<RpkitConsumableStoreItemRecord> aliased, Field<?>[] parameters) {
        super(alias, null, aliased, parameters, DSL.comment(""));
    }

    public <O extends Record> RpkitConsumableStoreItem(Table<O> child, ForeignKey<O, RpkitConsumableStoreItemRecord> key) {
        super(child, key, RPKIT_CONSUMABLE_STORE_ITEM);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Schema getSchema() {
        return Rpkit.RPKIT;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Index> getIndexes() {
        return Arrays.<Index>asList(Indexes.RPKIT_CONSUMABLE_STORE_ITEM_PRIMARY);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Identity<RpkitConsumableStoreItemRecord, Integer> getIdentity() {
        return Keys.IDENTITY_RPKIT_CONSUMABLE_STORE_ITEM;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UniqueKey<RpkitConsumableStoreItemRecord> getPrimaryKey() {
        return Keys.KEY_RPKIT_CONSUMABLE_STORE_ITEM_PRIMARY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<UniqueKey<RpkitConsumableStoreItemRecord>> getKeys() {
        return Arrays.<UniqueKey<RpkitConsumableStoreItemRecord>>asList(Keys.KEY_RPKIT_CONSUMABLE_STORE_ITEM_PRIMARY);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public RpkitConsumableStoreItem as(String alias) {
        return new RpkitConsumableStoreItem(DSL.name(alias), this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public RpkitConsumableStoreItem as(Name alias) {
        return new RpkitConsumableStoreItem(alias, this);
    }

    /**
     * Rename this table
     */
    @Override
    public RpkitConsumableStoreItem rename(String name) {
        return new RpkitConsumableStoreItem(DSL.name(name), null);
    }

    /**
     * Rename this table
     */
    @Override
    public RpkitConsumableStoreItem rename(Name name) {
        return new RpkitConsumableStoreItem(name, null);
    }
}


text:
from __future__ import print_function
import os, sys
import numpy as np
import progressbar

def readMatrix(embeddingFile):
    print('reading {} ...'.format(embeddingFile))
    embeddings = np.loadtxt(embeddingFile)
    return embeddings

def readMapping(idMappingFile):
    print('reading id mapping from {} ...'.format(idMappingFile))
    revDict = {}
    with open(idMappingFile) as fileHandler:
        numLines = fileHandler.readline()
        numLines = int(numLines)

        for line in fileHandler:
            arr = line.strip().split()
            entityName, entityID = arr[0], int(arr[1])
            revDict[entityID] = entityName
    return revDict

def row2str(row):
    line = ''
    for elem in row:
        line += '{} '.format(str(elem))
    line = line.rstrip()
    return line

def writeEmbeddings(embeddings, mapping, outputFilePath):
    num_entities, dimension = embeddings.shape
    print('writing embedding out ...' )
    num_entity = len(embeddings)
    with open(outputFilePath, 'w') as fileHandler:
        print('{} {}'.format(num_entities, dimension), file=fileHandler)
        counter = 0
        bar = progressbar.ProgressBar(maxval=num_entity,
                    widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])
        bar.start()

        for row in embeddings:
            entityName = mapping[counter]
            line = row2str(row)
            counter += 1
            print('{} {}'.format(entityName, line), file=fileHandler)
            bar.update(counter)
        bar.finish()
    print('done writing files ...')

if __name__ == '__main__':

    if len(sys.argv) != 4:
        print('usage: python3 transform.py [embedding file] [entity id mapping] [output file path]')
        exit(1)

    embeddingFile, idMappingFile, outputFilePath = sys.argv[1:]

    embeddings = readMatrix(embeddingFile)
    idMapping = readMapping(idMappingFile)
    writeEmbeddings(embeddings, idMapping, outputFilePath)


text:
//
//  WPError.h
//  WePay
//
//  Created by Chaitanya Bagaria on 12/22/14.
//  Copyright (c) 2014 WePay. All rights reserved.
//

#import <Foundation/Foundation.h>
/** \file WPError.h
 * \brief WPError.h serves as documentation for all errors surfaced by the WePay iOS SDK.
 *
 * When errors occur, the WePay iOS SDK returns NSError instances to delegate methods.
 * Each error instance has the following components:
 * - [error code] gives the integer code corresponding with the error
 * - [error domain] gives the domain that the error belongs to
 * - [error userInfo] gives a dictionary with some more useful info, which can be accessed with the keys kWPErrorCategoryKey and NSLocalizedDescriptionKey
 *
 * The WePay iOS SDK can return errors in various error domains:
 * - WePay server API errors are in the \ref kWPErrorAPIDomain
 * - Errors generated by the SDK itself are in the \ref kWPErrorSDKDomain
 * - System errors generated by iOS are passed through as-is, for example in the NSURLErrorDomain
 *
 * See the \ref WPErrorCode section for more details about error codes.
 */

#pragma mark - WPError constants.

/**
 *  The NSError domain of all errors surfaced by the WePay iOS SDK that were returned by the WePay API.
 *  For a full list of error codes in the \ref kWPErrorAPIDomain, visit https://www.wepay.com/developer/reference/errors
 */
FOUNDATION_EXPORT NSString * const kWPErrorAPIDomain;

/**
 *  The NSError domain of all errors returned by the WePay iOS SDK itself.
 *  For a full list of error codes in the \ref kWPErrorSDKDomain, look at \ref WPErrorCode.
 */
FOUNDATION_EXPORT NSString * const kWPErrorSDKDomain;

/**
 *  The key used in the NSError's userInfo dictionary to return the error category.
 */
FOUNDATION_EXPORT NSString * const kWPErrorCategoryKey;

/**
 *  The value used in the NSError's userInfo dictionary to return the "none" error category.
 */
FOUNDATION_EXPORT NSString * const kWPErrorCategoryNone;

/**
 *  The value used in the NSError's userInfo dictionary to return the "card reader" error category.
 */
FOUNDATION_EXPORT NSString * const kWPErrorCategoryCardReader;

#pragma mark - Error Codes.

/**
 *  Error codes for NSErrors surfaced by the WePay iOS SDK in the \ref kWPErrorSDKDomain.
 *  For a full list of error codes in the \ref kWPErrorAPIDomain, visit https://www.wepay.com/developer/reference/errors
 */
typedef enum WPErrorCode {
    /**
     *  -10000 Unknown error.
     */
    WPErrorUnknown              = -10000,

    // -10001 to -10014 are reserved for legacy error codes

    /**
     *  -10015 No data returned by the API call.
     */
    WPErrorNoDataReturned       = -10015,

    /**
     *  -10016 General error reported by the card reader - usually due to a bad swipe.
     */
    WPErrorCardReaderGeneralError   = -10016,

    /**
     *  -10017 Error while initializing the card reader.
     */
    WPErrorCardReaderInitialization = -10017,

    /**
     *  -10018 Timeout occurred while waiting for card.
     */
    WPErrorCardReaderTimeout        = -10018,

    /**
     *  -10019 Special error reported by card reader - very rare.
     */
    WPErrorCardReaderStatusError    = -10019,

    /**
     *  -10020 Invalid signature image.
     */
    WPErrorInvalidSignatureImage    = -10020,

    /**
     *  -10021 Name not found.
     */
    WPErrorNameNotFound         = -10021,

    /**
     *  -10022 Invalid card data.
     */
    WPErrorInvalidCardData = -10022,

    /**
     *  -10023 Card not supported.
     */
    WPErrorCardNotSupported = -10023,

    /**
     *  -10024 EMV transaction error.
     */
    WPErrorEMVTransactionError = -10024,

    /**
     *  -10025 Invalid application ID.
     */
    WPErrorInvalidApplicationId = -10025,

    /**
     *  -10026 Declined by card.
     */
    WPErrorDeclinedByCard = -10026,

    /**
     *  -10027 Card blocked.
     */
    WPErrorCardBlocked = -10027,

    /**
     *  -10028 Declined by issuer.
     */
    WPErrorDeclinedByIssuer = -10028,

    /**
     *  -10029 Issuer unreachable.
     */
    WPErrorIssuerUnreachable = -10029,

    /**
     *  -10030 Invalid auth info.
     */
    WPErrorInvalidAuthInfo = -10030,

    /**
     *  -10031 Auth info not provided.
     */
    WPErrorAuthInfoNotProvided = -10031,

} WPErrorCode;

#pragma mark - User facing messages.

/**
 *  The localizable user facing message for WPErrorUnknown, that can be retrieved by calling [error localizedDescription].
 */
#define WPUnexpectedErrorMessage NSLocalizedStringFromTable(@"There was an unexpected error.", @"WePay", @"There was an unexpected error.");

/**
 *  The localizable user facing message for WPErrorNoDataReturned, that can be retrieved by calling [error localizedDescription].
 */
#define WPNoDataReturnedErrorMessage NSLocalizedStringFromTable(@"There was no data returned.", @"WePay",  @"There was no data returned.");

/**
 *  The localizable user facing message for WPErrorCardReaderGeneralError, that can be retrieved by calling [error localizedDescription].
 */
#define WPCardReaderGeneralErrorMessage NSLocalizedStringFromTable(@"Swipe failed due to: (a) uneven swipe speed, (b) fast swipe, (c) slow swipe, or (d) damaged card.", @"WePay",  @"Swipe failed due to: (a) uneven swipe speed, (b) fast swipe, (c) slow swipe, or (d) damaged card.");

/**
 *  The localizable user facing message for WPErrorCardReaderInitialization, that can be retrieved by calling [error localizedDescription].
 */
#define WPCardReaderInitializationErrorMessage NSLocalizedStringFromTable(@"Failed to initialize card reader.", @"WePay",  @"Failed to initialize card reader.");

/**
 *  The localizable user facing message for WPErrorCardReaderTimeout, that can be retrieved by calling [error localizedDescription].
 */
#define WPCardReaderTimeoutErrorMessage NSLocalizedStringFromTable(@"Card reader timed out.", @"WePay",  @"Card reader timed out.");

/**
 *  The localizable user facing message for WPErrorInavlidSignatureImage, that can be retrieved by calling [error localizedDescription].
 */
#define WPSignatureInvalidImageErrorMessage NSLocalizedStringFromTable(@"Inavlid signature image provided.", @"WePay",  @"Inavlid signature image provided.");

/**
 *  The localizable user facing message for WPErrorNameNotFound, that can be retrieved by calling [error localizedDescription].
 */
#define WPNameNotFoundErrorMessage NSLocalizedStringFromTable(@"Name not found.", @"WePay",  @"Name not found.");

/**
 *  The localizable user facing message for WPErrorInvalidCardData, that can be retrieved by calling [error localizedDescription].
 */
#define WPInvalidCardDataErrorMessage NSLocalizedStringFromTable(@"Invalid card data.", @"WePay",  @"Invalid card data.");

/**
 *  The localizable user facing message for WPErrorCardNotSupported, that can be retrieved by calling [error localizedDescription].
 */
#define WPCardNotSupportedErrorMessage NSLocalizedStringFromTable(@"This card is not supported.", @"WePay",  @"This card is not supported.");

/**
 *  The localizable user facing message for WPErrorInvalidApplicationId, that can be retrieved by calling [error localizedDescription].
 */
#define WPInvalidApplicationIdErrorMessage NSLocalizedStringFromTable(@"Invalid application ID selected.", @"WePay",  @"Invalid application ID selected.");

/**
 *  The localizable user facing message for WPErrorDeclinedByCard, that can be retrieved by calling [error localizedDescription].
 */
#define WPDeclinedByCardErrorMessage NSLocalizedStringFromTable(@"The transaction was declined by the card.", @"WePay",  @"The transaction was declined by the card.");

/**
 *  The localizable user facing message for WPErrorCardBlocked, that can be retrieved by calling [error localizedDescription].
 */
#define WPCardBlockedErrorMessage NSLocalizedStringFromTable(@"This card has been blocked.", @"WePay",  @"This card has been blocked.");

/**
 *  The localizable user facing message for WPErrorDeclinedByIssuer, that can be retrieved by calling [error localizedDescription].
 */
#define WPDeclinedByIssuerErrorMessage NSLocalizedStringFromTable(@"The transaction was declined by the issuer bank.", @"WePay",  @"The transaction was declined by the issuer bank.");

/**
 *  The localizable user facing message for WPErrorIssuerUnreachable, that can be retrieved by calling [error localizedDescription].
 */
#define WPIssuerUnreachableErrorMessage NSLocalizedStringFromTable(@"The issuing bank could not be reached.", @"WePay",  @"The issuing bank could not be reached.");

/**
 *  The localizable user facing message for WPErrorInvalidAuthInfo, that can be retrieved by calling [error localizedDescription].
 */
#define WPInvalidAuthInfoErrorMessage NSLocalizedStringFromTable(@"The provided auth info is invalid.", @"WePay",  @"The provided auth info is invalid.");

/**
 *  The localizable user facing message for WPErrorAuthInfoNotProvided, that can be retrieved by calling [error localizedDescription].
 */
#define WPAuthInfoNotProvidedErrorMessage NSLocalizedStringFromTable(@"Auth info was not provided.", @"WePay",  @"Auth info was not provided.");