text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2020 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "txmempool.h"

#include "clientversion.h"
#include "bls/bls_wrapper.h"
#include "evo/deterministicmns.h"
#include "evo/specialtx.h"
#include "evo/providertx.h"
#include "policy/fees.h"
#include "reverse_iterate.h"
#include "streams.h"
#include "timedata.h"
#include "util/system.h"
#include "utilmoneystr.h"
#include "utiltime.h"
#include "version.h"
#include "validation.h"
#include "validationinterface.h"

CTxMemPoolEntry::CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
                                 int64_t _nTime, unsigned int _entryHeight,
                                 bool _spendsCoinbaseOrCoinstake, unsigned int _sigOps) :
     tx(MakeTransactionRef(_tx)), nFee(_nFee), nTime(_nTime), entryHeight(_entryHeight),
     spendsCoinbaseOrCoinstake(_spendsCoinbaseOrCoinstake), sigOpCount(_sigOps)
{
    nTxSize = ::GetSerializeSize(*_tx, PROTOCOL_VERSION);
    nUsageSize = _tx->DynamicMemoryUsage();
    hasZerocoins = _tx->ContainsZerocoins();
    m_isShielded = _tx->IsShieldedTx();

    nCountWithDescendants = 1;
    nSizeWithDescendants = nTxSize;
    nModFeesWithDescendants = nFee;

    feeDelta = 0;

    nCountWithAncestors = 1;
    nSizeWithAncestors = nTxSize;
    nModFeesWithAncestors = nFee;
    nSigOpCountWithAncestors = sigOpCount;
}

void CTxMemPoolEntry::UpdateFeeDelta(int64_t newFeeDelta)
{
    nModFeesWithDescendants += newFeeDelta - feeDelta;
    nModFeesWithAncestors += newFeeDelta - feeDelta;
    feeDelta = newFeeDelta;
}

// Update the given tx for any in-mempool descendants.
// Assumes that setMemPoolChildren is correct for the given tx and all
// descendants.
void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude)
{
    setEntries stageEntries, setAllDescendants;
    stageEntries = GetMemPoolChildren(updateIt);

    while (!stageEntries.empty()) {
        const txiter cit = *stageEntries.begin();
        setAllDescendants.insert(cit);
        stageEntries.erase(cit);
        const setEntries &setChildren = GetMemPoolChildren(cit);
        for (const txiter& childEntry : setChildren) {
            cacheMap::iterator cacheIt = cachedDescendants.find(childEntry);
            if (cacheIt != cachedDescendants.end()) {
                // We've already calculated this one, just add the entries for this set
                // but don't traverse again.
                for (const txiter& cacheEntry : cacheIt->second) {
                    setAllDescendants.insert(cacheEntry);
                }
            } else if (!setAllDescendants.count(childEntry)) {
                // Schedule for later processing
                stageEntries.insert(childEntry);
            }
        }
    }
    // setAllDescendants now contains all in-mempool descendants of updateIt.
    // Update and add to cached descendant map
    int64_t modifySize = 0;
    CAmount modifyFee = 0;
    int64_t modifyCount = 0;
    for (const txiter& cit : setAllDescendants) {
        if (!setExclude.count(cit->GetTx().GetHash())) {
            modifySize += cit->GetTxSize();
            modifyFee += cit->GetModifiedFee();
            modifyCount++;
            cachedDescendants[updateIt].insert(cit);
            // Update ancestor state for each descendant
            mapTx.modify(cit, update_ancestor_state(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCount()));
        }
    }
    mapTx.modify(updateIt, update_descendant_state(modifySize, modifyFee, modifyCount));
}

// vHashesToUpdate is the set of transaction hashes from a disconnected block
// which has been re-added to the mempool.
// for each entry, look for descendants that are outside hashesToUpdate, and
// add fee/size information for such descendants to the parent.
// for each such descendant, also update the ancestor state to include the parent.
void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate)
{
    LOCK(cs);
    // For each entry in vHashesToUpdate, store the set of in-mempool, but not
    // in-vHashesToUpdate transactions, so that we don't have to recalculate
    // descendants when we come across a previously seen entry.
    cacheMap mapMemPoolDescendantsToUpdate;

    // Use a set for lookups into vHashesToUpdate (these entries are already
    // accounted for in the state of their ancestors)
    std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());

    // Iterate in reverse, so that whenever we are looking at at a transaction
    // we are sure that all in-mempool descendants have already been processed.
    // This maximizes the benefit of the descendant cache and guarantees that
    // setMemPoolChildren will be updated, an assumption made in
    // UpdateForDescendants.
    for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {
        // we cache the in-mempool children to avoid duplicate updates
        setEntries setChildren;
        // calculate children from mapNextTx
        txiter it = mapTx.find(hash);
        if (it == mapTx.end()) {
            continue;
        }
        auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
        // First calculate the children, and update setMemPoolChildren to
        // include them, and update their setMemPoolParents to include this tx.
        for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
            const uint256 &childHash = iter->second->GetHash();
            txiter childIter = mapTx.find(childHash);
            assert(childIter != mapTx.end());
            // We can skip updating entries we've encountered before or that
            // are in the block (which are already accounted for).
            if (setChildren.insert(childIter).second && !setAlreadyIncluded.count(childHash)) {
                UpdateChild(it, childIter, true);
                UpdateParent(childIter, it, true);
            }
        }
        UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded);
    }
}

bool CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents /* = true */) const
{
    setEntries parentHashes;
    const auto &tx = entry.GetSharedTx();

    if (fSearchForParents) {
        // Get parents of this transaction that are in the mempool
        // GetMemPoolParents() is only valid for entries in the mempool, so we
        // iterate mapTx to find parents.
        for (unsigned int i = 0; i < tx->vin.size(); i++) {
            txiter piter = mapTx.find(tx->vin[i].prevout.hash);
            if (piter != mapTx.end()) {
                parentHashes.insert(piter);
                if (parentHashes.size() + 1 > limitAncestorCount) {
                    errString = strprintf("too many unconfirmed parents [limit: %u]", limitAncestorCount);
                    return false;
                }
            }
        }
    } else {
        // If we're not searching for parents, we require this to be an
        // entry in the mempool already.
        txiter it = mapTx.iterator_to(entry);
        parentHashes = GetMemPoolParents(it);
    }

    size_t totalSizeWithAncestors = entry.GetTxSize();

    while (!parentHashes.empty()) {
        txiter stageit = *parentHashes.begin();

        setAncestors.insert(stageit);
        parentHashes.erase(stageit);
        totalSizeWithAncestors += stageit->GetTxSize();

        if (stageit->GetSizeWithDescendants() + entry.GetTxSize() > limitDescendantSize) {
            errString = strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantSize);
            return false;
        } else if (stageit->GetCountWithDescendants() + 1 > limitDescendantCount) {
            errString = strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limitDescendantCount);
            return false;
        } else if (totalSizeWithAncestors > limitAncestorSize) {
            errString = strprintf("exceeds ancestor size limit [limit: %u]", limitAncestorSize);
            return false;
        }

        const setEntries & setMemPoolParents = GetMemPoolParents(stageit);
        for (const txiter& phash : setMemPoolParents) {
            // If this is a new ancestor, add it.
            if (setAncestors.count(phash) == 0) {
                parentHashes.insert(phash);
            }
            if (parentHashes.size() + setAncestors.size() + 1 > limitAncestorCount) {
                errString = strprintf("too many unconfirmed ancestors [limit: %u]", limitAncestorCount);
                return false;
            }
        }
    }

    return true;
}

void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
{
    setEntries parentIters = GetMemPoolParents(it);
    // add or remove this tx as a child of each parent
    for (const txiter& piter : parentIters) {
        UpdateChild(piter, it, add);
    }
    const int64_t updateCount = (add ? 1 : -1);
    const int64_t updateSize = updateCount * it->GetTxSize();
    const CAmount updateFee = updateCount * it->GetModifiedFee();
    for (const txiter& ancestorIt : setAncestors) {
        mapTx.modify(ancestorIt, update_descendant_state(updateSize, updateFee, updateCount));
    }
}

void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
{
    int64_t updateCount = setAncestors.size();
    int64_t updateSize = 0;
    CAmount updateFee = 0;
    int updateSigOps = 0;
    for (const txiter& ancestorIt : setAncestors) {
        updateSize += ancestorIt->GetTxSize();
        updateFee += ancestorIt->GetModifiedFee();
        updateSigOps += ancestorIt->GetSigOpCount();
    }
    mapTx.modify(it, update_ancestor_state(updateSize, updateFee, updateCount, updateSigOps));
}

void CTxMemPool::UpdateChildrenForRemoval(txiter it)
{
    const setEntries &setMemPoolChildren = GetMemPoolChildren(it);
    for (const txiter& updateIt : setMemPoolChildren) {
        UpdateParent(updateIt, it, false);
    }
}

void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
{
    // For each entry, walk back all ancestors and decrement size associated with this
    // transaction
    const uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
    if (updateDescendants) {
        // updateDescendants should be true whenever we're not recursively
        // removing a tx and all its descendants, eg when a transaction is
        // confirmed in a block.
        // Here we only update statistics and not data in mapLinks (which
        // we need to preserve until we're finished with all operations that
        // need to traverse the mempool).
        for (const txiter& removeIt : entriesToRemove) {
            setEntries setDescendants;
            CalculateDescendants(removeIt, setDescendants);
            setDescendants.erase(removeIt); // don't update state for self
            int64_t modifySize = -((int64_t)removeIt->GetTxSize());
            CAmount modifyFee = -removeIt->GetModifiedFee();
            int modifySigOps = -removeIt->GetSigOpCount();
            for (const txiter& dit : setDescendants) {
                mapTx.modify(dit, update_ancestor_state(modifySize, modifyFee, -1, modifySigOps));
            }
        }
    }
    for (const txiter& removeIt : entriesToRemove) {
        setEntries setAncestors;
        const CTxMemPoolEntry &entry = *removeIt;
        std::string dummy;
        // Since this is a tx that is already in the mempool, we can call CMPA
        // with fSearchForParents = false.  If the mempool is in a consistent
        // state, then using true or false should both be correct, though false
        // should be a bit faster.
        // However, if we happen to be in the middle of processing a reorg, then
        // the mempool can be in an inconsistent state.  In this case, the set
        // of ancestors reachable via mapLinks will be the same as the set of
        // ancestors whose packages include this transaction, because when we
        // add a new transaction to the mempool in addUnchecked(), we assume it
        // has no children, and in the case of a reorg where that assumption is
        // false, the in-mempool children aren't linked to the in-block tx's
        // until UpdateTransactionsFromBlock() is called.
        // So if we're being called during a reorg, ie before
        // UpdateTransactionsFromBlock() has been called, then mapLinks[] will
        // differ from the set of mempool parents we'd calculate by searching,
        // and it's important that we use the mapLinks[] notion of ancestor
        // transactions as the set of things to update for removal.
        CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
        // Note that UpdateAncestorsOf severs the child links that point to
        // removeIt in the entries for the parents of removeIt.
        UpdateAncestorsOf(false, removeIt, setAncestors);
    }
    // After updating all the ancestor sizes, we can now sever the link between each
    // transaction being removed and any mempool children (ie, update setMemPoolParents
    // for each direct child of a transaction being removed).
    for (const txiter& removeIt : entriesToRemove) {
        UpdateChildrenForRemoval(removeIt);
    }
}

void CTxMemPoolEntry::UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount)
{
    nSizeWithDescendants += modifySize;
    assert(int64_t(nSizeWithDescendants) > 0);
    nModFeesWithDescendants += modifyFee;
    nCountWithDescendants += modifyCount;
    assert(int64_t(nCountWithDescendants) > 0);
}

void CTxMemPoolEntry::UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps)
{
    nSizeWithAncestors += modifySize;
    assert(int64_t(nSizeWithAncestors) > 0);
    nModFeesWithAncestors += modifyFee;
    nCountWithAncestors += modifyCount;
    assert(int64_t(nCountWithAncestors) > 0);
    nSigOpCountWithAncestors += modifySigOps;
    assert(int(nSigOpCountWithAncestors) >= 0);
}

CTxMemPool::CTxMemPool(const CFeeRate& _minReasonableRelayFee) :
        nTransactionsUpdated(0)
{
    _clear();   // lock-free clear

    // Sanity checks off by default for performance, because otherwise
    // accepting transactions becomes O(N^2) where N is the number
    // of transactions in the pool
    nCheckFrequency = 0;

    minerPolicyEstimator = new CBlockPolicyEstimator(_minReasonableRelayFee);
    minReasonableRelayFee = _minReasonableRelayFee;
}

CTxMemPool::~CTxMemPool()
{
    delete minerPolicyEstimator;
}

bool CTxMemPool::isSpent(const COutPoint& outpoint)
{
    LOCK(cs);
    return mapNextTx.count(outpoint);
}

unsigned int CTxMemPool::GetTransactionsUpdated() const
{
    LOCK(cs);
    return nTransactionsUpdated;
}

void CTxMemPool::AddTransactionsUpdated(unsigned int n)
{
    LOCK(cs);
    nTransactionsUpdated += n;
}

void CTxMemPool::addUncheckedSpecialTx(const CTransaction& tx)
{
    if (!tx.IsSpecialTx()) return;

    // Invalid special txes never get this far because transactions should be
    // fully checked by AcceptToMemoryPool() at this point, so we just assume that
    // everything is fine here.
    const uint256& txid = tx.GetHash();
    switch(tx.nType) {
        case CTransaction::TxType::PROREG: {
            ProRegPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            if (!pl.collateralOutpoint.hash.IsNull()) {
                mapProTxRefs.emplace(txid, pl.collateralOutpoint.hash);
                mapProTxCollaterals.emplace(pl.collateralOutpoint, txid);
            }
            mapProTxAddresses.emplace(pl.addr, txid);
            mapProTxPubKeyIDs.emplace(pl.keyIDOwner, txid);
            mapProTxBlsPubKeyHashes.emplace(pl.pubKeyOperator.GetHash(), txid);
            break;
        }

        case CTransaction::TxType::PROUPSERV: {
            ProUpServPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            mapProTxRefs.emplace(pl.proTxHash, txid);
            mapProTxAddresses.emplace(pl.addr, txid);
            break;
        }

        case CTransaction::TxType::PROUPREG: {
            ProUpRegPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            mapProTxRefs.emplace(pl.proTxHash, txid);
            mapProTxBlsPubKeyHashes.emplace(pl.pubKeyOperator.GetHash(), txid);
            break;
        }

        case CTransaction::TxType::PROUPREV: {
            ProUpRevPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            mapProTxRefs.emplace(pl.proTxHash, txid);
            break;
        }

    }
}

bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate)
{
    // Add to memory pool without checking anything.
    // Used by AcceptToMemoryPool(), which DOES do all the appropriate checks.
    LOCK(cs);
    indexed_transaction_set::iterator newit = mapTx.insert(entry).first;
    mapLinks.insert(make_pair(newit, TxLinks()));

    // Update transaction for any feeDelta created by PrioritiseTransaction
    // TODO: refactor so that the fee delta is calculated before inserting
    // into mapTx.
    std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
    if (pos != mapDeltas.end()) {
        const CAmount &delta = pos->second;
        if (delta) {
            mapTx.modify(newit, update_fee_delta(delta));
        }
    }

    // Update cachedInnerUsage to include contained transaction's usage.
    // (When we update the entry for in-mempool parents, memory usage will be
    // further updated.)
    cachedInnerUsage += entry.DynamicMemoryUsage();

    const CTransaction& tx = newit->GetTx();
    std::set<uint256> setParentTransactions;
    if(!tx.HasZerocoinSpendInputs()) {
        for (unsigned int i = 0; i < tx.vin.size(); i++) {
            mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit->GetSharedTx()));
            setParentTransactions.insert(tx.vin[i].prevout.hash);
        }
    }
    // Don't bother worrying about child transactions of this one.
    // Normal case of a new transaction arriving is that there can't be any
    // children, because such children would be orphans.
    // An exception to that is if a transaction enters that used to be in a block.
    // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
    // to clean up the mess we're leaving here.

    // Update ancestors with information about this tx
    for (const uint256& phash : setParentTransactions) {
        txiter pit = mapTx.find(phash);
        if (pit != mapTx.end()) {
            UpdateParent(newit, pit, true);
        }
    }
    UpdateAncestorsOf(true, newit, setAncestors);
    UpdateEntryForAncestors(newit, setAncestors);

    // Save spent nullifiers
    if (tx.IsShieldedTx()) {
        for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
            mapSaplingNullifiers[sd.nullifier] = newit->GetSharedTx();
        }
    }

    nTransactionsUpdated++;
    totalTxSize += entry.GetTxSize();
    minerPolicyEstimator->processTransaction(entry, validFeeEstimate);

    addUncheckedSpecialTx(tx);

    return true;
}

void CTxMemPool::removeUncheckedSpecialTx(const CTransaction& tx)
{
    if (!tx.IsSpecialTx()) return;

    auto eraseProTxRef = [&](const uint256& proTxHash, const uint256& txHash) {
        auto its = mapProTxRefs.equal_range(proTxHash);
        for (auto it = its.first; it != its.second;) {
            if (it->second == txHash) {
                it = mapProTxRefs.erase(it);
            } else {
                ++it;
            }
        }
    };

    const uint256& txid = tx.GetHash();
    switch(tx.nType) {
        case CTransaction::TxType::PROREG: {
            ProRegPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            if (!pl.collateralOutpoint.IsNull()) {
                eraseProTxRef(txid, pl.collateralOutpoint.hash);
            }
            mapProTxCollaterals.erase(pl.collateralOutpoint);
            mapProTxAddresses.erase(pl.addr);
            mapProTxPubKeyIDs.erase(pl.keyIDOwner);
            mapProTxBlsPubKeyHashes.erase(pl.pubKeyOperator.GetHash());
            break;
        }

        case CTransaction::TxType::PROUPSERV: {
            ProUpServPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            eraseProTxRef(pl.proTxHash, txid);
            mapProTxAddresses.erase(pl.addr);
            break;
        }

        case CTransaction::TxType::PROUPREG: {
            ProUpRegPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            eraseProTxRef(pl.proTxHash, txid);
            mapProTxBlsPubKeyHashes.erase(pl.pubKeyOperator.GetHash());
            break;
        }

        case CTransaction::TxType::PROUPREV: {
            ProUpRevPL pl;
            bool ok = GetTxPayload(tx, pl);
            assert(ok);
            eraseProTxRef(pl.proTxHash, txid);
            break;
        }

    }
}

void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
{
    if (reason != MemPoolRemovalReason::BLOCK) {
        // Notify clients that a transaction has been removed from the mempool
        // for any reason except being included in a block. Clients interested
        // in transactions included in blocks can subscribe to the BlockConnected
        // notification.
        GetMainSignals().TransactionRemovedFromMempool(it->GetSharedTx(), reason);
    }

    AssertLockHeld(cs);
    const CTransaction& tx = it->GetTx();
    for (const CTxIn& txin : tx.vin)
        mapNextTx.erase(txin.prevout);
    // Remove spent nullifiers
    if (tx.IsShieldedTx()) {
        for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
            mapSaplingNullifiers.erase(sd.nullifier);
        }
    }

    removeUncheckedSpecialTx(tx);

    totalTxSize -= it->GetTxSize();
    cachedInnerUsage -= it->DynamicMemoryUsage();
    cachedInnerUsage -= memusage::DynamicUsage(mapLinks[it].parents) + memusage::DynamicUsage(mapLinks[it].children);
    mapLinks.erase(it);
    mapTx.erase(it);
    nTransactionsUpdated++;
    minerPolicyEstimator->removeTx(tx.GetHash());
}

// Calculates descendants of entry that are not already in setDescendants, and adds to
// setDescendants. Assumes entryit is already a tx in the mempool and setMemPoolChildren
// is correct for tx and all descendants.
// Also assumes that if an entry is in setDescendants already, then all
// in-mempool descendants of it are already in setDescendants as well, so that we
// can save time by not iterating over those entries.
void CTxMemPool::CalculateDescendants(txiter entryit, setEntries &setDescendants)
{
    setEntries stage;
    if (setDescendants.count(entryit) == 0) {
        stage.insert(entryit);
    }
    // Traverse down the children of entry, only adding children that are not
    // accounted for in setDescendants already (because those children have either
    // already been walked, or will be walked in this iteration).
    while (!stage.empty()) {
        txiter it = *stage.begin();
        setDescendants.insert(it);
        stage.erase(it);

        const setEntries &setChildren = GetMemPoolChildren(it);
        for (const txiter& childiter : setChildren) {
            if (!setDescendants.count(childiter)) {
                stage.insert(childiter);
            }
        }
    }
}

void CTxMemPool::removeRecursive(const CTransaction& origTx, MemPoolRemovalReason reason)
{
    // Remove transaction from memory pool
    {
        LOCK(cs);
        setEntries txToRemove;
        txiter origit = mapTx.find(origTx.GetHash());
        if (origit != mapTx.end()) {
            txToRemove.insert(origit);
        } else {
            // When recursively removing but origTx isn't in the mempool
            // be sure to remove any children that are in the pool. This can
            // happen during chain re-orgs if origTx isn't re-accepted into
            // the mempool for any reason.
            for (unsigned int i = 0; i < origTx.vout.size(); i++) {
                auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
                if (it == mapNextTx.end())
                    continue;
                txiter nextit = mapTx.find(it->second->GetHash());
                assert(nextit != mapTx.end());
                txToRemove.insert(nextit);
            }
        }
        setEntries setAllRemoves;
        for (const txiter& it : txToRemove) {
            CalculateDescendants(it, setAllRemoves);
        }

        RemoveStaged(setAllRemoves, false, reason);
    }
}

void CTxMemPool::removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags)
{
    AssertLockHeld(cs_main);
    // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
    LOCK(cs);
    setEntries txToRemove;
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
        const CTransactionRef& tx = it->GetSharedTx();
        if (!CheckFinalTx(tx, flags)) {
            txToRemove.insert(it);
        } else if (it->GetSpendsCoinbaseOrCoinstake()) {
            for (const CTxIn& txin : tx->vin) {
                indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
                if (it2 != mapTx.end())
                    continue;
                const Coin &coin = pcoins->AccessCoin(txin.prevout);
                if (nCheckFrequency != 0) assert(!coin.IsSpent());
                if (coin.IsSpent() || ((coin.IsCoinBase() || coin.IsCoinStake()) && ((signed long)nMemPoolHeight) - coin.nHeight < (signed long)Params().GetConsensus().nCoinbaseMaturity)) {
                    txToRemove.insert(it);
                    break;
                }
            }
        }
    }
    setEntries setAllRemoves;
    for (txiter it : txToRemove) {
        CalculateDescendants(it, setAllRemoves);
    }
    RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
}

void CTxMemPool::removeWithAnchor(const uint256& invalidRoot)
{

    // If a block is disconnected from the tip, and the root changed,
    // we must invalidate transactions from the mempool which spend
    // from that root -- almost as though they were spending coinbases
    // which are no longer valid to spend due to coinbase maturity.
    LOCK(cs);
    std::list<CTransaction> transactionsToRemove;
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
        const CTransaction& tx = it->GetTx();
        if (!tx.IsShieldedTx()) continue;
        for (const auto& sd : tx.sapData->vShieldedSpend) {
            if (sd.anchor == invalidRoot) {
                transactionsToRemove.emplace_back(tx);
                break;
            }
        }
    }
    for (const CTransaction& tx : transactionsToRemove) {
        removeRecursive(tx);
    }
}

void CTxMemPool::removeConflicts(const CTransaction& tx)
{
    // Remove transactions which depend on inputs of tx, recursively
    std::list<CTransaction> result;
    LOCK(cs);
    for (const CTxIn& txin : tx.vin) {
        auto it = mapNextTx.find(txin.prevout);
        if (it != mapNextTx.end()) {
            const CTransaction& txConflict = *it->second;
            if (txConflict != tx) {
                removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
                ClearPrioritisation(txConflict.GetHash());
            }
        }
    }
    // Remove txes with conflicting nullifier
    if (tx.IsShieldedTx()) {
        for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
            const auto& it = mapSaplingNullifiers.find(sd.nullifier);
            if (it != mapSaplingNullifiers.end()) {
                const CTransaction& txConflict = *it->second;
                if (txConflict != tx) {
                    removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
                    ClearPrioritisation(txConflict.GetHash());
                }
            }
        }
    }
}

void CTxMemPool::removeProTxPubKeyConflicts(const CTransaction& tx, const CKeyID& keyId)
{
    if (mapProTxPubKeyIDs.count(keyId)) {
        const uint256& conflictHash = mapProTxPubKeyIDs.at(keyId);
        if (conflictHash != tx.GetHash() && mapTx.count(conflictHash)) {
            removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
        }
    }
}

void CTxMemPool::removeProTxPubKeyConflicts(const CTransaction& tx, const CBLSPublicKey& pubKey)
{
    if (mapProTxBlsPubKeyHashes.count(pubKey.GetHash())) {
        const uint256& conflictHash = mapProTxBlsPubKeyHashes.at(pubKey.GetHash());
        if (conflictHash != tx.GetHash() && mapTx.count(conflictHash)) {
            removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
        }
    }
}

void CTxMemPool::removeProTxCollateralConflicts(const CTransaction &tx, const COutPoint &collateralOutpoint)
{
    if (mapProTxCollaterals.count(collateralOutpoint)) {
        const uint256& conflictHash = mapProTxCollaterals.at(collateralOutpoint);
        if (conflictHash != tx.GetHash() && mapTx.count(conflictHash)) {
            removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
        }
    }
}

void CTxMemPool::removeProTxReferences(const uint256& proTxHash, MemPoolRemovalReason reason)
{
    // Remove TXs that refer to a certain MN
    while (true) {
        auto it = mapProTxRefs.find(proTxHash);
        if (it == mapProTxRefs.end()) {
            break;
        }
        auto conflictIt = mapTx.find(it->second);
        if (conflictIt != mapTx.end()) {
            removeRecursive(conflictIt->GetTx(), reason);
        } else {
            // Should not happen as we track referencing TXs in addUnchecked/removeUnchecked.
            // But lets be on the safe side and not run into an endless loop...
            LogPrint(BCLog::MEMPOOL, "%s: ERROR: found invalid TX ref in mapProTxRefs, proTxHash=%s, txHash=%s\n", __func__, proTxHash.ToString(), it->second.ToString());
            mapProTxRefs.erase(it);
        }
    }
}

void CTxMemPool::removeProTxSpentCollateralConflicts(const CTransaction &tx)
{
    auto mnList = deterministicMNManager->GetListAtChainTip();
    for (const auto& in : tx.vin) {
        auto collateralIt = mapProTxCollaterals.find(in.prevout);
        if (collateralIt != mapProTxCollaterals.end()) {
            // These are not yet mined ProRegTxs
            removeProTxReferences(collateralIt->second, MemPoolRemovalReason::CONFLICT);
        }
        auto dmn = mnList.GetMNByCollateral(in.prevout);
        if (dmn) {
            // These are updates refering to a mined ProRegTx
            removeProTxReferences(dmn->proTxHash, MemPoolRemovalReason::CONFLICT);
        }
    }
}

void CTxMemPool::removeProTxConflicts(const CTransaction &tx)
{
    removeProTxSpentCollateralConflicts(tx);

    if (!tx.IsSpecialTx()) return;

    const uint256& txid = tx.GetHash();
    switch(tx.nType) {
        case CTransaction::TxType::PROREG: {
            ProRegPL pl;
            if (!GetTxPayload(tx, pl)) {
                LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s", __func__, tx.ToString());
                return;
            }
            if (mapProTxAddresses.count(pl.addr)) {
                const uint256& conflictHash = mapProTxAddresses.at(pl.addr);
                if (conflictHash != txid && mapTx.count(conflictHash)) {
                    removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
                }
            }
            removeProTxPubKeyConflicts(tx, pl.keyIDOwner);
            removeProTxPubKeyConflicts(tx, pl.pubKeyOperator);
            if (!pl.collateralOutpoint.hash.IsNull()) {
                removeProTxCollateralConflicts(tx, pl.collateralOutpoint);
            }
            break;
        }

        case CTransaction::TxType::PROUPSERV: {
            ProUpServPL pl;
            if (!GetTxPayload(tx, pl)) {
                LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s", __func__, tx.ToString());
                return;
            }
            if (mapProTxAddresses.count(pl.addr)) {
                const uint256& conflictHash = mapProTxAddresses.at(pl.addr);
                if (conflictHash != txid && mapTx.count(conflictHash)) {
                    removeRecursive(mapTx.find(conflictHash)->GetTx(), MemPoolRemovalReason::CONFLICT);
                }
            }
            break;
        }

        case CTransaction::TxType::PROUPREG: {
            ProUpRegPL pl;
            if (!GetTxPayload(tx, pl)) {
                LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s", __func__, tx.ToString());
                return;
            }
            removeProTxPubKeyConflicts(tx, pl.pubKeyOperator);
            break;
        }

    }
}

/**
 * Called when a block is connected. Removes from mempool and updates the miner fee estimator.
 */
void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
{
    LOCK(cs);
    std::vector<const CTxMemPoolEntry*> entries;
    for (const auto& tx : vtx) {
        uint256 hash = tx->GetHash();
        indexed_transaction_set::iterator i = mapTx.find(hash);
        if (i != mapTx.end())
            entries.push_back(&*i);
    }
    // Before the txs in the new block have been removed from the mempool, update policy estimates
    minerPolicyEstimator->processBlock(nBlockHeight, entries);
    for (const auto& tx : vtx) {
        txiter it = mapTx.find(tx->GetHash());
        if (it != mapTx.end()) {
            setEntries stage;
            stage.insert(it);
            RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
        }
        removeConflicts(*tx);
        removeProTxConflicts(*tx);
        ClearPrioritisation(tx->GetHash());
    }
    lastRollingFeeUpdate = GetTime();
    blockSinceLastRollingFeeBump = true;
}

void CTxMemPool::_clear()
{
    mapLinks.clear();
    mapTx.clear();
    mapNextTx.clear();
    mapProTxAddresses.clear();
    mapProTxPubKeyIDs.clear();
    totalTxSize = 0;
    cachedInnerUsage = 0;
    lastRollingFeeUpdate = GetTime();
    blockSinceLastRollingFeeBump = false;
    rollingMinimumFeeRate = 0;
    ++nTransactionsUpdated;
}

void CTxMemPool::clear()
{
    LOCK(cs);
    _clear();
}

void CTxMemPool::check(const CCoinsViewCache* pcoins) const
{
    if (nCheckFrequency == 0)
        return;

    if (GetRand(std::numeric_limits<uint32_t>::max()) >= nCheckFrequency)
        return;

    LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());

    uint64_t checkTotal = 0;
    uint64_t innerUsage = 0;

    CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));

    LOCK(cs);
    std::list<const CTxMemPoolEntry*> waitingOnDependants;
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
        unsigned int i = 0;
        checkTotal += it->GetTxSize();
        innerUsage += it->DynamicMemoryUsage();
        const CTransaction& tx = it->GetTx();
        txlinksMap::const_iterator linksiter = mapLinks.find(it);
        assert(linksiter != mapLinks.end());
        const TxLinks &links = linksiter->second;
        innerUsage += memusage::DynamicUsage(links.parents) + memusage::DynamicUsage(links.children);
        bool fDependsWait = false;
        setEntries setParentCheck;
        int64_t parentSizes = 0;
        unsigned int parentSigOpCount = 0;
        bool fHasZerocoinSpends = false;
        for (const CTxIn& txin : tx.vin) {
            // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
            indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
            if (it2 != mapTx.end()) {
                const CTransaction& tx2 = it2->GetTx();
                assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
                fDependsWait = true;
                if (setParentCheck.insert(it2).second) {
                    parentSizes += it2->GetTxSize();
                    parentSigOpCount += it2->GetSigOpCount();
                }
            } else if(!txin.IsZerocoinSpend() && !txin.IsZerocoinPublicSpend()) {
                assert(pcoins->HaveCoin(txin.prevout));
            } else {
                fHasZerocoinSpends = true;
            }
            // Check whether its inputs are marked in mapNextTx.
            if(!fHasZerocoinSpends) {
                auto it3 = mapNextTx.find(txin.prevout);
                assert(it3 != mapNextTx.end());
                assert(it3->first == &txin.prevout);
                assert(*it3->second == tx);
            } else {
                fDependsWait=false;
            }
            i++;
        }
        // sapling txes
        if (tx.IsShieldedTx()) {
            for (const SpendDescription& sd : tx.sapData->vShieldedSpend) {
                SaplingMerkleTree tree;
                assert(pcoins->GetSaplingAnchorAt(sd.anchor, tree));
                assert(!pcoins->GetNullifier(sd.nullifier));
            }
        }
        assert(setParentCheck == GetMemPoolParents(it));
        // Verify ancestor state is correct.
        setEntries setAncestors;
        uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
        std::string dummy;
        CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
        uint64_t nCountCheck = setAncestors.size() + 1;
        uint64_t nSizeCheck = it->GetTxSize();
        CAmount nFeesCheck = it->GetModifiedFee();
        unsigned int nSigOpCheck = it->GetSigOpCount();

        for (const txiter& ancestorIt : setAncestors) {
            nSizeCheck += ancestorIt->GetTxSize();
            nFeesCheck += ancestorIt->GetModifiedFee();
            nSigOpCheck += ancestorIt->GetSigOpCount();
        }

        assert(it->GetCountWithAncestors() == nCountCheck);
        assert(it->GetSizeWithAncestors() == nSizeCheck);
        assert(it->GetSigOpCountWithAncestors() == nSigOpCheck);
        assert(it->GetModFeesWithAncestors() == nFeesCheck);

        // Check children against mapNextTx
        if (!fHasZerocoinSpends) {
            CTxMemPool::setEntries setChildrenCheck;
            auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
            int64_t childSizes = 0;
            for (; iter != mapNextTx.end() && iter->first->hash == tx.GetHash(); ++iter) {
                txiter childit = mapTx.find(iter->second->GetHash());
                assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
                if (setChildrenCheck.insert(childit).second) {
                    childSizes += childit->GetTxSize();
                }
            }
            assert(setChildrenCheck == GetMemPoolChildren(it));
            // Also check to make sure size is greater than sum with immediate children.
            // just a sanity check, not definitive that this calc is correct...
            assert(it->GetSizeWithDescendants() >= (uint64_t)(childSizes + it->GetTxSize()));
        }

        if (fDependsWait)
            waitingOnDependants.push_back(&(*it));
        else {
            CValidationState state;
            PrecomputedTransactionData precomTxData(tx);
            assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, precomTxData, NULL));
            UpdateCoins(tx, mempoolDuplicate, 1000000);
        }
    }

    unsigned int stepsSinceLastRemove = 0;
    while (!waitingOnDependants.empty()) {
        const CTxMemPoolEntry* entry = waitingOnDependants.front();
        waitingOnDependants.pop_front();
        CValidationState state;
        if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
            waitingOnDependants.push_back(entry);
            stepsSinceLastRemove++;
            assert(stepsSinceLastRemove < waitingOnDependants.size());
        } else {
            PrecomputedTransactionData precomTxData(entry->GetTx());
            assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, precomTxData, NULL));
            UpdateCoins(entry->GetTx(), mempoolDuplicate, 1000000);
            stepsSinceLastRemove = 0;
        }
    }
    for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
        const uint256& hash = it->second->GetHash();
        indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
        const CTransactionRef& tx = it2->GetSharedTx();
        assert(it2 != mapTx.end());
        assert(tx == it->second);
    }

    // Consistency check for sapling nullifiers
    checkNullifiers();

    assert(totalTxSize == checkTotal);
    assert(innerUsage == cachedInnerUsage);
}

void CTxMemPool::checkNullifiers() const
{
    for (const auto& it : mapSaplingNullifiers) {
        const uint256& hash = it.second->GetHash();
        const auto& findTx = mapTx.find(hash);
        assert(findTx != mapTx.end());
        const CTransactionRef& tx = findTx->GetSharedTx();
        assert(*tx == *it.second);
    }
}

bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb)
{
    LOCK(cs);
    indexed_transaction_set::const_iterator i = mapTx.find(hasha);
    if (i == mapTx.end()) return false;
    indexed_transaction_set::const_iterator j = mapTx.find(hashb);
    if (j == mapTx.end()) return true;
    uint64_t counta = i->GetCountWithAncestors();
    uint64_t countb = j->GetCountWithAncestors();
    if (counta == countb) {
        return CompareTxMemPoolEntryByScore()(*i, *j);
    }
    return counta < countb;
}

namespace {
    class DepthAndScoreComparator
    {
    public:
        bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b) const
        {
            uint64_t counta = a->GetCountWithAncestors();
            uint64_t countb = b->GetCountWithAncestors();
            if (counta == countb) {
                return CompareTxMemPoolEntryByScore()(*a, *b);
            }
            return counta < countb;
        }
    };
}

std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
{
    std::vector<indexed_transaction_set::const_iterator> iters;
    AssertLockHeld(cs);

    iters.reserve(mapTx.size());

    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
        iters.push_back(mi);
    }
    std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
    return iters;
}

void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
    LOCK(cs);
    auto iters = GetSortedDepthAndScore();

    vtxid.clear();
    vtxid.reserve(mapTx.size());

    for (auto it : iters) {
        vtxid.emplace_back(it->GetTx().GetHash());
    }
}

static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
    return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), CFeeRate(it->GetFee(), it->GetTxSize()), it->GetModifiedFee() - it->GetFee()};
}

std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
{
    LOCK(cs);
    auto iters = GetSortedDepthAndScore();

    std::vector<TxMempoolInfo> ret;
    ret.reserve(mapTx.size());
    for (auto it : iters) {
        ret.emplace_back(GetInfo(it));
    }

    return ret;
}

void CTxMemPool::getTransactions(std::set<uint256>& setTxid)
{
    setTxid.clear();

    LOCK(cs);
    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
        setTxid.insert(mi->GetTx().GetHash());
}

std::shared_ptr<const CTransaction> CTxMemPool::get(const uint256& hash) const
{
    LOCK(cs);
    indexed_transaction_set::const_iterator i = mapTx.find(hash);
    if (i == mapTx.end())
        return nullptr;
    return i->GetSharedTx();
}

TxMempoolInfo CTxMemPool::info(const uint256& hash) const
{
    LOCK(cs);
    indexed_transaction_set::const_iterator i = mapTx.find(hash);
    if (i == mapTx.end())
        return TxMempoolInfo();
    return GetInfo(i);
}

bool CTxMemPool::existsProviderTxConflict(const CTransaction &tx) const
{
    if (!tx.IsSpecialTx()) return false;

    LOCK(cs);

    switch(tx.nType) {
        case CTransaction::TxType::PROREG: {
            ProRegPL pl;
            if (!GetTxPayload(tx, pl)) {
                LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s", __func__, tx.ToString());
                return true; // i.e. can't decode payload == conflict
            }
            if (mapProTxAddresses.count(pl.addr) || mapProTxPubKeyIDs.count(pl.keyIDOwner) ||
                    mapProTxBlsPubKeyHashes.count(pl.pubKeyOperator.GetHash())) {
                return true;
            }
            if (!pl.collateralOutpoint.hash.IsNull()) {
                if (mapProTxCollaterals.count(pl.collateralOutpoint)) {
                    // there is another ProRegTx that refers to the same collateral
                    return true;
                }
                if (mapNextTx.count(pl.collateralOutpoint)) {
                    // there is another tx that spends the collateral
                    return true;
                }
            }
            return false;
        }

        case CTransaction::TxType::PROUPSERV: {
            ProUpServPL pl;
            if (!GetTxPayload(tx, pl)) {
                LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s", __func__, tx.ToString());
                return true; // i.e. can't decode payload == conflict
            }
            auto it = mapProTxAddresses.find(pl.addr);
            return it != mapProTxAddresses.end() && it->second != pl.proTxHash;
        }

        case CTransaction::TxType::PROUPREG: {
            ProUpRegPL pl;
            if (!GetTxPayload(tx, pl)) {
                LogPrint(BCLog::MEMPOOL, "%s: ERROR: Invalid transaction payload, tx: %s", __func__, tx.ToString());
                return true; // i.e. can't decode payload == conflict
            }
            auto it = mapProTxBlsPubKeyHashes.find(pl.pubKeyOperator.GetHash());
            return it != mapProTxBlsPubKeyHashes.end() && it->second != pl.proTxHash;
        }

    }
    return false;
}

CFeeRate CTxMemPool::estimateFee(int nBlocks) const
{
    LOCK(cs);
    return minerPolicyEstimator->estimateFee(nBlocks);
}

CFeeRate CTxMemPool::estimateSmartFee(int nBlocks, int *answerFoundAtBlocks) const
{
    LOCK(cs);
    return minerPolicyEstimator->estimateSmartFee(nBlocks, answerFoundAtBlocks, *this);
}

bool CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
{
    try {
        LOCK(cs);
        fileout << 4029900;         // version required to read: 4.2.99
        fileout << CLIENT_VERSION;  // version that wrote the file
        minerPolicyEstimator->Write(fileout);
    } catch (const std::exception&) {
        LogPrintf("CTxMemPool::WriteFeeEstimates() : unable to write policy estimator data (non-fatal)");
        return false;
    }
    return true;
}

bool CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
{
    try {
        int nVersionRequired, nVersionThatWrote;
        filein >> nVersionRequired >> nVersionThatWrote;
        if (nVersionRequired > CLIENT_VERSION)
            return error("CTxMemPool::ReadFeeEstimates() : up-version (%d) fee estimate file", nVersionRequired);

        LOCK(cs);
        minerPolicyEstimator->Read(filein, nVersionThatWrote);
    } catch (const std::exception&) {
        LogPrintf("CTxMemPool::ReadFeeEstimates() : unable to read policy estimator data (non-fatal)");
        return false;
    }
    return true;
}

void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
{
    {
        LOCK(cs);
        CAmount &delta = mapDeltas[hash];
        delta += nFeeDelta;
        txiter it = mapTx.find(hash);
        if (it != mapTx.end()) {
            mapTx.modify(it, update_fee_delta(delta));
            // Now update all ancestors' modified fees with descendants
            setEntries setAncestors;
            uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
            std::string dummy;
            CalculateMemPoolAncestors(*it, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false);
            for (const txiter& ancestorIt : setAncestors) {
                mapTx.modify(ancestorIt, update_descendant_state(0, nFeeDelta, 0));
            }
        }
    }
    LogPrintf("PrioritiseTransaction: %s feerate += %s\n", hash.ToString(), FormatMoney(nFeeDelta));
}

void CTxMemPool::ApplyDelta(const uint256& hash, CAmount& nFeeDelta) const
{
    LOCK(cs);
    std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
    if (pos == mapDeltas.end())
        return;
    const CAmount &delta = pos->second;
    nFeeDelta += delta;
}

void CTxMemPool::ClearPrioritisation(const uint256 hash)
{
    LOCK(cs);
    mapDeltas.erase(hash);
}

bool CTxMemPool::nullifierExists(const uint256& nullifier) const
{
    LOCK(cs);
    return mapSaplingNullifiers.count(nullifier);
}

bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
{
    if (tx.HasZerocoinSpendInputs())
        return true;
    for (unsigned int i = 0; i < tx.vin.size(); i++)
        if (exists(tx.vin[i].prevout.hash))
            return false;
    return true;
}

CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) {}

bool CCoinsViewMemPool::GetCoin(const COutPoint& outpoint, Coin& coin) const
{
    // If an entry in the mempool exists, always return that one, as it's guaranteed to never
    // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
    // transactions. First checking the underlying cache risks returning a pruned entry instead.
    CTransactionRef ptx = mempool.get(outpoint.hash);
    if (ptx) {
        if (outpoint.n < ptx->vout.size()) {
            coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false, false);
            return true;
        } else {
            return false;
        }
    }
    return (base->GetCoin(outpoint, coin) && !coin.IsSpent());
}

bool CCoinsViewMemPool::HaveCoin(const COutPoint& outpoint) const
{
    return mempool.exists(outpoint) || base->HaveCoin(outpoint);
}

bool CCoinsViewMemPool::GetNullifier(const uint256& nullifier) const
{
    return mempool.nullifierExists(nullifier) || base->GetNullifier(nullifier);
}

size_t CTxMemPool::DynamicMemoryUsage() const
{
    LOCK(cs);
    // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for
    // boost::multi_index_contained is implemented.
    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() +
            memusage::DynamicUsage(mapNextTx) +
            memusage::DynamicUsage(mapDeltas) +
            memusage::DynamicUsage(mapLinks) +
            cachedInnerUsage +
            memusage::DynamicUsage(mapSaplingNullifiers);
}

void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason)
{
    AssertLockHeld(cs);
    UpdateForRemoveFromMempool(stage, updateDescendants);
    for (const txiter& it : stage) {
        removeUnchecked(it, reason);
    }
}

int CTxMemPool::Expire(int64_t time)
{
    LOCK(cs);
    indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
    setEntries toremove;
    while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
        toremove.insert(mapTx.project<0>(it));
        it++;
    }
    setEntries stage;
    for (const txiter& removeit : toremove) {
        CalculateDescendants(removeit, stage);
    }
    RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
    return stage.size();
}

bool CTxMemPool::addUnchecked(const uint256&hash, const CTxMemPoolEntry &entry, bool validFeeEstimate)
{
    LOCK(cs);
    setEntries setAncestors;
    uint64_t nNoLimit = std::numeric_limits<uint64_t>::max();
    std::string dummy;
    CalculateMemPoolAncestors(entry, setAncestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy);
    return addUnchecked(hash, entry, setAncestors, validFeeEstimate);
}

void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
{
    setEntries s;
    if (add && mapLinks[entry].children.insert(child).second) {
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
    } else if (!add && mapLinks[entry].children.erase(child)) {
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
    }
}

void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
{
    setEntries s;
    if (add && mapLinks[entry].parents.insert(parent).second) {
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
    } else if (!add && mapLinks[entry].parents.erase(parent)) {
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
    }
}

const CTxMemPool::setEntries & CTxMemPool::GetMemPoolParents(txiter entry) const
{
    assert (entry != mapTx.end());
    txlinksMap::const_iterator it = mapLinks.find(entry);
    assert(it != mapLinks.end());
    return it->second.parents;
}

const CTxMemPool::setEntries & CTxMemPool::GetMemPoolChildren(txiter entry) const
{
    assert (entry != mapTx.end());
    txlinksMap::const_iterator it = mapLinks.find(entry);
    assert(it != mapLinks.end());
    return it->second.children;
}

CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const
{
    LOCK(cs);
    if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
        return CFeeRate(rollingMinimumFeeRate);

    int64_t time = GetTime();
    if (time > lastRollingFeeUpdate + 10) {
        double halflife = ROLLING_FEE_HALFLIFE;
        if (DynamicMemoryUsage() < sizelimit / 4)
            halflife /= 4;
        else if (DynamicMemoryUsage() < sizelimit / 2)
            halflife /= 2;

        rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
        lastRollingFeeUpdate = time;

        if (rollingMinimumFeeRate < (double)minReasonableRelayFee.GetFeePerK() / 2) {
            rollingMinimumFeeRate = 0;
            return CFeeRate(0);
        }
    }
    return std::max(CFeeRate(rollingMinimumFeeRate), minReasonableRelayFee);
}

void CTxMemPool::trackPackageRemoved(const CFeeRate& rate)
{
    AssertLockHeld(cs);
    if (rate.GetFeePerK() > rollingMinimumFeeRate) {
        rollingMinimumFeeRate = rate.GetFeePerK();
        blockSinceLastRollingFeeBump = false;
    }
}

void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining)
{
    LOCK(cs);
    unsigned nTxnRemoved = 0;
    CFeeRate maxFeeRateRemoved(0);
    while (DynamicMemoryUsage() > sizelimit) {
        indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();

        // We set the new mempool min fee to the feerate of the removed set, plus the
        // "minimum reasonable fee rate" (ie some value under which we consider txn
        // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
        // equal to txn which were removed with no block in between.
        CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
        removed += minReasonableRelayFee;
        trackPackageRemoved(removed);
        maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);

        setEntries stage;
        CalculateDescendants(mapTx.project<0>(it), stage);
        nTxnRemoved += stage.size();

        std::vector<CTransaction> txn;
        if (pvNoSpendsRemaining) {
            txn.reserve(stage.size());
            for (txiter it: stage)
                txn.push_back(it->GetTx());
        }
        RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
        if (pvNoSpendsRemaining) {
            for (const CTransaction& tx: txn) {
                for (const CTxIn& txin: tx.vin) {
                    if (exists(txin.prevout.hash)) continue;
                    if (!mapNextTx.count(txin.prevout)) {
                        pvNoSpendsRemaining->push_back(txin.prevout);
                    }
                }
            }
        }
    }

    if (maxFeeRateRemoved > CFeeRate(0))
        LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
}

bool CTxMemPool::IsLoaded() const
{
    LOCK(cs);
    return m_is_loaded;
}

void CTxMemPool::SetIsLoaded(bool loaded)
{
    LOCK(cs);
    m_is_loaded = loaded;
}


text:
package server

import (
	"errors"
	"fmt"
	"io"
	"mime"
	"net"
	"net/http"
	"path"
	"strings"
	"sync"

	"github.com/elazarl/go-bindata-assetfs"
	"github.com/golang/glog"
	//"github.com/gorilla/websocket"

	"golang.org/x/net/context"
	"golang.org/x/net/websocket"

	apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"

	"github.com/tangfeixiong/go-to-bigdata/nps-wss/pkg/httpfs"
	"github.com/tangfeixiong/go-to-kubernetes/mysql-operator/pb"
	"github.com/tangfeixiong/go-to-kubernetes/mysql-operator/pkg/ui/data/webapp"
)

func (ctl *controller) CreateCrd(ctx context.Context, req *pb.CrdReqResp) (*pb.CrdReqResp, error) {
	fmt.Println("Request to create CRD:", req)
	resp := &pb.CrdReqResp{
		Recipe: new(pb.CrdRecipient),
	}
	if req == nil || req.Recipe == nil {
		resp.StateCode = 100
		resp.StateMessage = "CRD recipe is required"
		return resp, errors.New(resp.StateMessage)
	}
	if req.Recipe.Group == "" || req.Recipe.Plural == "" {
		resp.StateCode = 101
		resp.StateMessage = "CRD name e.g. <group>/<plural> is required"
		return resp, errors.New(resp.StateMessage)
	}
	if req.Recipe.Scope != string(apiextv1beta1.NamespaceScoped) && req.Recipe.Scope != string(apiextv1beta1.ClusterScoped) {
		req.Recipe.Scope = req.Recipe.ResourceScope.String()
	}
	resp.Recipe.Group = req.Recipe.Group
	resp.Recipe.Version = req.Recipe.Version
	resp.Recipe.Scope = req.Recipe.Scope
	resp.Recipe.Plural = req.Recipe.Plural
	resp.Recipe.Singular = req.Recipe.Singular
	resp.Recipe.Kind = req.Recipe.Kind

	if v, ok := ctl.ops["mysql-operator"]; !ok {
		glog.Infoln("CRD operation does not exist")
		resp.StateCode = 199
		resp.StateMessage = "Missing operation"
		return resp, fmt.Errorf("Missing operation")
	} else if err := v.CreateCRD(req.Recipe); err != nil {
		glog.Infof("Create CRD failed: %s", err.Error())
		resp.StateCode = 10
		resp.StateMessage = err.Error()
		return resp, err
	}
	return resp, nil
}

func (ctl *controller) ReapCrd(ctx context.Context, req *pb.CrdReqResp) (*pb.CrdReqResp, error) {
	fmt.Println("Requesting:", req)
	return new(pb.CrdReqResp), nil
}

/*
  https://github.com/golang/go/blob/master/net/http/fs.go
*/
// FileServer returns a handler that serves HTTP requests
// with the contents of the file system rooted at root.
//
// To use the operating system's file system implementation,
// use http.Dir:
//
//     http.Handle("/", http.FileServer(http.Dir("/tmp")))
//
// As a special case, the returned file server redirects any request
// ending in "/index.html" to the same path, without the final
// "index.html".
/*
func FileServer(root http.FileSystem) http.Handler {
	return &fileHandler{root}
}
*/

func (ctl *controller) serveWebPages(mux *http.ServeMux) {
	mime.AddExtensionType(".svg", "image/svg+xml")

	// Expose files in third_party/swagger-ui/ on <host>/swagger-ui
	//	fileserver := FileServer(&assetfs.AssetFS{
	//		Asset:    webapp.Asset,
	//		AssetDir: webapp.AssetDir,
	//		Prefix:   "static",
	//	})
	//	prefix := "/html/"
	//	mux.Handle(prefix, http.StripPrefix(prefix, fileserver))
	ctl.root = &assetfs.AssetFS{
		Asset:    webapp.Asset,
		AssetDir: webapp.AssetDir,
		Prefix:   "static",
	}
	prefix := "/test/"
	mux.Handle(prefix, http.StripPrefix(prefix, ctl))

	//	ws := websocket.Server{
	//		Handshake: ctl.bootHandshake,
	//		Handler:   ctl.handleWss,
	//	}
	//	mux.Handle("/ws", ws)
	prefix += "ws"
	mux.HandleFunc(prefix, ctl.WebsocketHandler)
}

func (f *controller) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if token := r.URL.Query().Get("token"); token != "" {
		fmt.Printf("request: %+v\n", r)
		http.SetCookie(w, &http.Cookie{
			Name:  "nps_token",
			Value: token,
			Path:  "/",
		})
	} else {
		fmt.Printf("header referer: %+v\n", r.Header.Get("Referer"))
	}

	upath := r.URL.Path
	if !strings.HasPrefix(upath, "/") {
		upath = "/" + upath
		r.URL.Path = upath
	}
	httpfs.ServeFileSystem(w, r, f.root, path.Clean(upath), true)
}

func (ctl *controller) handleWss(wsconn *websocket.Conn) {
	fmt.Printf("handle wss: %+v\n", wsconn.Config())
	var cookie *http.Cookie
	var err error
	cookie, err = wsconn.Request().Cookie("novnc_token")
	if cookie == nil || err != nil {
		fmt.Println(wsconn.Request().URL, wsconn.Request().Form, wsconn.Request().Header)
		return
	}
	token := cookie.Value
	if token == "" {
		fmt.Println("Unexpected, token does not exist")
		return
	}

	var conn net.Conn
	var wsc *websocket.Conn
	var targetAddr string

	conn, wsc, targetAddr = nil, nil, "127.0.0.1:5670"
	if targetAddr == "" {
		fmt.Println("API not invoked")
		return
	}
	if wsc != nil {
		if wsc == wsconn {
			fmt.Println("Already connected")
			return
		}
		fmt.Print("Disconnect old streaming")
		if err := wsc.Close(); err != nil {
			fmt.Println(err.Error())
		} else {
			fmt.Println()
		}
		if conn != nil {
			if err := conn.Close(); err != nil {
				fmt.Println(err.Error())
			} else {
				fmt.Println()
			}
		}
	}
	if conn == nil {
		fmt.Println("Connecting", targetAddr)
		conn, err = net.Dial("tcp", targetAddr)
		if err != nil {
			fmt.Println("Could not connect VNC, error:", err.Error())
			wsconn.Close()
			return
		}
	}

	wsconn.PayloadType = websocket.BinaryFrame
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		defer wsconn.Close()
		l, e := io.Copy(conn, wsconn)
		fmt.Println("Client streaming terminated (ws -> vnc), ", l, e)
	}()
	wg.Add(1)
	go func() {
		defer wg.Done()
		defer conn.Close()
		l, e := io.Copy(wsconn, conn)
		fmt.Println("Server streaming terminated (vnc -> ws), ", l, e)
	}()
	//select {}
	wg.Wait()
}

func (ctl *controller) bootHandshake(config *websocket.Config, r *http.Request) error {
	fmt.Printf("handshake: %+v\nrequest: %+v\n", config, r)
	config.Protocol = []string{"binary"}

	r.Header.Set("Access-Control-Allow-Origin", "*")
	r.Header.Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
require File.expand_path('../error', __FILE__)

module Automatic
  module Core
    class Errors
      include Enumerable

      def initialize(collection)
        @collection = Array(collection)
      end

      def each(&block)
        record_collection.each(&block)
      end

      def find_by_code(code)
        self.select { |record| record.code == code.to_i }.first
      end

      def find_by_name(name)
        self.select { |record| record.name == name.to_s }.first
      end

      private
      def record_collection
        @collection.map { |record| Error.new(record) }
      end
    end
  end
end


text:
<?php

namespace RodrigoPedra\RecordProcessor\Records;

use Illuminate\Support\Fluent;
use RodrigoPedra\RecordProcessor\Contracts\JsonRecord;
use RodrigoPedra\RecordProcessor\Contracts\Record;
use RodrigoPedra\RecordProcessor\Contracts\TextRecord;
use RodrigoPedra\RecordProcessor\Serializers\JSONFileSerializer;

class SimpleRecord extends Fluent implements Record, TextRecord, JsonRecord
{
    protected ?string $key;

    public function __construct(?string $key, array $attributes = [])
    {
        parent::__construct($attributes);

        $this->key = $key;
    }

    public function key(): ?string
    {
        return $this->key;
    }

    public function field(string $field): mixed
    {
        return $this->get($field);
    }

    public function isValid(): bool
    {
        if (\is_null($this->key)) {
            return false;
        }

        return \mb_strlen($this->key) > 0;
    }

    public function toText(): string
    {
        return $this->toJson(JSONFileSerializer::JSON_ENCODE_OPTIONS);
    }
}


text:
namespace Dominion.GameHost.AI.BehaviourBased
{
    public class CommentOnGameEndBehaviour : IAIBehaviour
    {
        private readonly string _comment;

        public CommentOnGameEndBehaviour(string comment)
        {
            _comment = comment;
        }

        public virtual bool CanRespond(ActivityModel activity, GameViewModel state)
        {
            return state.Status.GameIsComplete;
        }

        public virtual void Respond(IGameClient client, ActivityModel activity, GameViewModel state)
        {
            client.SendChatMessage(_comment);
        }
    }
}


text:
package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Dragon extends StdRace
{
	public String ID(){	return "Dragon"; }
	public String name(){ return "Dragon"; }
	public int shortestMale(){return 84;}
	public int shortestFemale(){return 78;}
	public int heightVariance(){return 80;}
	public int lightestWeight(){return 2000;}
	public int weightVariance(){return 500;}
	public long forbiddenWornBits(){return Wearable.WORN_WIELD|Wearable.WORN_WAIST|Wearable.WORN_BACK|Wearable.WORN_ABOUT_BODY|Wearable.WORN_FEET|Wearable.WORN_HANDS;}
	public String racialCategory(){return "Dragon";}
	private String[]racialAbilityNames={"Dragonbreath","WingFlying"};
	private int[]racialAbilityLevels={5,1};
	private int[]racialAbilityProficiencies={100,100};
	private boolean[]racialAbilityQuals={false,false};
	protected String[] racialAbilityNames(){return racialAbilityNames;}
	protected int[] racialAbilityLevels(){return racialAbilityLevels;}
	protected int[] racialAbilityProficiencies(){return racialAbilityProficiencies;}
	protected boolean[] racialAbilityQuals(){return racialAbilityQuals;}
	private String[]culturalAbilityNames={"Draconic"};
	private int[]culturalAbilityProficiencies={100};
	public String[] culturalAbilityNames(){return culturalAbilityNames;}
	public int[] culturalAbilityProficiencies(){return culturalAbilityProficiencies;}

	//                                an ey ea he ne ar ha to le fo no gi mo wa ta wi
	private static final int[] parts={0 ,2 ,2 ,1 ,1 ,0 ,0 ,1 ,4 ,4 ,1 ,0 ,1 ,1 ,1 ,2 };
	public int[] bodyMask(){return parts;}

	private int[] agingChart={0,5,20,110,325,500,850,950,1050};
	public int[] getAgingChart(){return agingChart;}

	protected static Vector resources=new Vector();
	public int availabilityCode(){return Area.THEME_FANTASY|Area.THEME_SKILLONLYMASK;}

	public void affectEnvStats(Environmental affected, EnvStats affectableStats)
	{
		super.affectEnvStats(affected,affectableStats);
		affectableStats.setSensesMask(affectableStats.sensesMask()|EnvStats.CAN_SEE_INFRARED);
		if(!CMLib.flags().isSleeping(affected))
			affectableStats.setDisposition(affectableStats.disposition()|EnvStats.IS_FLYING);
	}
	public void affectCharStats(MOB affectedMOB, CharStats affectableStats)
	{
		super.affectCharStats(affectedMOB, affectableStats);
		int bump = affectedMOB.isMonster()?15:5;
		affectableStats.setStat(CharStats.STAT_STRENGTH,affectableStats.getStat(CharStats.STAT_STRENGTH)+bump);
		affectableStats.setStat(CharStats.STAT_DEXTERITY,affectableStats.getStat(CharStats.STAT_DEXTERITY)+bump);
		affectableStats.setStat(CharStats.STAT_INTELLIGENCE,affectableStats.getStat(CharStats.STAT_INTELLIGENCE)+bump);
	}
	public Weapon myNaturalWeapon()
	{
		if(naturalWeapon==null)
		{
			naturalWeapon=CMClass.getWeapon("StdWeapon");
			naturalWeapon.setName("huge talons");
			naturalWeapon.setWeaponType(Weapon.TYPE_PIERCING);
		}
		return naturalWeapon;
	}
	public String healthText(MOB viewer, MOB mob)
	{
		double pct=(CMath.div(mob.curState().getHitPoints(),mob.maxState().getHitPoints()));

		if(pct<.10)
			return "^r" + mob.displayName(viewer) + "^r is raging in bloody pain!^N";
		else
		if(pct<.20)
			return "^r" + mob.displayName(viewer) + "^r is covered in blood.^N";
		else
		if(pct<.30)
			return "^r" + mob.displayName(viewer) + "^r is bleeding badly from lots of wounds.^N";
		else
		if(pct<.50)
			return "^y" + mob.displayName(viewer) + "^y has some bloody wounds and gashed scales.^N";
		else
		if(pct<.60)
			return "^p" + mob.displayName(viewer) + "^p has a few bloody wounds.^N";
		else
		if(pct<.70)
			return "^p" + mob.displayName(viewer) + "^p is cut and bruised heavily.^N";
		else
		if(pct<.90)
			return "^g" + mob.displayName(viewer) + "^g has a few bruises and scratched scales.^N";
		else
		if(pct<.99)
			return "^g" + mob.displayName(viewer) + "^g has a few small bruises.^N";
		else
			return "^c" + mob.displayName(viewer) + "^c is in perfect health.^N";
	}
	public Vector myResources()
	{
		synchronized(resources)
		{
			if(resources.size()==0)
			{
				resources.addElement(makeResource
				("a "+name().toLowerCase()+" claw",RawMaterial.RESOURCE_BONE));
				for(int i=0;i<100;i++)
					resources.addElement(makeResource
					("a strip of "+name().toLowerCase()+" scales",RawMaterial.RESOURCE_SCALES));
				for(int i=0;i<50;i++)
					resources.addElement(makeResource
					("a pound of "+name().toLowerCase()+" meat",RawMaterial.RESOURCE_DRAGONMEAT));
				resources.addElement(makeResource
				("some "+name().toLowerCase()+" blood",RawMaterial.RESOURCE_DRAGONBLOOD));
			}
		}
		return resources;
	}
}


text:
.class public Lcom/mediatek/op/net/DefaultConnectivityServiceExt;
.super Ljava/lang/Object;
.source "DefaultConnectivityServiceExt.java"

# interfaces
.implements Lcom/mediatek/common/net/IConnectivityServiceExt;

# static fields
.field private static final TAG:Ljava/lang/String; = "CDS/IConnectivityServiceExt"

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 55
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 56
    const-string v0, "DefaultConnectivityServiceExt in default"

    invoke-direct {p0, v0}, Lcom/mediatek/op/net/DefaultConnectivityServiceExt;->log(Ljava/lang/String;)V

    .line 57
    return-void
.end method

.method private log(Ljava/lang/String;)V
    .locals 1
    .parameter "s"

    .prologue
    .line 85
    const-string v0, "CDS/IConnectivityServiceExt"

    invoke-static {v0, p1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 86
    return-void
.end method

# virtual methods
.method public init(Landroid/content/Context;)V
    .locals 1
    .parameter "context"

    .prologue
    .line 60
    const-string v0, "init in default"

    invoke-direct {p0, v0}, Lcom/mediatek/op/net/DefaultConnectivityServiceExt;->log(Ljava/lang/String;)V

    .line 61
    return-void
.end method

.method public isControlBySetting(II)Z
    .locals 2
    .parameter "netType"
    .parameter "radio"

    .prologue
    .line 74
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "isControlBySetting: netType="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, " readio="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-direct {p0, v0}, Lcom/mediatek/op/net/DefaultConnectivityServiceExt;->log(Ljava/lang/String;)V

    .line 75
    if-nez p2, :cond_0

    const/16 v0, 0x22

    if-eq p1, v0, :cond_0

    const/4 v0, 0x2

    if-eq p1, v0, :cond_0

    .line 78
    const/4 v0, 0x1

    .line 81
    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public isDefaultFailover(II)Z
    .locals 1
    .parameter "netType"
    .parameter "activeDefaultNetwork"

    .prologue
    .line 69
    const-string v0, "default isDefaultFailover"

    invoke-direct {p0, v0}, Lcom/mediatek/op/net/DefaultConnectivityServiceExt;->log(Ljava/lang/String;)V

    .line 70
    const/4 v0, 0x1

    return v0
.end method

.method public isUserPrompt()Z
    .locals 1

    .prologue
    .line 64
    const-string v0, "default isUserPrompt"

    invoke-direct {p0, v0}, Lcom/mediatek/op/net/DefaultConnectivityServiceExt;->log(Ljava/lang/String;)V

    .line 65
    const/4 v0, 0x0

    return v0
.end method


text:
/**
 * @file Constructor function for comments assist control
 *
 * @constructor
 * @since: 1.6.0
 * @author: h.m.kwon@samsung.com
 *
 */

/*jshint unused:false*/

// @formatter:off
define([
    'external/codemirror/lib/codemirror',
    'external/lodash/lodash.min',
    'require',
    'webida-lib/util/genetic',
    'webida-lib/util/logger/logger-client',
    'plugins/webida.editor.code-editor/content-assist/IContentAssist'
], function (
    codemirror,
     _,
    require,
    genetic,
    Logger,
    IContentAssist
) {
    'use strict';
// @formatter:on

    var logger = new Logger();
    logger.off();

    /* Content assist commands */

    var caCommands = [
        'isLineCommentable',
        'isBlockCommentable',
        'isSelectionCommentable',
        'lineComment',
        'blockComment',
        'commentOutSelection'
    ];

    function CommentsControl(viewer, cm, options, c) {
        logger.info('new CommentsControl()');

        if (c) {
            c();
        }
    }

    function getEnclosingBlockComments(mode, editor, from, to) {
        var startStr = mode.blockCommentStart;
        var endStr = mode.blockCommentEnd;
        var doc = editor.getDoc();
        var endStrLen = endStr.length;
        var state = 'closed';
        var comments = [];
        var openingPos;
        var lineComment = mode.lineComment;
        var done = false;
        function comparePos(p1, p2) {
            if (p1.line < p2.line) {
                return -1;
            } else if (p1.line > p2.line) {
                return 1;
            } else {
                return p1.ch - p2.ch;
            }
        }

        // collect block comments in the code
        doc.eachLine(function (h) {

            var lineNo, text;

            function findCommentStart(i) {
                if (state !== 'closed') {
                    throw new Error('assertion fail: unrechable');
                }

                if (comparePos({ line: lineNo, ch: i }, to) >= 0) {
                    done = true;
                    return;
                }

                var j = text.indexOf(startStr, i);
                if (j >= i) {
                    var pos = { line: lineNo, ch: j + 1 };
                    var token = editor.getTokenAt(pos, true);
                    if (token && token.string.indexOf(startStr) === 0) {
                        if (comparePos({ line: lineNo, ch: j }, to) < 0) {
                            // found an opening of a block comment
                            state = 'opened';
                            openingPos = { line: lineNo, ch: j };
                            findCommentEnd(j + startStr.length);
                        } else {
                            done = true;
                            return;
                        }
                    }
                }
            }

            function findCommentEnd(i) {
                if (state !== 'opened') {
                    throw new Error('assertion fail: unrechable');
                }
                var j = text.indexOf(endStr, i);
                if (j >= i) {
                    var pos = { line: lineNo, ch: j + 1 };
                    var token = editor.getTokenAt(pos, true);
                    if (token && token.string.substr(-endStrLen) === endStr &&
                        (!lineComment || token.string.indexOf(lineComment) !== 0)) {
                        // found an closing of a block comment
                        state = 'closed';
                        var closingPos;
                        if (comparePos(from, (closingPos = { line: lineNo, ch: j + endStrLen })) < 0) {
                            comments.push([openingPos, closingPos]);
                        }
                        openingPos = null;

                        findCommentStart(j + endStrLen);
                    }
                }
            }

            if (!done) {
                lineNo = h.lineNo();
                text = h.text;
                if (state === 'closed') {
                    findCommentStart(0);
                } else if (state === 'opened') {
                    findCommentEnd(0);
                } else {
                    throw new Error('assertion fail: unreachable');
                }
            }
        });

        //console.log('hina temp: overlapping block comments: ');
        //console.debug(comments);

        // check if from-to overlaps any block comments
        // without being included or including the comments.
        var commentsLen = comments.length;
        if (commentsLen === 0) {
            return [];
        } else if (commentsLen === 1) {
            if (comparePos(comments[0][0], from) <= 0 && comparePos(to, comments[0][1]) <= 0) {
                return comments;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    function isLineCommentable(editor) {
        var from = editor.getCursor('from');
        var to = editor.getCursor('to');
        var mode1 = editor.getModeAt(from);
        var mode2 = editor.getModeAt(to);
        return mode1.name === mode2.name &&
            mode1.lineComment && mode1.lineComment === mode2.lineComment;
    }

    function isBlockCommentable(editor) {
        var doc = editor.getDoc();
        var from = editor.getCursor('from');
        var to = editor.getCursor('to');
        var from2 = {
            line: from.line,
            ch: 0
        };
        var to2 = {
            line: to.line,
            ch: doc.getLine(to.line).length
        };

        var mode1 = editor.getModeAt(from);
        var mode2 = editor.getModeAt(to);
        var comments;
        return mode1.name === mode2.name &&
            mode1.blockCommentStart &&
            mode1.blockCommentStart === mode2.blockCommentStart &&
            mode1.blockCommentEnd === mode2.blockCommentEnd &&
            (comments = getEnclosingBlockComments(mode1, editor, from, to)) &&
            (comments.length === 1 ||
             ((comments = getEnclosingBlockComments(mode1, editor, from2, to2)) && comments.length === 0));
    }

    function isSelectionCommentable(editor) {
        var from = editor.getCursor('from');
        var to = editor.getCursor('to');

        if (from.line === to.line && from.ch === to.ch) {
            return false;
            // no selection
        }

        var mode1 = editor.getModeAt(from);
        var mode2 = editor.getModeAt(to);
        var comments;
        return mode1.name === mode2.name && mode1.blockCommentStart &&
            mode1.blockCommentStart === mode2.blockCommentStart &&
            mode1.blockCommentEnd === mode2.blockCommentEnd &&
            (comments = getEnclosingBlockComments(mode1, editor, from, to)) && comments.length === 0;
    }

    function lineComment(cm) {
        if (cm.__instance) {
            var from = cm.getCursor('from');
            var to = cm.getCursor('to');
            var mode1 = cm.getModeAt(from);
            var mode2 = cm.getModeAt(to);

            if (mode1.lineComment && mode1.lineComment === mode2.lineComment) {
                var doc = cm.getDoc();
                var commenting = false;
                var line;
                var commentStr = mode1.lineComment;
                doc.eachLine(from.line, to.line + 1, function (h) {
                    var i, text = h.text;
                    var commented =
                        (i = text.indexOf(commentStr)) >= 0 &&
                        !/\S/.test(text.substring(0, i));

                    // if there is at least one uncommented line, then we are commenting.
                    commenting = commenting || !commented;
                });
                if (commenting) {
                    for (line = from.line; line <= to.line; line++) {
                        doc.replaceRange(commentStr, {line: line, ch: 0});
                    }
                } else {
                    var len = commentStr.length;
                    for (line = from.line; line <= to.line; line++) {
                        var i, text = doc.getLine(line);
                        i = text.indexOf(commentStr);
                        doc.replaceRange('', {line: line, ch: i}, {line: line, ch: i + len});
                    }
                }
                return;
            }
            return codemirror.Pass;
        }
    }

    function blockComment(cm) {
        if (cm.__instance) {
            var doc = cm.getDoc();
            var from = cm.getCursor('from');
            var to = cm.getCursor('to');
            var lastLine = doc.getLine(to.line);

            var mode = cm.getModeAt(from);
            var commenting = (cm.getTokenAt(to, true).type !== 'comment');
            var bcStart = mode.blockCommentStart, bcEnd = mode.blockCommentEnd;
            if (commenting) {
                doc.replaceRange('\n' + bcEnd, { line: to.line, ch: lastLine.length });
                doc.replaceRange(bcStart + '\n', { line: from.line, ch: 0 });
            } else {
                // uncommenting
                var comments =
                    getEnclosingBlockComments(mode, cm, from, to, bcStart, bcEnd);
                if (comments.length === 1) {
                    var comment = comments[0];
                    doc.replaceRange('',
                                     { line: comment[1].line, ch: comment[1].ch - bcEnd.length },
                                     comment[1]);
                    doc.replaceRange('',
                                     comment[0],
                                     { line: comment[0].line, ch: comment[0].ch + bcStart.length });
                } else {
                    console.error('assertion fail: unreachable');
                }
            }
        }
    }

    function commentOutSelection(cm) {
        if (cm.__instance) {
            var from = cm.getCursor('from');
            var to = cm.getCursor('to');
            var mode = cm.getModeAt(from);
            var bcStart = mode.blockCommentStart, bcEnd = mode.blockCommentEnd;

            var doc = cm.getDoc();
            doc.replaceRange(bcEnd, to);
            doc.replaceRange(bcStart, from);
        }
    }

    function isCaCommand(command) {
        return caCommands.indexOf(command) >= 0;
    }

    genetic.inherits(CommentsControl, IContentAssist, {

        /**
         * Returns whether the command is supported
         *
         * @param {string} command
         *
         * @return {boolean}
         */
        canExecute: function (command) {
            return isCaCommand(command);
        },

        /**
         * Execute the command
         *
         * @param {string} command
         *
         * @param {[args]} arguments
         *
         * @return {all}
         */
        execCommand: function (command) {
            var slice = Array.prototype.slice;
            var args = slice.apply(arguments);
            args.splice(0, 1);
            var func;
            if (isCaCommand(command)) {
                switch (command) {
                    case 'isLineCommentable':
                        func = isLineCommentable;
                        break;
                    case 'isBlockCommentable':
                        func = isBlockCommentable;
                        break;
                    case 'isSelectionCommentable':
                        func = isSelectionCommentable;
                        break;
                    case 'lineComment':
                        func = lineComment;
                        break;
                    case 'blockComment':
                        func = blockComment;
                        break;
                    case 'commentOutSelection':
                        func = commentOutSelection;
                        break;
                }
                return func.apply(undefined, args);
            } else {
                console.error('Command[' + command + '] is not supported.');
            }
        }
    });

    return CommentsControl;
});


text:
name             'elasticsearch'
maintainer       'Wanelo'
maintainer_email 'play@wanelo.com'
license          'MIT'
description      'Installs/Configures elasticsearch on Joyent SmartOS'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.13.2'

depends 'java'
depends 'logadm'
depends 'paths'
depends 'resource-control'
depends 'smf', '>= 2.2.0'


text:
#include <stdlib.h>
#include "mgos.h"
#include "mgos_onewire.h"
#include "ds18b20.h"

// Helper for allocating new things
#define new(what) (what *)malloc(sizeof(what))

// Helper for allocating strings
#define new_string(len) (char *)malloc(len * sizeof(char))

// Converts a uint8_t rom address to a MAC address string
#define to_mac(r, str) sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7])

// Read all temperatures
void ds18b20_read_all(int pin, int res, ds18b20_read_t callback) {
    uint8_t rom[8], data[9];
    int16_t raw;
    int us, cfg;
    struct mgos_onewire *ow;
    struct ds18b20_result *temp, *list = NULL;

    // Step 1: Determine config
    if ( res == 9 )       { cfg=0x1F;  us=93750;  } // 9-bit resolution (93.75ms delay)
    else if ( res == 10 ) { cfg=0x3F;  us=187500; } // 10-bit resolution (187.5ms delay)
    else if ( res == 11 ) { cfg=0x5F;  us=375000; } // 11-bit resolution (375ms delay)
    else /* 12-bit */     { cfg=0x7F;  us=750000; } // 12-bit resolution (750ms delay)

    // Step 2: Find all the sensors
    ow = mgos_onewire_create(pin);                  // Create one-wire
    mgos_onewire_search_clean(ow);                  // Reset search
    while ( mgos_onewire_next(ow, rom, 1) ) {       // Loop over all devices
        if (rom[0] != 0x28) continue;               // Skip devices that are not DS18B20's
        temp = new(struct ds18b20_result);          // Create a new results struct
        if ( temp == NULL ) {                       // Make sure it worked
            printf("Memory allocation failure!");   // If not, print a useful message
            exit(1);                                // And blow up
        }
        memcpy(temp->rom, rom, 8);                  // Copy the ROM code into the result
        temp->mac = new_string(23);                 // Allocate a string for the MAC address
        to_mac(rom, temp->mac);                     // Convert the rom to a MAC address string
        temp->next = list;                          // link to previous sensor
        list = temp;                                // set list point to new result
    }

    // Step 3: Write the configuration
    mgos_onewire_reset(ow);                         // Reset
    mgos_onewire_write(ow, 0xCC);                   // Skip Rom
    mgos_onewire_write(ow, 0x4E);                   // Write to scratchpad
    mgos_onewire_write(ow, 0x00);                   // Th or User Byte 1
    mgos_onewire_write(ow, 0x00);                   // Tl or User Byte 2
    mgos_onewire_write(ow, cfg);                    // Configuration register
    mgos_onewire_write(ow, 0x48);                   // Copy scratchpad

    // Step 4: Start temperature conversion
    mgos_onewire_reset(ow);                         // Reset
    mgos_onewire_write(ow, 0xCC);                   // Skip Rom
    mgos_onewire_write(ow, 0x44);                   // Start conversion
    mgos_usleep(us);                                // Wait for conversion

    // Step 5: Read the temperatures
    temp = list;                                    // Temporary results holder
    while ( temp != NULL ) {                        // Loop over all devices
        mgos_onewire_reset(ow);                     // Reset
        mgos_onewire_select(ow, temp->rom);         // Select the device
        mgos_onewire_write(ow, 0xBE);               // Issue read command
        mgos_onewire_read_bytes(ow, data, 9);       // Read the 9 data bytes
        raw = (data[1] << 8) | data[0];             // Get the raw temperature
        cfg = (data[4] & 0x60);                     // Read the config (just in case)
        if (cfg == 0x00)      raw = raw & ~7;       // 9-bit raw adjustment
        else if (cfg == 0x20) raw = raw & ~3;       // 10-bit raw adjustment
        else if (cfg == 0x40) raw = raw & ~1;       // 11-bit raw adjustment
        temp->temp = (float) raw / 16.0;            // Convert to celsius and store the temp
        temp = temp->next;                          // Switch to the next sensor in the list
    }

    // Step 6: Invoke the callback
    callback(list);

    // Step 7: Cleanup
    while ( list != NULL ) {                        // Loop over all device results
        temp = list->next;                          // Store a ref to the next device
        free(list->mac);                            // Free up the MAC address string
        free(list);                                 // Free up the struct
        list = temp;                                // Cleanup next device
    }
    mgos_onewire_close(ow);                         // Close one wire
}

bool mgos_mongoose_os_ds18b20_init(void) {
    return true;
}


text:
ALTER TABLE batches ADD COLUMN format_version INT NOT NULL DEFAULT 1;
ALTER TABLE batches MODIFY COLUMN format_version INT NOT NULL;

CREATE TABLE IF NOT EXISTS `batch_bunches` (
  `batch_id` BIGINT NOT NULL,
  `start_job_id` INT NOT NULL,
  `token` VARCHAR(100) NOT NULL,
  PRIMARY KEY (`batch_id`, `start_job_id`),
  FOREIGN KEY (`batch_id`, `start_job_id`) REFERENCES jobs(batch_id, job_id) ON DELETE CASCADE
) ENGINE = InnoDB;

ALTER TABLE instances ADD COLUMN version INT NOT NULL DEFAULT 1;
ALTER TABLE instances MODIFY COLUMN version INT NOT NULL;

DELIMITER $$

DROP PROCEDURE IF EXISTS mark_job_complete;
CREATE PROCEDURE mark_job_complete(
  IN in_batch_id BIGINT,
  IN in_job_id INT,
  IN in_attempt_id VARCHAR(40),
  IN in_instance_name VARCHAR(100),
  IN new_state VARCHAR(40),
  IN new_status TEXT,
  IN new_start_time BIGINT,
  IN new_end_time BIGINT,
  IN new_reason VARCHAR(40),
  IN new_timestamp BIGINT
)
BEGIN
  DECLARE cur_job_state VARCHAR(40);
  DECLARE cur_instance_state VARCHAR(40);
  DECLARE cur_cores_mcpu INT;
  DECLARE cur_end_time BIGINT;
  DECLARE delta_cores_mcpu INT DEFAULT 0;
  DECLARE expected_attempt_id VARCHAR(40);

  START TRANSACTION;

  SELECT state, cores_mcpu
  INTO cur_job_state, cur_cores_mcpu
  FROM jobs
  WHERE batch_id = in_batch_id AND job_id = in_job_id
  FOR UPDATE;

  CALL add_attempt(in_batch_id, in_job_id, in_attempt_id, in_instance_name, cur_cores_mcpu, delta_cores_mcpu);

  SELECT end_time INTO cur_end_time FROM attempts
  WHERE batch_id = in_batch_id AND job_id = in_job_id AND attempt_id = in_attempt_id
  FOR UPDATE;

  UPDATE attempts
  SET start_time = new_start_time, end_time = new_end_time, reason = new_reason
  WHERE batch_id = in_batch_id AND job_id = in_job_id AND attempt_id = in_attempt_id;

  SELECT state INTO cur_instance_state FROM instances WHERE name = in_instance_name FOR UPDATE;
  IF cur_instance_state = 'active' AND cur_end_time IS NULL THEN
    UPDATE instances
    SET free_cores_mcpu = free_cores_mcpu + cur_cores_mcpu
    WHERE name = in_instance_name;

    SET delta_cores_mcpu = delta_cores_mcpu + cur_cores_mcpu;
  END IF;

  SELECT attempt_id INTO expected_attempt_id FROM jobs
  WHERE batch_id = in_batch_id AND job_id = in_job_id
  FOR UPDATE;

  IF expected_attempt_id != in_attempt_id THEN
    COMMIT;
    SELECT 2 as rc,
      expected_attempt_id,
      delta_cores_mcpu,
      'input attempt id does not match expected attempt id' as message;
  ELSEIF cur_job_state = 'Ready' OR cur_job_state = 'Running' THEN
    UPDATE jobs
    SET state = new_state, status = new_status
    WHERE batch_id = in_batch_id AND job_id = in_job_id;

    UPDATE batches SET n_completed = n_completed + 1 WHERE id = in_batch_id;
    UPDATE batches
      SET time_completed = new_timestamp,
          `state` = 'complete'
      WHERE id = in_batch_id AND n_completed = batches.n_jobs;

    IF new_state = 'Cancelled' THEN
      UPDATE batches SET n_cancelled = n_cancelled + 1 WHERE id = in_batch_id;
    ELSEIF new_state = 'Error' OR new_state = 'Failed' THEN
      UPDATE batches SET n_failed = n_failed + 1 WHERE id = in_batch_id;
    ELSE
      UPDATE batches SET n_succeeded = n_succeeded + 1 WHERE id = in_batch_id;
    END IF;

    UPDATE jobs
      INNER JOIN `job_parents`
        ON jobs.batch_id = `job_parents`.batch_id AND
           jobs.job_id = `job_parents`.job_id
      SET jobs.state = IF(jobs.n_pending_parents = 1, 'Ready', 'Pending'),
          jobs.n_pending_parents = jobs.n_pending_parents - 1,
          jobs.cancelled = IF(new_state = 'Success', jobs.cancelled, 1)
      WHERE jobs.batch_id = in_batch_id AND
            `job_parents`.batch_id = in_batch_id AND
            `job_parents`.parent_id = in_job_id;

    COMMIT;
    SELECT 0 as rc,
      cur_job_state as old_state,
      delta_cores_mcpu;
  ELSEIF cur_job_state = 'Cancelled' OR cur_job_state = 'Error' OR
         cur_job_state = 'Failed' OR cur_job_state = 'Success' THEN
    COMMIT;
    SELECT 0 as rc,
      cur_job_state as old_state,
      delta_cores_mcpu;
  ELSE
    COMMIT;
    SELECT 1 as rc,
      cur_job_state,
      delta_cores_mcpu,
      'job state not Ready, Running or complete' as message;
  END IF;
END $$

DROP TRIGGER IF EXISTS attempts_before_update;
CREATE TRIGGER attempts_before_update BEFORE UPDATE ON attempts
FOR EACH ROW
BEGIN
  IF OLD.start_time IS NOT NULL AND (NEW.start_time IS NULL OR NEW.start_time < OLD.start_time) THEN
    SET NEW.start_time = OLD.start_time;
  END IF;

  IF OLD.reason IS NOT NULL AND (OLD.end_time IS NULL OR NEW.end_time IS NULL OR NEW.end_time >= OLD.end_time) THEN
    SET NEW.end_time = OLD.end_time;
    SET NEW.reason = OLD.reason;
  END IF;
END $$

DELIMITER ;


text:
(function(){
    "use strict";

    angular.module('app.controllers').controller('FavoriteCtrl', function(){
        //
    });

})();


text:
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var app = express();

app.set('port', (process.env.PORT || 5000));
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');

app.use(session({
    secret: 'secretstuffs',
    resave: 'true',
    saveUninitialized: 'true'
}));
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(__dirname + '/public'));
app.use(require('./controllers'));

app.listen(app.get('port'));