text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The DarkCoin developers
// Copyright (c) 2018 The Denarius developers
// Copyright (c) 2018 The Bzlcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode.h"
#include "activemasternode.h"
#include "darksend.h"
#include "txdb.h"
#include "main.h"
#include "util.h"
#include "addrman.h"
#include "sync.h"
#include "core.h"
#include <boost/lexical_cast.hpp>

int CMasterNode::minProtoVersion = MIN_MN_PROTO_VERSION;

CCriticalSection cs_masternodes;

/** The list of active masternodes */
std::vector<CMasterNode> vecMasternodes;
std::vector<pair<int, CMasterNode*> > vecMasternodeScores;
std::vector<pair<int, CMasterNode> > vecMasternodeRanks;
/** Object for who's going to get paid on which blocks */
CMasternodePayments masternodePayments;
// keep track of masternode votes I've seen
map<uint256, CMasternodePaymentWinner> mapSeenMasternodeVotes;
// keep track of the scanning errors I've seen
map<uint256, int> mapSeenMasternodeScanningErrors;
// who's asked for the masternode list and the last time
std::map<CNetAddr, int64_t> askedForMasternodeList;
// which masternodes we've asked for
std::map<COutPoint, int64_t> askedForMasternodeListEntry;
// cache block hashes as we calculate them
std::map<int64_t, uint256> mapCacheBlockHashes;
CMedianFilter<unsigned int> mnMedianCount(10, 0);
unsigned int mnCount;

// manage the masternode connections
void ProcessMasternodeConnections(){
    LOCK(cs_vNodes);

    BOOST_FOREACH(CNode* pnode, vNodes)
    {
        //if it's our masternode, let it be
        if(darkSendPool.submittedToMasternode == pnode->addr) continue;

        if( pnode->fDarkSendMaster ||
            (pnode->addr.GetPort() == 27777 && pnode->nStartingHeight > (nBestHeight - 120)) // disconnect masternodes that were in sync when they connected recently
                )
        {
            printf("Closing masternode connection %s \n", pnode->addr.ToString().c_str());
            pnode->CloseSocketDisconnect();
        }
    }
}

void ProcessMessageMasternode(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{

    if (strCommand == "dsee") { //DarkSend Election Entry

        bool fIsInitialDownload = IsInitialBlockDownload();
        if(fIsInitialDownload) return;

        CTxIn vin;
        CService addr;
        CPubKey pubkey;
        CPubKey pubkey2;
        vector<unsigned char> vchSig;
        int64_t sigTime;
        int count;
        int current;
        int64_t lastUpdated;
        int protocolVersion;
        std::string strMessage;

        // 70047 and greater
        vRecv >> vin >> addr >> vchSig >> sigTime >> pubkey >> pubkey2 >> count >> current >> lastUpdated >> protocolVersion;

        // make sure signature isn't in the future (past is OK)
        if (sigTime > GetAdjustedTime() + 60 * 60) {
            printf("dsee - Signature rejected, too far into the future %s\n", vin.ToString().c_str());
            return;
        }

        bool isLocal = addr.IsRFC1918() || addr.IsLocal();
        //if(Params().MineBlocksOnDemand()) isLocal = false;

        std::string vchPubKey(pubkey.begin(), pubkey.end());
        std::string vchPubKey2(pubkey2.begin(), pubkey2.end());

        strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);

        if(protocolVersion < MIN_MN_PROTO_VERSION) {
            printf("dsee - ignoring outdated masternode %s protocol version %d\n", vin.ToString().c_str(), protocolVersion);
            return;
        }

        CScript pubkeyScript;
        pubkeyScript = GetScriptForDestination(pubkey.GetID());

        if(pubkeyScript.size() != 25) {
            printf("dsee - pubkey the wrong size\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        CScript pubkeyScript2;
        pubkeyScript2 =GetScriptForDestination(pubkey2.GetID());

        if(pubkeyScript2.size() != 25) {
            printf("dsee - pubkey2 the wrong size\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        std::string errorMessage = "";
        if(!darkSendSigner.VerifyMessage(pubkey, vchSig, strMessage, errorMessage)){
            printf("dsee - Got bad masternode address signature\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        if((fTestNet && addr.GetPort() != 27776) || (!fTestNet && addr.GetPort() != 27777)) return;

        //search existing masternode list, this is where we update existing masternodes with new dsee broadcasts
	      LOCK(cs_masternodes);
        BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
            if(mn.vin.prevout == vin.prevout) {
                // count == -1 when it's a new entry
                //   e.g. We don't want the entry relayed/time updated when we're syncing the list
                // mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below,
                //   after that they just need to match
                if(count == -1 && mn.pubkey == pubkey && !mn.UpdatedWithin(MASTERNODE_MIN_DSEE_SECONDS)){
                    mn.UpdateLastSeen();

                    if(mn.now < sigTime){ //take the newest entry
                        printf("dsee - Got updated entry for %s\n", addr.ToString().c_str());
                        mn.pubkey2 = pubkey2;
                        mn.now = sigTime;
                        mn.sig = vchSig;
                        mn.protocolVersion = protocolVersion;
                        mn.addr = addr;

                        RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion);
                    }
                }

                return;
            }
        }

        // make sure the vout that was signed is related to the transaction that spawned the masternode
        //  - this is expensive, so it's only done once per masternode
        if(!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubkey)) {
            printf("dsee - Got mismatched pubkey and vin\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        if(fDebug) printf("dsee - Got NEW masternode entry %s\n", addr.ToString().c_str());

        // make sure it's still unspent
        //  - this is checked later by .check() in many places and by ThreadCheckDarkSendPool()
        std::string vinError;
        if(CheckMasternodeVin(vin,vinError)){
            if (fDebugNet) printf("dsee - Accepted input for masternode entry %i %i\n", count, current);

            if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){
                if (fDebugNet) printf("dsee - Input must have least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS);
                Misbehaving(pfrom->GetId(), 20);
                return;
            }

            // use this as a peer
            addrman.Add(CAddress(addr), pfrom->addr, 2*60*60);

            // add our masternode
            CMasterNode mn(addr, vin, pubkey, vchSig, sigTime, pubkey2, protocolVersion);
            mn.UpdateLastSeen(lastUpdated);
            CBlockIndex* pindex = pindexBest;
            mn.UpdateLastPaidBlock(pindex, 1000); // do a search back 1000 blocks when receiving a new masternode to find their last payment
            vecMasternodes.push_back(mn);

            // if it matches our masternodeprivkey, then we've been remotely activated
            if(pubkey2 == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION){
                activeMasternode.EnableHotColdMasterNode(vin, addr);
            }

            if(count == -1 && !isLocal)
                RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion);
            if (count > 0) {
                mnMedianCount.input(count);
                mnCount = mnMedianCount.median();
            }

        } else {
            printf("dsee - Rejected masternode entry %s: %s\n", addr.ToString().c_str(),vinError.c_str());
        }
    }

    else if (strCommand == "dseep") { //DarkSend Election Entry Ping
        bool fIsInitialDownload = IsInitialBlockDownload();
        if(fIsInitialDownload) return;

        CTxIn vin;
        vector<unsigned char> vchSig;
        int64_t sigTime;
        bool stop;
        vRecv >> vin >> vchSig >> sigTime >> stop;

        if (fDebug) printf("dseep - Received: vin: %s sigTime: %lld stop: %s\n", vin.ToString().c_str(), sigTime, stop ? "true" : "false");

        if (sigTime > GetAdjustedTime() + 60 * 60) {
            printf("dseep - Signature rejected, too far into the future %s\n", vin.ToString().c_str());
            return;
        }

        if (sigTime <= GetAdjustedTime() - 60 * 60) {
            printf("dseep - Signature rejected, too far into the past %s - %d %d \n", vin.ToString().c_str(), sigTime, GetAdjustedTime());
            return;
        }

        // see if we have this masternode
	      LOCK(cs_masternodes);
        BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
            if(mn.vin.prevout == vin.prevout) {
            	// printf("dseep - Found corresponding mn for vin: %s\n", vin.ToString().c_str());
            	// take this only if it's newer
                if(mn.lastDseep < sigTime){
                    std::string strMessage = mn.addr.ToString() + boost::lexical_cast<std::string>(sigTime) + boost::lexical_cast<std::string>(stop);

                    std::string errorMessage = "";
                    if(!darkSendSigner.VerifyMessage(mn.pubkey2, vchSig, strMessage, errorMessage)){
                        printf("dseep - Got bad masternode address signature %s \n", vin.ToString().c_str());
                        //Misbehaving(pfrom->GetId(), 100);
                        return;
                    }

                    mn.lastDseep = sigTime;

                    if(!mn.UpdatedWithin(MASTERNODE_MIN_DSEEP_SECONDS)){
                        mn.UpdateLastSeen();
                        if(stop) {
                            mn.Disable();
                            mn.Check(true);
                        }
                        RelayDarkSendElectionEntryPing(vin, vchSig, sigTime, stop);
                    }
                }
                return;
            }
        }

        if (fDebugNet) printf("dseep - Couldn't find masternode entry %s\n", vin.ToString().c_str());

        std::map<COutPoint, int64_t>::iterator i = askedForMasternodeListEntry.find(vin.prevout);
        if (i != askedForMasternodeListEntry.end()){
            int64_t t = (*i).second;
            if (GetTime() < t) {
                // we've asked recently
                return;
            }
        }

        // ask for the dsee info once from the node that sent dseep

        if (fDebugNet) printf("dseep - Asking source node for missing entry %s\n", vin.ToString().c_str());
        pfrom->PushMessage("dseg", vin);
        int64_t askAgain = GetTime()+(60*60*1); // only ask for each dsee once per hour
        askedForMasternodeListEntry[vin.prevout] = askAgain;

    } else if (strCommand == "dseg") { //Get masternode list or specific entry
        bool fIsInitialDownload = IsInitialBlockDownload();
        if(fIsInitialDownload) return;

        CTxIn vin;
        vRecv >> vin;

        if(vin == CTxIn()) { //only should ask for this once
            //local network
            //Note tor peers show up as local proxied addrs
            //if(!pfrom->addr.IsRFC1918())//&& !Params().MineBlocksOnDemand())
            //{
              if(!pfrom->addr.IsRFC1918())
              {
                std::map<CNetAddr, int64_t>::iterator i = askedForMasternodeList.find(pfrom->addr);
                if (i != askedForMasternodeList.end())
                {
                    int64_t t = (*i).second;
                    if (GetTime() < t) {
                        //Misbehaving(pfrom->GetId(), 34);
                        //printf("dseg - peer already asked me for the list\n");
                        //return;
                        Misbehaving(pfrom->GetId(), 34);
                        printf("dseg - peer already asked me for the list\n");
                        return;
                    }
                }

                int64_t askAgain = GetTime()+(60*60*1); // only allow nodes to do a dseg all once per hour
                askedForMasternodeList[pfrom->addr] = askAgain;
            //}
              }
        } //else, asking for a specific node which is ok

	      LOCK(cs_masternodes);
        int count = vecMasternodes.size();
        int i = 0;

        BOOST_FOREACH(CMasterNode mn, vecMasternodes) {

            if(mn.addr.IsRFC1918()) continue; //local network

            if(vin == CTxIn()){
                mn.Check(true);
                if(mn.IsEnabled()) {
                    if(fDebug) printf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str());
                    pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion);
                }
            } else if (vin == mn.vin) {
                if(fDebug) printf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str());
                pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion);
                printf("dseg - Sent 1 masternode entries to %s\n", pfrom->addr.ToString().c_str());
                return;
            }
            i++;
        }

        printf("dseg - Sent %d masternode entries to %s\n", count, pfrom->addr.ToString().c_str());
    }

    else if (strCommand == "mnget") { //Masternode Payments Request Sync
        bool fIsInitialDownload = IsInitialBlockDownload();
        if(fIsInitialDownload) return;

        if(pfrom->HasFulfilledRequest("mnget")) {
            printf("mnget - peer already asked me for the list\n");
            Misbehaving(pfrom->GetId(), 20);
            return;
        }

        pfrom->FulfilledRequest("mnget");
        masternodePayments.Sync(pfrom);
        printf("mnget - Sent masternode winners to %s\n", pfrom->addr.ToString().c_str());
    }
    else if (strCommand == "mnw") { //Masternode Payments Declare Winner
        bool fIsInitialDownload = IsInitialBlockDownload();
        if(fIsInitialDownload) return;

        CMasternodePaymentWinner winner;
        int a = 0;
        vRecv >> winner >> a;

        if(pindexBest == NULL) return;

        uint256 hash = winner.GetHash();
        if(mapSeenMasternodeVotes.count(hash)) {
            if(fDebug) printf("mnw - seen vote %s Height %d bestHeight %d\n", hash.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
            return;
        }

        if(winner.nBlockHeight < pindexBest->nHeight - 10 || winner.nBlockHeight > pindexBest->nHeight+20){
            printf("mnw - winner out of range %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);
            return;
        }

        if(winner.vin.nSequence != std::numeric_limits<unsigned int>::max()){
            printf("mnw - invalid nSequence\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        printf("mnw - winning vote  %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight);

        if(!masternodePayments.CheckSignature(winner)){
            printf("mnw - invalid signature\n");
            Misbehaving(pfrom->GetId(), 100);
            return;
        }

        mapSeenMasternodeVotes.insert(make_pair(hash, winner));

        if(masternodePayments.AddWinningMasternode(winner)){
            masternodePayments.Relay(winner);
        }
    }
}

struct CompareValueOnly
{
    bool operator()(const pair<int64_t, CTxIn>& t1,
                    const pair<int64_t, CTxIn>& t2) const
    {
        return t1.first < t2.first;
    }
};

struct CompareLastPaidBlock
{
    bool operator()(const pair<int, CMasterNode*>& t1,
                    const pair<int, CMasterNode*>& t2) const
    {
        return (t1.first != t2.first ? t1.first > t2.first : t1.second->CalculateScore(1, pindexBest->nHeight) > t1.second->CalculateScore(1, pindexBest->nHeight));
    }
};

struct CompareValueOnly2
{
    bool operator()(const pair<int64_t, int>& t1,
                    const pair<int64_t, int>& t2) const
    {
        return t1.first < t2.first;
    }
};

int CountMasternodesAboveProtocol(int protocolVersion)
{
    int i = 0;
    LOCK(cs_masternodes);
    BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
        if(mn.protocolVersion < protocolVersion) continue;
        i++;
    }

    return i;
}

int GetMasternodeByVin(CTxIn& vin)
{
    int i = 0;
    LOCK(cs_masternodes);
    BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
        if (mn.vin == vin) return i;
        i++;
    }

    return -1;
}

int GetCurrentMasterNode(int mod, int64_t nBlockHeight, int minProtocol)
{
    int i = 0;
    unsigned int score = 0;
    int winner = -1;
    LOCK(cs_masternodes);
    // scan for winner
    BOOST_FOREACH(CMasterNode mn, vecMasternodes) {
        mn.Check();
        if(mn.protocolVersion < minProtocol) continue;
        if(!mn.IsEnabled()) {
            i++;
            continue;
        }

        // calculate the score for each masternode
        uint256 n = mn.CalculateScore(mod, nBlockHeight);
        unsigned int n2 = 0;
        memcpy(&n2, &n, sizeof(n2));

        // determine the winner
        if(n2 > score){
            score = n2;
            winner = i;
        }
        i++;
    }

    return winner;
}
bool GetMasternodeRanks()
{
    if (masternodePayments.vecMasternodeRanksLastUpdated == pindexBest->nHeight)
        return true;

    // std::vector<pair<int, CMasterNode*> > vecMasternodeScores;

    vecMasternodeScores.clear();

    BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {

        mn.Check();
        if(mn.protocolVersion < MIN_MN_PROTO_VERSION) continue;

        if (!mn.nBlockLastPaid || mn.nBlockLastPaid == 0)
        {
            CBlockIndex* pindex = pindexBest;
            mn.UpdateLastPaidBlock(pindex, 2880); // search back 1 day
        }
        vecMasternodeScores.push_back(make_pair(mn.nBlockLastPaid, &mn));
    }

    sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareLastPaidBlock());

    masternodePayments.vecMasternodeRanksLastUpdated = pindexBest->nHeight;
    return true;
}

int GetMasternodeRank(CMasterNode &tmn, int64_t nBlockHeight, int minProtocol)
{
    LOCK(cs_masternodes);
    GetMasternodeRanks();
    unsigned int i = 0;

    BOOST_FOREACH(PAIRTYPE(int, CMasterNode*)& s, vecMasternodeScores)
    {
        i++;
        if (s.second->vin == tmn.vin)
            return i;
    }
}

int GetMasternodeByRank(int findRank, int64_t nBlockHeight, int minProtocol)
{
    LOCK(cs_masternodes);
    GetMasternodeRanks();
    unsigned int i = 0;

    BOOST_FOREACH(PAIRTYPE(int, CMasterNode*)& s, vecMasternodeScores)
    {
        i++;
        if (i == findRank)
            return s.first;
    }
}

//Get the last hash that matches the modulus given. Processed in reverse order
bool GetBlockHash(uint256& hash, int nBlockHeight)
{
    if (pindexBest == NULL) return false;

    if(nBlockHeight == 0)
        nBlockHeight = pindexBest->nHeight;

    if(mapCacheBlockHashes.count(nBlockHeight)){
        hash = mapCacheBlockHashes[nBlockHeight];
        return true;
    }

    const CBlockIndex *BlockLastSolved = pindexBest;
    const CBlockIndex *BlockReading = pindexBest;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || pindexBest->nHeight+1 < nBlockHeight) return false;

    int nBlocksAgo = 0;
    if(nBlockHeight > 0) nBlocksAgo = (pindexBest->nHeight+1)-nBlockHeight;
    assert(nBlocksAgo >= 0);

    int n = 0;
    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if(n >= nBlocksAgo){
            hash = BlockReading->GetBlockHash();
            mapCacheBlockHashes[nBlockHeight] = hash;
            return true;
        }
        n++;

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    return false;
}

void CMasterNode::UpdateLastPaidBlock(const CBlockIndex *pindex, int nMaxBlocksToScanBack)
{
    if(!pindex) return;

    const CBlockIndex *BlockReading = pindex;

    CScript mnpayee = GetScriptForDestination(pubkey.GetID());
    CTxDestination address1;
    ExtractDestination(mnpayee, address1);
    CBitcoinAddress address2(address1);

    uint64_t nCoinAge;

    for (int i = 0; BlockReading && BlockReading->nHeight > nBlockLastPaid && i < nMaxBlocksToScanBack; i++) {
            CBlock block;
            if(!block.ReadFromDisk(BlockReading, true)) // shouldn't really happen
                continue;

    /*  no amount checking for now
     * TODO: Scan block for payments to calculate reward
            // Calculate Coin Age for Masternode Reward Calculation
            if (!block.vtx[1].GetCoinAge(txdb, nCoinAge))
                return error("CheckBlock-POS : %s unable to get coin age for coinstake, Can't Calculate Masternode Reward\n", block.vtx[1].GetHash().ToString().substr(0,10).c_str());
            int64_t nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, nFees);
            int64_t nMasternodePayment = GetMasternodePayment(BlockReading->nHeight, block.IsProofOfStake() ? nCalculatedStakeReward : block.vtx[0].GetValueOut());
    */
            if (block.IsProofOfWork())
            {
                // TODO HERE: Scan the block for masternode payment amount
                BOOST_FOREACH(CTxOut txout, block.vtx[0].vout)
                    if(mnpayee == txout.scriptPubKey) {
                        nBlockLastPaid = BlockReading->nHeight;
                        nTimeLastPaid = BlockReading->nTime;
                        int lastPay = pindexBest->nHeight - nBlockLastPaid;
                        // TODO HERE: Check the nValue for the masternode payment amount
                        if (fDebug) printf("CMasterNode::UpdateLastPaidBlock -- searching for block with payment to %s -- found pow %d (%d blocks ago)\n", address2.ToString().c_str(), nBlockLastPaid, lastPay);
                        return;
                    }
            } else if (block.IsProofOfStake())
            {
                // TODO HERE: Scan the block for masternode payment amount
                BOOST_FOREACH(CTxOut txout, block.vtx[1].vout)
                    if(mnpayee == txout.scriptPubKey) {
                        nBlockLastPaid = BlockReading->nHeight;
                        nTimeLastPaid = BlockReading->nTime;
                        int lastPay = pindexBest->nHeight - nBlockLastPaid;
                        // TODO HERE: Check the nValue for the masternode payment amount
                        if (fDebug) printf("CMasterNode::UpdateLastPaidBlock -- searching for block with payment to %s -- found pos %d (%d blocks ago)\n", address2.ToString().c_str(), nBlockLastPaid, lastPay);
                        return;
                    }
            }

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }

        BlockReading = BlockReading->pprev;
    }
    if (!nBlockLastPaid)
    {
        if (fDebug) printf("CMasternode::UpdateLastPaidBlock -- searching for block with payment to %s e.g. %s -- NOT FOUND\n", vin.prevout.ToString().c_str(),address2.ToString().c_str());
        nBlockLastPaid = 1;
    }
}

//
// Deterministically calculate a given "score" for a masternode depending on how close it's hash is to
// the proof of work for that block. The further away they are the better, the furthest will win the election
// and get paid this block
//
uint256 CMasterNode::CalculateScore(int mod, int64_t nBlockHeight)
{
    if(pindexBest == NULL) return 0;

    uint256 hash = 0;
    uint256 aux = vin.prevout.hash + vin.prevout.n;

    if(!GetBlockHash(hash, nBlockHeight)) return 0;

    uint256 hash2 = Tribus(BEGIN(hash), END(hash)); //Tribus Algo Integrated, WIP
    uint256 hash3 = Tribus(BEGIN(hash), END(aux));

    uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3);

    return r;
}

void CMasterNode::Check(bool forceCheck)
{
    if(!forceCheck && (GetTime() - lastTimeChecked < MASTERNODE_CHECK_SECONDS)) return;
    lastTimeChecked = GetTime();

    //once spent, stop doing the checks
    if(enabled==3) return;

    if(!UpdatedWithin(MASTERNODE_REMOVAL_SECONDS)){
        enabled = 4;
        return;
    }

    if(!UpdatedWithin(MASTERNODE_EXPIRATION_SECONDS)){
        enabled = 2;
        return;
    }

    if(!unitTest){
        std::string vinError;
        if(!CheckMasternodeVin(vin,vinError)) {
                enabled = 3; //MN input was spent, disable checks for this MN
                if (fDebug) printf("error checking masternode %s: %s\n", vin.prevout.ToString().c_str(), vinError.c_str());
                return;
            }
        }

    enabled = 1; // OK
}

bool CheckMasternodeVin(CTxIn& vin, std::string& errorMessage) {
    CTxDB txdb("r");
    CTxIndex txindex;
    CTransaction ctx;
    uint256 hashBlock;

    if (!GetTransaction(vin.prevout.hash,ctx,hashBlock))
    {
        errorMessage = "could not find transaction";
        return false;
    }

    CTxOut vout = ctx.vout[vin.prevout.n];
	CBlockIndex *blockIndexAux;
	blockIndexAux = mapBlockIndex[hashBlock];
	if (vout.nValue != GetMNCollateralForBlock(blockIndexAux->nHeight)*COIN)
    {
        errorMessage = "specified vin was not a masternode capable transaction";
        return false;
    }

    if (txdb.ReadTxIndex(vin.prevout.hash, txindex))
    {
        if (txindex.vSpent[vin.prevout.n].nTxPos != 0) {
            errorMessage = "vin was spent";
            return false;
        }
        return true;
    } else {
        errorMessage = "specified vin transaction was not found in the txindex\n";
    }
    return false;
}

bool CMasternodePayments::CheckSignature(CMasternodePaymentWinner& winner)
{
    //note: need to investigate why this is failing
    std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast<std::string>(winner.nBlockHeight) + winner.payee.ToString();
    std::string strPubKey = fTestNet? strTestPubKey : strMainPubKey;
    CPubKey pubkey(ParseHex(strPubKey));

    std::string errorMessage = "";
    if(!darkSendSigner.VerifyMessage(pubkey, winner.vchSig, strMessage, errorMessage)){
        return false;
    }

    return true;
}

bool CMasternodePayments::Sign(CMasternodePaymentWinner& winner)
{
    std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast<std::string>(winner.nBlockHeight) + winner.payee.ToString();

    CKey key2;
    CPubKey pubkey2;
    std::string errorMessage = "";

    if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2))
    {
        printf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str());
        return false;
    }

    if(!darkSendSigner.SignMessage(strMessage, errorMessage, winner.vchSig, key2)) {
        printf("CMasternodePayments::Sign - Sign message failed");
        return false;
    }

    if(!darkSendSigner.VerifyMessage(pubkey2, winner.vchSig, strMessage, errorMessage)) {
        printf("CMasternodePayments::Sign - Verify message failed");
        return false;
    }

    return true;
}

uint64_t CMasternodePayments::CalculateScore(uint256 blockHash, CTxIn& vin)
{
    uint256 n1 = blockHash;
    uint256 n2 = Tribus(BEGIN(n1), END(n1));
    uint256 n3 = Tribus(BEGIN(vin.prevout.hash), END(vin.prevout.hash));
    uint256 n4 = n3 > n2 ? (n3 - n2) : (n2 - n3);

    //printf(" -- CMasternodePayments CalculateScore() n2 = %d \n", n2.Get64());
    //printf(" -- CMasternodePayments CalculateScore() n3 = %d \n", n3.Get64());
    //printf(" -- CMasternodePayments CalculateScore() n4 = %d \n", n4.Get64());

    return n4.Get64();
}

bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee)
{
    CBlockIndex *blockIndexAux;
    BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){
        if(winner.nBlockHeight == nBlockHeight) {
            CTransaction tx;
            uint256 hash;
            if(GetTransaction(winner.vin.prevout.hash, tx, hash)){
                BOOST_FOREACH(CTxOut out, tx.vout){
                    blockIndexAux = mapBlockIndex[hash];
                    if(out.nValue == GetMNCollateralForBlock(blockIndexAux->nHeight)*COIN){
                        payee = out.scriptPubKey;
                        return true;
                    }
                }
            }
            return false;
        }
    }
    return false;
}

bool CMasternodePayments::GetWinningMasternode(int nBlockHeight, CTxIn& vinOut)
{
    BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){
        if(winner.nBlockHeight == nBlockHeight) {
            vinOut = winner.vin;
            return true;
        }
    }

    return false;
}

bool CMasternodePayments::AddWinningMasternode(CMasternodePaymentWinner& winnerIn)
{
    uint256 blockHash = 0;
    if(!GetBlockHash(blockHash, winnerIn.nBlockHeight-576)) {
        return false;
    }

    winnerIn.score = CalculateScore(blockHash, winnerIn.vin);

    bool foundBlock = false;
    BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){
        if(winner.nBlockHeight == winnerIn.nBlockHeight) {
            foundBlock = true;
            if(winner.score < winnerIn.score){
                winner.score = winnerIn.score;
                winner.vin = winnerIn.vin;
                winner.payee = winnerIn.payee;
                winner.vchSig = winnerIn.vchSig;

                return true;
            }
        }
    }

    // if it's not in the vector
    if(!foundBlock){
        vWinning.push_back(winnerIn);
        mapSeenMasternodeVotes.insert(make_pair(winnerIn.GetHash(), winnerIn));

        return true;
    }

    return false;
}

void CMasternodePayments::CleanPaymentList()
{
    LOCK(cs_masternodes);
    if(pindexBest == NULL) return;

    int nLimit = std::max(((int)vecMasternodes.size())*2, 5000);

    vector<CMasternodePaymentWinner>::iterator it;
    for(it=vWinning.begin();it<vWinning.end();it++){
        if(pindexBest->nHeight - (*it).nBlockHeight > nLimit){
            if(fDebug) printf("CMasternodePayments::CleanPaymentList - Removing old masternode payment - block %d\n", (*it).nBlockHeight);
            vWinning.erase(it);
            break;
        }
    }
}

int CMasternodePayments::LastPayment(CMasterNode& mn)
{
    if(pindexBest == NULL) return 0;

    int ret = mn.GetMasternodeInputAge();

    BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){
        if(winner.vin == mn.vin && pindexBest->nHeight - winner.nBlockHeight < ret)
            ret = pindexBest->nHeight - winner.nBlockHeight;
    }

    return ret;
}

bool CMasternodePayments::ProcessBlock(int nBlockHeight)
{
    LOCK(cs_masternodes);
    if(!enabled) return false; // don't process blocks for masternode winners if we aren't signing a winner list
    CMasternodePaymentWinner winner;

    std::vector<CTxIn> vecLastPayments;
    int c = 0;
    BOOST_REVERSE_FOREACH(CMasternodePaymentWinner& winner, vWinning){
        vecLastPayments.push_back(winner.vin);
        //if we have one full payment cycle, break
        if(++c > (int)vecMasternodes.size()) break;
    }

    std::random_shuffle ( vecMasternodes.begin(), vecMasternodes.end() );
    BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
        bool found = false;
        BOOST_FOREACH(CTxIn& vin, vecLastPayments)
            if(mn.vin == vin) found = true;

        if(found) continue;

        mn.Check();
        if(!mn.IsEnabled()) {
            continue;
        }

        winner.score = 0;
        winner.nBlockHeight = nBlockHeight;
        winner.vin = mn.vin;
        winner.payee =GetScriptForDestination(mn.pubkey.GetID());

        break;
    }

    //if we can't find someone to get paid, pick randomly
    if(winner.nBlockHeight == 0 && vecMasternodes.size() > 0) {
        winner.score = 0;
        winner.nBlockHeight = nBlockHeight;
        winner.vin = vecMasternodes[0].vin;
        winner.payee =GetScriptForDestination(vecMasternodes[0].pubkey.GetID());
    }

    if(CMasternodePayments::enabled && Sign(winner)){
        if(AddWinningMasternode(winner)){
            Relay(winner);
            return true;
        }
    }

    return false;
}

void CMasternodePayments::Relay(CMasternodePaymentWinner& winner)
{
    CInv inv(MSG_MASTERNODE_WINNER, winner.GetHash());

    vector<CInv> vInv;
    vInv.push_back(inv);
    LOCK(cs_vNodes);
    BOOST_FOREACH(CNode* pnode, vNodes){
        pnode->PushMessage("inv", vInv);
    }
}

void CMasternodePayments::Sync(CNode* node)
{
    int a = 0;
    BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning)
        if(winner.nBlockHeight >= pindexBest->nHeight-10 && winner.nBlockHeight <= pindexBest->nHeight + 20)
            node->PushMessage("mnw", winner, a);
}

bool CMasternodePayments::SetPrivKey(std::string strPrivKey)
{
    CMasternodePaymentWinner winner;

    // Test signing successful, proceed
    strMasterPrivKey = strPrivKey;

    Sign(winner);

    if(CheckSignature(winner)){
        printf("CMasternodePayments::SetPrivKey - Successfully initialized as masternode payments master\n");
        enabled = true;
        return true;
    } else {
        return false;
    }
}


text:
.class Landroid/media/IRemoteVolumeController$Stub$Proxy;
.super Ljava/lang/Object;
.source "IRemoteVolumeController.java"

# interfaces
.implements Landroid/media/IRemoteVolumeController;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/IRemoteVolumeController$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .locals 0
    .param p1, "remote"    # Landroid/os/IBinder;

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

    .line 77
    iput-object p1, p0, Landroid/media/IRemoteVolumeController$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 75
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 1

    .prologue
    .line 81
    iget-object v0, p0, Landroid/media/IRemoteVolumeController$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .locals 1

    .prologue
    .line 85
    const-string/jumbo v0, "android.media.IRemoteVolumeController"

    return-object v0
.end method

.method public remoteVolumeChanged(Landroid/media/session/ISessionController;I)V
    .locals 5
    .param p1, "session"    # Landroid/media/session/ISessionController;
    .param p2, "flags"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    const/4 v1, 0x0

    .line 89
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 91
    .local v0, "_data":Landroid/os/Parcel;
    :try_start_0
    const-string/jumbo v2, "android.media.IRemoteVolumeController"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 92
    if-eqz p1, :cond_0

    invoke-interface {p1}, Landroid/media/session/ISessionController;->asBinder()Landroid/os/IBinder;

    move-result-object v1

    :cond_0
    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    .line 93
    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeInt(I)V

    .line 94
    iget-object v1, p0, Landroid/media/IRemoteVolumeController$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v2, 0x1

    const/4 v3, 0x0

    const/4 v4, 0x1

    invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 97
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 87
    return-void

    .line 96
    :catchall_0
    move-exception v1

    .line 97
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 96
    throw v1
.end method

.method public updateRemoteController(Landroid/media/session/ISessionController;)V
    .locals 5
    .param p1, "session"    # Landroid/media/session/ISessionController;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    const/4 v1, 0x0

    .line 105
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 107
    .local v0, "_data":Landroid/os/Parcel;
    :try_start_0
    const-string/jumbo v2, "android.media.IRemoteVolumeController"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 108
    if-eqz p1, :cond_0

    invoke-interface {p1}, Landroid/media/session/ISessionController;->asBinder()Landroid/os/IBinder;

    move-result-object v1

    :cond_0
    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    .line 109
    iget-object v1, p0, Landroid/media/IRemoteVolumeController$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v2, 0x2

    const/4 v3, 0x0

    const/4 v4, 0x1

    invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 112
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 103
    return-void

    .line 111
    :catchall_0
    move-exception v1

    .line 112
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 111
    throw v1
.end method

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: My Silicon Valley and Cloudkick experience
published: true
tags:
  - misc
---

## [{{page.title}}][1]

I have spent better part of this summer doing internship at [Y-Combinator][2] startup [Cloudkick][3].

Cloudkick main product is a cloud and dedicated server management and monitoring platform. They are also the innovators behind [libcloud][4] - a Python library for managing cloud server from different providers through a unified interface.

The technology itself behind Cloudkick is very diverse.

Better part of the backend code is written in Python using [Twisted][5] framework, but there is also C, C++, Java, Lua and in the future, when it gets more mature and stable I have a feeling that [NodeJS][6] will also play a big role in the Cloudkick infrastructure.

While staying there, I have worked on [multi factor authentication][7], better search powered by [Solr][8], Cloudkick agent plugins, [role based permissions framework][9], [Cast][10] (more about Cast in the future post) and more.

Better part of the time which I did not spend in the office I have spent with my roommate and other intern [Russell Haering][46] exploring San Francisco and doing pair programing up to 5:00 in the morning (yeah, Russell loves pair programming :P).

The whole experience with living in San Francisco, the place with all the [web 2.0 companies][11] (which I have to say, is totally different from [Maribor][12], the city where I come from) and working at startup with smart, fun and driven people like [Dan][13], [Paul][14], [Alex][15] and [others][16] was
great and lots of fun (and not to say I have also learned a lot).

Also, I got a chance to meet Eric Brewer (the author of the [CAP theorem][17]), [Ryan Dahl][18] (author of NodeJS), view a cluster of [~200 Mac Minis at Mozilla][19] and visit Facebook, Google and other SV companies (oh and did I mention that I lived ~5 minutes away from the [Mythbusters HQ][20]?).

As taxing and stressful as working at startup can sometimes be, it definitely is very rewarding - I have experienced it first hand not long after arriving to San Francisco when going to the SysAdmin Appreciation day party wearing a Cloudkick t-shirt.

Soon after I have arrived to the party, a person has seen my t-shirt, come to me and said that they use Cloudkick and they love it (there is hardly anything better then someone who is using something you have been part of saying that they love it).

Oh, and how does the saying go again, "pics or it didn't happen".

[![Golden Gate][22]][23] [![Mozilla HQ][24]][25] [![Team Cloudkick (minus Bjorn)][38]][39]
[![Nice view on the city from the Clarendon Heights near the Sutro Tower][28]][29] [![Stanford Campus][30]][31] [![Gold's Gym][32]][33]
[![Spam, and lots of it][34]][35] [!["Watering the Apple" by Russell Haering][36]][37] [![Cloudkick volunteer day at Muir Woods][26]][27]
[![Facebook lobby][40]][41] [![Google HQ][42]][43] [![Yelp's Doll][44]][45]

[1]: {{ page.url }}
[2]: http://ycombinator.com/
[3]: http://www.cloudkick.com
[4]: http://incubator.apache.org/libcloud/
[5]: http://twistedmatrix.com
[6]: http://nodejs.org/
[7]: https://www.cloudkick.com/blog/2010/jul/28/multi-factor-authentication-in-cloudkick/
[8]: http://lucene.apache.org/solr/
[9]: https://www.cloudkick.com/blog/2010/oct/27/user-roles-and-account-level-permissions/
[10]: http://github.com/cloudkick/cast
[11]: http://www.crunchbase.com/maps/city/San%2520Francisco/
[12]: http://en.wikipedia.org/wiki/Maribor
[13]: http://twitter.com/dispalt
[14]: http://twitter.com/pquerna
[15]: http://twitter.com/polvi
[16]: http://twitter.com/#!/list/KamiSLO/cloudkickers
[17]: http://www.julianbrowne.com/article/viewer/brewers-cap-theorem
[18]: http://github.com/ry
[19]: http://blog.mozilla.com/mrz/2008/06/12/i-want-to-rack-80-mac-minis/
[20]: http://maps.google.com/maps?f=q&source=s_q&hl=en&q=mythbusters+hq&sll=37.750358,-122.395592&sspn=0.242957,0.44632&ie=UTF8&rq=1&ev=zi&radius=14.65&split=1&filter=0&hq=mythbusters+hq&hnear=&ll=37.722664,-122.356796&spn=0.236259,0.44632&z=12&iwloc=A&layer=c&cbll=37.750371,-122.395312&panoid=yYkPjFdz4wOcVwum7y5q3w&cbp=12,257.21,,0,5.05
[21]: http://www.softqual.ucalgary.ca/images/projects/robocup_2010_class_diagram.jpg
[46]: http://twitter.com/#!/russell_h

[22]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-03_18-10-58_524_thumb.jpg
[23]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-03_18-10-58_524.jpg
[24]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck8_thumb.JPG
[25]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck8.JPG
[26]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/IMG_6665_thumb.JPG
[27]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/IMG_6665.JPG
[28]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-03_16-47-27_811_thumb.jpg
[29]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-03_16-47-27_811.jpg
[30]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-08-1716.40.57_thumb.jpg
[31]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-08-1716.40.57.jpg
[32]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-02_17-14-36_80_thumb.jpg
[33]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-02_17-14-36_80.jpg
[34]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-16_19-27-19_791_thumb.jpg
[35]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-07-16_19-27-19_791.jpg
[36]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/IMG_20100817_133705_large_thumb.jpg
[37]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/IMG_20100817_133705_large.jpg
[38]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck30_thumb.jpg
[39]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck30.jpg
[40]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck20_thumb.jpg
[41]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck20.jpg
[42]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck6_thumb.JPG
[43]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/ck6.JPG
[44]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-08-1710.36.08_thumb.jpg
[45]: /images/2010-11-01-my-silicon-valley-and-cloudkick-experience/2010-08-1710.36.08.jpg


text:
<?xml version="1.0" encoding="UTF-8"?>
<tei xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<teiHeader>
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>

						<affiliation>
							<orgName type="department">Institut für Chemie</orgName> der
							<orgName type="institution">Universität Hohenheim</orgName>,
							<address>
								<postCode>D-7000</postCode>
								<settlement>Stuttgart 70</settlement>,
								<country>Bundesrepublik Deutschland</country>
								<lb/>
							</address>
						</affiliation>
						<affiliation>
							<orgName type="department">FB 15, Botanik</orgName>,
							<orgName type="institution">Universität des Saarlandes</orgName>,
							<address>
								<postCode>D-6600</postCode>
								<settlement>Saarbrücken</settlement>,
								<country>Bundesrepublik Deutschland</country>
							</address>
						</affiliation>

						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</tei>


text:
package ca.quadrilateral.websocket.stats;

import org.apache.commons.lang3.builder.ToStringBuilder;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

@JsonAutoDetect(
        fieldVisibility=Visibility.ANY,
        getterVisibility=Visibility.NONE,
        isGetterVisibility=Visibility.NONE,
        setterVisibility=Visibility.NONE)
public class CpuStats {
    private final String cpuId;
    private final double userTime;
    private final double systemTime;
    private final double ioWaitTime;

    private CpuStats(
            final String cpuId,
            final double userTime,
            final double systemTime,
            final double ioWaitTime) {

        this.cpuId = cpuId;
        this.userTime = userTime;
        this.systemTime = systemTime;
        this.ioWaitTime = ioWaitTime;
    }

    public static CpuStats of(
            final String cpuId,
            final double userTime,
            final double systemTime,
            final double ioWaitTime) {

        return new CpuStats(cpuId, userTime, systemTime, ioWaitTime);
    }

    public String getCpuId() {
		return cpuId;
	}

	public double getUserTime() {
		return userTime;
	}

	public double getSystemTime() {
		return systemTime;
	}

	public double getIoWaitTime() {
		return ioWaitTime;
	}

	@Override
    public String toString() {
        return new ToStringBuilder(this)
            .append("CpuID", cpuId)
            .append("usr", userTime)
            .append("sys", systemTime)
            .append("ioWait", ioWaitTime)
            .toString();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig">

    <persistence-manager-factory name="transactions-optional">
        <property name="javax.jdo.PersistenceManagerFactoryClass"
                  value="org.datanucleus.store.appengine.jdo.DatastoreJDOPersistenceManagerFactory"/>
        <property name="javax.jdo.option.ConnectionURL" value="appengine"/>
        <property name="javax.jdo.option.NontransactionalRead" value="true"/>
        <property name="javax.jdo.option.NontransactionalWrite" value="true"/>
        <property name="javax.jdo.option.RetainValues" value="true"/>
        <property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
    </persistence-manager-factory>
</jdoconfig>


text:
package com.speedment.fika.lazy.specialized;

import static java.util.Objects.requireNonNull;
import java.util.function.Supplier;

/**
 * Generic lazy initialization class. The supplier must produce a non-null
 * value.
 *
 * This class is thread safe. The Supplier is guaranteed to be called exactly
 * one time following one or several calls to
 * {@link  #getOrCompute(java.util.function.Supplier) } by any number of
 * threads.
 *
 * @author Per Minborg
 */
public final class LazyFloat {

    private volatile Float value;

    private LazyFloat() {
    }

    public Float getOrCompute(Supplier<Float> supplier) {
        // With this local variable, we only need to do one volatile read
        final Float result = value;
        return result == null ? maybeCompute(supplier) : result;
    }

    private synchronized Float maybeCompute(Supplier<Float> supplier) {
        if (value == null) {
            value = requireNonNull(supplier.get());
        }
        return value;
    }

    public static LazyFloat create() {
        return new LazyFloat();
    }
}


text:
import React from 'react'
import { Provider } from 'react-redux'
import { mount } from 'enzyme'
import { act } from 'react-dom/test-utils'
import * as Formik from 'formik'
import { OutlineButton, SlotMap } from '@opentrons/components'
import {
  MAGNETIC_MODULE_TYPE,
  TEMPERATURE_MODULE_TYPE,
  MAGNETIC_MODULE_V2,
  TEMPERATURE_MODULE_V2,
} from '@opentrons/shared-data'
import {
  getMockDeckSetup,
  getMockMagneticModule,
  getMockTemperatureModule,
} from '../../../../../fixtures/state/deck'
import {
  actions as stepFormActions,
  selectors as stepFormSelectors,
} from '../../../../step-forms'
import {
  getLabwareOnSlot,
  getSlotsBlockedBySpanning,
  getSlotIsEmpty,
} from '../../../../step-forms/utils'
import * as moduleData from '../../../../modules/moduleData'
import { MODELS_FOR_MODULE_TYPE } from '../../../../constants'
import { selectors as featureSelectors } from '../../../../feature-flags'
import { getLabwareIsCompatible } from '../../../../utils/labwareModuleCompatibility'
import { isModuleWithCollisionIssue } from '../../../modules/utils'
import { PDAlert } from '../../../alerts/PDAlert'
import { EditModulesModal } from '..'
import { ModelDropdown } from '../ModelDropdown'
import { SlotDropdown } from '../SlotDropdown'
import { ConnectedSlotMap } from '../ConnectedSlotMap'

jest.mock('../../../../utils/labwareModuleCompatibility')
jest.mock('../../../../feature-flags')
jest.mock('../../../../step-forms/selectors')
jest.mock('../../../modules/utils')
jest.mock('../../../../step-forms/utils')
jest.mock('../form-state')

const MODEL_FIELD = 'selectedModel'
const SLOT_FIELD = 'selectedSlot'

const getInitialDeckSetupMock: JestMockFn<any, any> =
  stepFormSelectors.getInitialDeckSetup

const getLabwareIsCompatibleMock: JestMockFn<any, any> = getLabwareIsCompatible

const getDisableModuleRestrictionsMock: JestMockFn<any, any> =
  featureSelectors.getDisableModuleRestrictions

const isModuleWithCollisionIssueMock: JestMockFn<
  any,
  any
> = isModuleWithCollisionIssue

const getSlotsBlockedBySpanningMock: JestMockFn<
  any,
  any
> = getSlotsBlockedBySpanning

const getSlotIsEmptyMock: JestMockFn<any, any> = getSlotIsEmpty

const getLabwareOnSlotMock: JestMockFn<any, any> = getLabwareOnSlot

describe('Edit Modules Modal', () => {
  let mockStore
  let props
  beforeEach(() => {
    getInitialDeckSetupMock.mockReturnValue(getMockDeckSetup())
    getSlotsBlockedBySpanningMock.mockReturnValue([])
    getLabwareOnSlotMock.mockReturnValue({})
    props = {
      moduleOnDeck: null,
      moduleType: MAGNETIC_MODULE_TYPE,
      onCloseClick: jest.fn(),
      editModuleModel: jest.fn(),
      editModuleSlot: jest.fn(),
      displayModuleWarning: jest.fn(),
    }
    mockStore = {
      dispatch: jest.fn(),
      subscribe: jest.fn(),
      getState: () => ({}),
    }
  })

  afterEach(() => {
    jest.clearAllMocks()
  })
  const render = props =>
    mount(
      <Provider store={mockStore}>
        <EditModulesModal {...props} />
      </Provider>
    )

  describe('PD alert', () => {
    beforeEach(() => {
      getDisableModuleRestrictionsMock.mockReturnValue(false)
    })
    afterEach(() => {
      jest.clearAllMocks()
    })
    it('does NOT render when labware is compatible', () => {
      getLabwareIsCompatibleMock.mockReturnValue(true)
      const wrapper = render(props)
      expect(wrapper.find(PDAlert)).toHaveLength(0)
    })

    it('renders when labware is incompatible', () => {
      getLabwareIsCompatibleMock.mockReturnValue(false)
      const wrapper = render(props)
      expect(wrapper.find(PDAlert)).toHaveLength(1)
    })
  })

  describe('Slot Dropdown', () => {
    it('should pass the correct options and field name', () => {
      const mockSlots = [{ value: 'mockSlots', name: 'mockSlots' }]
      jest
        .spyOn(moduleData, 'getAllModuleSlotsByType')
        .mockImplementation(() => mockSlots)

      const wrapper = render(props)
      expect(wrapper.find(SlotDropdown).prop('options')).toBe(mockSlots)
      expect(wrapper.find(SlotDropdown).prop('fieldName')).toBe(SLOT_FIELD)
    })
    it('should be enabled when there is no collision issue', () => {
      props.moduleOnDeck = getMockMagneticModule()
      isModuleWithCollisionIssueMock.mockReturnValueOnce(false)
      const wrapper = render(props)
      expect(wrapper.find(SlotDropdown).prop('disabled')).toBe(false)
    })

    it('should be disabled when there is no collision issue', () => {
      isModuleWithCollisionIssueMock.mockReturnValue(true)
      const wrapper = render(props)
      expect(wrapper.find(SlotDropdown).prop('disabled')).toBe(true)
    })

    it('should error when labware is incompatible', () => {
      getLabwareIsCompatibleMock.mockReturnValue(false)
      const wrapper = render(props)
      expect(
        wrapper
          .find(SlotDropdown)
          .childAt(0)
          .prop('error')
      ).toMatch('labware incompatible')
    })

    it('should error when slot is empty but blocked', () => {
      getSlotIsEmptyMock.mockReturnValueOnce(true)
      getSlotsBlockedBySpanningMock.mockReturnValue(['1']) // 1 is default slot
      const wrapper = render(props)
      expect(
        wrapper
          .find(SlotDropdown)
          .childAt(0)
          .prop('error')
      ).toMatch('labware incompatible')
    })
    it('should NOT error when labware is compatible', () => {
      getLabwareIsCompatibleMock.mockReturnValue(true)
      const wrapper = render(props)
      expect(
        wrapper
          .find(SlotDropdown)
          .childAt(0)
          .prop('error')
      ).toBeFalsy()
    })
  })

  describe('Model Dropdown', () => {
    it('should pass the correct props for magnetic module', () => {
      props.moduleType = MAGNETIC_MODULE_TYPE
      const wrapper = render(props)
      const expectedProps = {
        fieldName: MODEL_FIELD,
        options: MODELS_FOR_MODULE_TYPE[MAGNETIC_MODULE_TYPE],
        tabIndex: 0,
      }
      expect(wrapper.find(ModelDropdown).props()).toEqual(expectedProps)
    })
    it('should pass the correct props for temperature module', () => {
      props.moduleType = TEMPERATURE_MODULE_TYPE
      const wrapper = render(props)
      const expectedProps = {
        fieldName: MODEL_FIELD,
        options: MODELS_FOR_MODULE_TYPE[TEMPERATURE_MODULE_TYPE],
        tabIndex: 0,
      }
      expect(wrapper.find(ModelDropdown).props()).toEqual(expectedProps)
    })
  })

  describe('Connected Slot Map', () => {
    it('should pass the selected slot field name', () => {
      const wrapper = render(props)
      expect(wrapper.find(ConnectedSlotMap).prop('fieldName')).toBe(
        'selectedSlot'
      )
    })
    it('should pass an error if the labware is not compatible', () => {
      getLabwareIsCompatibleMock.mockReturnValue(false)
      const wrapper = render(props)
      expect(wrapper.find(SlotMap).prop('isError')).toBeTruthy()
    })
    it('should NOT pass an error if the labware is compatible', () => {
      getLabwareIsCompatibleMock.mockReturnValue(true)
      const wrapper = render(props)
      expect(wrapper.find(SlotMap).prop('isError')).toBeFalsy()
    })
  })

  describe('Cancel Button', () => {
    it('calls onCloseClick when pressed', () => {
      const wrapper = render(props)
      wrapper
        .find(OutlineButton)
        .at(0)
        .prop('onClick')()
      expect(props.onCloseClick).toHaveBeenCalled()
    })
  })
  describe('Form Submission', () => {
    it('sets module change warning info when model has changed and is magnetic module', () => {
      props.moduleOnDeck = getMockMagneticModule()
      const wrapper = render(props)
      const formik = wrapper.find(Formik.Formik)
      const mockValues = {
        selectedSlot: '1',
        selectedModel: MAGNETIC_MODULE_V2,
      }
      act(() => {
        formik.invoke('onSubmit')(mockValues)
      })
      expect(props.displayModuleWarning).toHaveBeenCalledWith({
        model: mockValues.selectedModel,
        slot: mockValues.selectedSlot,
      })
    })

    it('edits the model and slot if module is not magnetic module', () => {
      props.moduleOnDeck = getMockTemperatureModule()
      const wrapper = render(props)
      const formik = wrapper.find(Formik.Formik)
      const mockValues = {
        selectedSlot: '1',
        selectedModel: TEMPERATURE_MODULE_V2,
      }
      act(() => {
        formik.invoke('onSubmit')(mockValues)
      })
      expect(props.editModuleModel).toHaveBeenCalledWith(TEMPERATURE_MODULE_V2)
      expect(props.editModuleSlot).toHaveBeenCalledWith('1')
    })

    it('creates a new module if no module is registered', () => {
      props.moduleOnDeck = null
      const wrapper = render(props)
      const formik = wrapper.find(Formik.Formik)
      const mockValues = {
        selectedSlot: '1',
        selectedModel: MAGNETIC_MODULE_V2,
      }
      act(() => {
        formik.invoke('onSubmit')(mockValues)
      })

      const params = {
        slot: '1',
        type: MAGNETIC_MODULE_TYPE,
        model: MAGNETIC_MODULE_V2,
      }

      const createModuleAction = stepFormActions.createModule(params)

      const expected = {
        ...createModuleAction,
        payload: {
          ...createModuleAction.payload,
          id: expect.stringContaining(MAGNETIC_MODULE_TYPE), // need to do this because exact id is created on the fly
        },
      }

      expect(mockStore.dispatch).toHaveBeenCalledWith(expected)
    })
  })
})


text:
package java.io;

import avian.Utf8;

public class InputStreamReader extends Reader {
  private static final int MultibytePadding = 4;

  private final InputStream in;

  public InputStreamReader(InputStream in) {
    this.in = in;
  }

  public InputStreamReader(InputStream in, String encoding)
    throws UnsupportedEncodingException
  {
    this(in);

    if (! encoding.equals("UTF-8")) {
      throw new UnsupportedEncodingException(encoding);
    }
  }

  public int read(char[] b, int offset, int length) throws IOException {
    if (length == 0) {
      return 0;
    }

    byte[] buffer = new byte[length + MultibytePadding];
    int bufferLength = length;
    int bufferOffset = 0;
    while (true) {
      int c = in.read(buffer, bufferOffset, bufferLength);

      if (c <= 0) {
        if (bufferOffset > 0) {
          // if we've reached the end of the stream while trying to
          // read a multibyte character, we still need to return any
          // competely-decoded characters, plus \ufffd to indicate an
          // unknown character
          c = 1;
          while (bufferOffset > 0) {
            char[] buffer16 = Utf8.decode16(buffer, 0, bufferOffset);

            if (buffer16 != null) {
              System.arraycopy(buffer16, 0, b, offset, buffer16.length);

              c = buffer16.length + 1;
              break;
            } else {
              -- bufferOffset;
            }
          }

          b[offset + c - 1] = '\ufffd';
        }

        return c;
      }

      bufferOffset += c;

      char[] buffer16 = Utf8.decode16(buffer, 0, bufferOffset);

      if (buffer16 != null) {
        bufferOffset = 0;

        System.arraycopy(buffer16, 0, b, offset, buffer16.length);

        return buffer16.length;
      } else {
        // the buffer ended in an incomplete multibyte character, so
        // we try to read a another byte at a time until it's complete
        bufferLength = 1;
      }
    }
  }

  public void close() throws IOException {
    in.close();
  }
}


text:
@implementation OpenCVTestViewController
@synthesize imageView;

- (void)dealloc {
	AudioServicesDisposeSystemSoundID(alertSoundID);
	[imageView dealloc];
	[super dealloc];
}

#pragma mark -
#pragma mark OpenCV Support Methods

// NOTE you SHOULD cvReleaseImage() for the return value when end of the code.
- (IplImage *)CreateIplImageFromUIImage:(UIImage *)image {
	CGImageRef imageRef = image.CGImage;

	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	IplImage *iplimage = cvCreateImage(cvSize(image.size.width, image.size.height), IPL_DEPTH_8U, 4);
	CGContextRef contextRef = CGBitmapContextCreate(iplimage->imageData, iplimage->width, iplimage->height,
													iplimage->depth, iplimage->widthStep,
													colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault);
	CGContextDrawImage(contextRef, CGRectMake(0, 0, image.size.width, image.size.height), imageRef);
	CGContextRelease(contextRef);
	CGColorSpaceRelease(colorSpace);

	IplImage *ret = cvCreateImage(cvGetSize(iplimage), IPL_DEPTH_8U, 3);
	cvCvtColor(iplimage, ret, CV_RGBA2BGR);
	cvReleaseImage(&iplimage);

	return ret;
}

// NOTE You should convert color mode as RGB before passing to this function
- (UIImage *)UIImageFromIplImage:(IplImage *)image {
	NSLog(@"IplImage (%d, %d) %d bits by %d channels, %d bytes/row %s", image->width, image->height, image->depth, image->nChannels, image->widthStep, image->channelSeq);

	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	NSData *data = [NSData dataWithBytes:image->imageData length:image->imageSize];
	CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
	CGImageRef imageRef = CGImageCreate(image->width, image->height,
										image->depth, image->depth * image->nChannels, image->widthStep,
										colorSpace, kCGImageAlphaNone|kCGBitmapByteOrderDefault,
										provider, NULL, false, kCGRenderingIntentDefault);
	UIImage *ret = [UIImage imageWithCGImage:imageRef];
	CGImageRelease(imageRef);
	CGDataProviderRelease(provider);
	CGColorSpaceRelease(colorSpace);
	return ret;
}

#pragma mark -
#pragma mark Utilities for intarnal use

- (void)showProgressIndicator:(NSString *)text {
	//[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	self.view.userInteractionEnabled = FALSE;
	if(!progressHUD) {
		CGFloat w = 160.0f, h = 120.0f;
		progressHUD = [[UIProgressHUD alloc] initWithFrame:CGRectMake((self.view.frame.size.width-w)/2, (self.view.frame.size.height-h)/2, w, h)];
		[progressHUD setText:text];
		[progressHUD showInView:self.view];
	}
}

- (void)hideProgressIndicator {
	//[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	self.view.userInteractionEnabled = TRUE;
	if(progressHUD) {
		[progressHUD hide];
		[progressHUD release];
		progressHUD = nil;

		AudioServicesPlaySystemSound(alertSoundID);
	}
}

- (void)opencvEdgeDetect {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	if(imageView.image) {
		cvSetErrMode(CV_ErrModeParent);

		// Create grayscale IplImage from UIImage
		IplImage *img_color = [self CreateIplImageFromUIImage:imageView.image];
		IplImage *img = cvCreateImage(cvGetSize(img_color), IPL_DEPTH_8U, 1);
		cvCvtColor(img_color, img, CV_BGR2GRAY);
		cvReleaseImage(&img_color);

		// Detect edge
		IplImage *img2 = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
		cvCanny(img, img2, 64, 128, 3);
		cvReleaseImage(&img);

		// Convert black and whilte to 24bit image then convert to UIImage to show
		IplImage *image = cvCreateImage(cvGetSize(img2), IPL_DEPTH_8U, 3);
		for(int y=0; y<img2->height; y++) {
			for(int x=0; x<img2->width; x++) {
				char *p = image->imageData + y * image->widthStep + x * 3;
				*p = *(p+1) = *(p+2) = img2->imageData[y * img2->widthStep + x];
			}
		}
		cvReleaseImage(&img2);
		imageView.image = [self UIImageFromIplImage:image];
		cvReleaseImage(&image);

		[self hideProgressIndicator];
	}

	[pool release];
}

- (void) opencvFaceDetect:(UIImage *)overlayImage  {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

	if(imageView.image) {
		cvSetErrMode(CV_ErrModeParent);

		IplImage *image = [self CreateIplImageFromUIImage:imageView.image];

		// Scaling down
		IplImage *small_image = cvCreateImage(cvSize(image->width/2,image->height/2), IPL_DEPTH_8U, 3);
		cvPyrDown(image, small_image, CV_GAUSSIAN_5x5);
		int scale = 2;

		// Load XML
		NSString *path = [[NSBundle mainBundle] pathForResource:@"haarcascade_frontalface_default" ofType:@"xml"];
		CvHaarClassifierCascade* cascade = (CvHaarClassifierCascade*)cvLoad([path cStringUsingEncoding:NSASCIIStringEncoding], NULL, NULL, NULL);
		CvMemStorage* storage = cvCreateMemStorage(0);

		// Detect faces and draw rectangle on them
		CvSeq* faces = cvHaarDetectObjects(small_image, cascade, storage, 1.2f, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(0,0), cvSize(20, 20));
		cvReleaseImage(&small_image);

		// Create canvas to show the results
		CGImageRef imageRef = imageView.image.CGImage;
		CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
		CGContextRef contextRef = CGBitmapContextCreate(NULL, imageView.image.size.width, imageView.image.size.height,
														8, imageView.image.size.width * 4,
														colorSpace, kCGImageAlphaPremultipliedLast|kCGBitmapByteOrderDefault);
		CGContextDrawImage(contextRef, CGRectMake(0, 0, imageView.image.size.width, imageView.image.size.height), imageRef);

		CGContextSetLineWidth(contextRef, 4);
		CGContextSetRGBStrokeColor(contextRef, 0.0, 0.0, 1.0, 0.5);

		// Draw results on the iamge
		for(int i = 0; i < faces->total; i++) {
			NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

			// Calc the rect of faces
			CvRect cvrect = *(CvRect*)cvGetSeqElem(faces, i);
			CGRect face_rect = CGContextConvertRectToDeviceSpace(contextRef, CGRectMake(cvrect.x * scale, cvrect.y * scale, cvrect.width * scale, cvrect.height * scale));

			if(overlayImage) {
				CGContextDrawImage(contextRef, face_rect, overlayImage.CGImage);
			} else {
				CGContextStrokeRect(contextRef, face_rect);
			}

			[pool release];
		}

		imageView.image = [UIImage imageWithCGImage:CGBitmapContextCreateImage(contextRef)];
		CGContextRelease(contextRef);
		CGColorSpaceRelease(colorSpace);

		cvReleaseMemStorage(&storage);
		cvReleaseHaarClassifierCascade(&cascade);

		[self hideProgressIndicator];
	}

	[pool release];
}

#pragma mark -
#pragma mark IBAction

- (IBAction)loadImage:(id)sender {
	if(!actionSheetAction) {
		UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
																 delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
														otherButtonTitles:@"Use Photo from Library", @"Take Photo with Camera", @"Use Default Lena", nil];
		actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
		actionSheetAction = ActionSheetToSelectTypeOfSource;
		[actionSheet showInView:self.view];
		[actionSheet release];
	}
}

- (IBAction)saveImage:(id)sender {
	if(imageView.image) {
		[self showProgressIndicator:@"Saving"];
		UIImageWriteToSavedPhotosAlbum(imageView.image, self, @selector(finishUIImageWriteToSavedPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
	}
}

- (void)finishUIImageWriteToSavedPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
	[self hideProgressIndicator];
}

- (IBAction)edgeDetect:(id)sender {
	[self showProgressIndicator:@"Detecting"];
	[self performSelectorInBackground:@selector(opencvEdgeDetect) withObject:nil];
}

- (IBAction)faceDetect:(id)sender {
	cvSetErrMode(CV_ErrModeParent);
	if(imageView.image && !actionSheetAction) {
		UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@""
																 delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
														otherButtonTitles:@"Bounding Box", @"Laughing Man", nil];
		actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
		actionSheetAction = ActionSheetToSelectTypeOfMarks;
		[actionSheet showInView:self.view];
		[actionSheet release];
	}
}

#pragma mark -
#pragma mark UIViewControllerDelegate

- (void)viewDidLoad {
	[super viewDidLoad];
	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];
	[self loadImage:nil];

	NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Tink" ofType:@"aiff"] isDirectory:NO];
	AudioServicesCreateSystemSoundID((CFURLRef)url, &alertSoundID);
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return NO;
}

#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	switch(actionSheetAction) {
		case ActionSheetToSelectTypeOfSource: {
			UIImagePickerControllerSourceType sourceType;
			if (buttonIndex == 0) {
				sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
			} else if(buttonIndex == 1) {
				sourceType = UIImagePickerControllerSourceTypeCamera;
			} else if(buttonIndex == 2) {
				NSString *path = [[NSBundle mainBundle] pathForResource:@"lena" ofType:@"jpg"];
				imageView.image = [UIImage imageWithContentsOfFile:path];
				break;
			} else {
				// Cancel
				break;
			}
			if([UIImagePickerController isSourceTypeAvailable:sourceType]) {
				UIImagePickerController *picker = [[UIImagePickerController alloc] init];
				picker.sourceType = sourceType;
				picker.delegate = self;
				picker.allowsImageEditing = NO;
				[self presentModalViewController:picker animated:YES];
				[picker release];
			}
			break;
		}
		case ActionSheetToSelectTypeOfMarks: {
			if(buttonIndex != 0 && buttonIndex != 1) {
				break;
			}

			UIImage *image = nil;
			if(buttonIndex == 1) {
				NSString *path = [[NSBundle mainBundle] pathForResource:@"laughing_man" ofType:@"png"];
				image = [UIImage imageWithContentsOfFile:path];
			}

			[self showProgressIndicator:@"Detecting"];
			[self performSelectorInBackground:@selector(opencvFaceDetect:) withObject:image];
			break;
		}
	}
	actionSheetAction = 0;
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (UIImage *)scaleAndRotateImage:(UIImage *)image {
	static int kMaxResolution = 640;

	CGImageRef imgRef = image.CGImage;
	CGFloat width = CGImageGetWidth(imgRef);
	CGFloat height = CGImageGetHeight(imgRef);

	CGAffineTransform transform = CGAffineTransformIdentity;
	CGRect bounds = CGRectMake(0, 0, width, height);
	if (width > kMaxResolution || height > kMaxResolution) {
		CGFloat ratio = width/height;
		if (ratio > 1) {
			bounds.size.width = kMaxResolution;
			bounds.size.height = bounds.size.width / ratio;
		} else {
			bounds.size.height = kMaxResolution;
			bounds.size.width = bounds.size.height * ratio;
		}
	}

	CGFloat scaleRatio = bounds.size.width / width;
	CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
	CGFloat boundHeight;

	UIImageOrientation orient = image.imageOrientation;
	switch(orient) {
		case UIImageOrientationUp:
			transform = CGAffineTransformIdentity;
			break;
		case UIImageOrientationUpMirrored:
			transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			break;
		case UIImageOrientationDown:
			transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
			transform = CGAffineTransformRotate(transform, M_PI);
			break;
		case UIImageOrientationDownMirrored:
			transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
			transform = CGAffineTransformScale(transform, 1.0, -1.0);
			break;
		case UIImageOrientationLeftMirrored:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
			transform = CGAffineTransformScale(transform, -1.0, 1.0);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
			break;
		case UIImageOrientationLeft:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
			transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
			break;
		case UIImageOrientationRightMirrored:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeScale(-1.0, 1.0);
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);
			break;
		case UIImageOrientationRight:
			boundHeight = bounds.size.height;
			bounds.size.height = bounds.size.width;
			bounds.size.width = boundHeight;
			transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
			transform = CGAffineTransformRotate(transform, M_PI / 2.0);
			break;
		default:
			[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
	}

	UIGraphicsBeginImageContext(bounds.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
	if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
		CGContextScaleCTM(context, -scaleRatio, scaleRatio);
		CGContextTranslateCTM(context, -height, 0);
	} else {
		CGContextScaleCTM(context, scaleRatio, -scaleRatio);
		CGContextTranslateCTM(context, 0, -height);
	}
	CGContextConcatCTM(context, transform);
	CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
	UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();

	return imageCopy;
}

- (void)imagePickerController:(UIImagePickerController *)picker
		didFinishPickingImage:(UIImage *)image
				  editingInfo:(NSDictionary *)editingInfo
{
	imageView.image = [self scaleAndRotateImage:image];
	[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}
@end


text:
from __future__ import unicode_literals
from .models import ecr_backends
from ..core.models import base_decorator, deprecated_base_decorator

ecr_backend = ecr_backends["us-east-1"]
mock_ecr = base_decorator(ecr_backends)
mock_ecr_deprecated = deprecated_base_decorator(ecr_backends)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface org.apache.cassandra.db.rows.Row (apache-cassandra API)</title>
<meta name="date" content="2016-04-09">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.apache.cassandra.db.rows.Row

Packages that use Row

Package
Description

org.apache.cassandra.cql3

org.apache.cassandra.db

org.apache.cassandra.db.filter

org.apache.cassandra.db.partitions

org.apache.cassandra.db.rows

org.apache.cassandra.db.transform

org.apache.cassandra.index

org.apache.cassandra.index.internal

org.apache.cassandra.index.internal.composites

org.apache.cassandra.index.internal.keys

org.apache.cassandra.index.sasi.conf

org.apache.cassandra.index.transactions

org.apache.cassandra.io.sstable

org.apache.cassandra.service.pager

org.apache.cassandra.streaming

org.apache.cassandra.utils.memory

Uses of Row in org.apache.cassandra.cql3

Methods in org.apache.cassandra.cql3 that return Row

Modifier and Type
Method and Description

Row
UpdateParameters.buildRow()

Row
UpdateParameters.getPrefetchedRow(DecoratedKey key,
                Clustering clustering)

Methods in org.apache.cassandra.cql3 with parameters of type Row

Modifier and Type
Method and Description

abstract boolean
ColumnCondition.Bound.appliesTo(Row row)

Validates whether this condition applies to current.

boolean
ColumnCondition.CollectionInBound.appliesTo(Row row)

static UntypedResultSet.Row
UntypedResultSet.Row.fromInternalRow(CFMetaData metadata,
               DecoratedKey key,
               Row row)

Uses of Row in org.apache.cassandra.db

Methods in org.apache.cassandra.db that return Row

Modifier and Type
Method and Description

protected Row
ReadCommand.CheckForAbort.applyToRow(Row row)

static Row
LegacyLayout.extractStaticColumns(CFMetaData metadata,
                    DataInputPlus in,
                    Columns statics)

Row
LegacyLayout.CellGrouper.getRow()

Methods in org.apache.cassandra.db that return types with arguments of type Row

Modifier and Type
Method and Description

java.util.Comparator<Row>
ClusteringComparator.rowComparator()

A comparator for rows.

Methods in org.apache.cassandra.db with parameters of type Row

Modifier and Type
Method and Description

protected Row
ReadCommand.CheckForAbort.applyToRow(Row row)

static UnfilteredRowIterator
EmptyIterators.unfilteredRow(CFMetaData metadata,
             DecoratedKey partitionKey,
             boolean isReverseOrder,
             Row staticRow,
             DeletionTime partitionDeletion)

Uses of Row in org.apache.cassandra.db.filter

Methods in org.apache.cassandra.db.filter with parameters of type Row

Modifier and Type
Method and Description

protected abstract void
DataLimits.Counter.applyToPartition(DecoratedKey partitionKey,
                Row staticRow)

protected java.nio.ByteBuffer
RowFilter.Expression.getValue(CFMetaData metadata,
        DecoratedKey partitionKey,
        Row row)

abstract boolean
RowFilter.Expression.isSatisfiedBy(CFMetaData metadata,
             DecoratedKey partitionKey,
             Row row)

Returns whether the provided row satisfied this expression or not.

boolean
RowFilter.CustomExpression.isSatisfiedBy(CFMetaData metadata,
             DecoratedKey partitionKey,
             Row row)

Uses of Row in org.apache.cassandra.db.partitions

Methods in org.apache.cassandra.db.partitions that return Row

Modifier and Type
Method and Description

Row
PurgeFunction.applyToRow(Row row)

Row
PurgeFunction.applyToStatic(Row row)

Row
AbstractBTreePartition.getRow(Clustering clustering)

Row
AtomicBTreePartition.getRow(Clustering clustering)

Row
Partition.getRow(Clustering clustering)

Returns the row corresponding to the provided clustering, or null if there is not such row.

Row
AbstractBTreePartition.lastRow()

Row
AtomicBTreePartition.lastRow()

Row
CachedPartition.lastRow()

The last row in this cached partition (in order words, the row with the
 biggest clustering that the partition contains).

Row
AbstractBTreePartition.staticRow()

Row
AtomicBTreePartition.staticRow()

Methods in org.apache.cassandra.db.partitions that return types with arguments of type Row

Modifier and Type
Method and Description

java.util.Iterator<Row>
AbstractBTreePartition.iterator()

java.util.Iterator<Row>
AtomicBTreePartition.iterator()

java.util.Iterator<Row>
PartitionUpdate.iterator()

Returns an iterator that iterates over the rows of this update in clustering order.

SearchIterator<Clustering,Row>
AbstractBTreePartition.searchIterator(ColumnFilter columns,
              boolean reversed)

SearchIterator<Clustering,Row>
AtomicBTreePartition.searchIterator(ColumnFilter columns,
              boolean reversed)

SearchIterator<Clustering,Row>
Partition.searchIterator(ColumnFilter columns,
              boolean reversed)

Returns an iterator that allows to search specific rows efficiently.

Methods in org.apache.cassandra.db.partitions with parameters of type Row

Modifier and Type
Method and Description

void
PartitionUpdate.add(Row row)

Adds a row to this update.

Row
PurgeFunction.applyToRow(Row row)

Row
PurgeFunction.applyToStatic(Row row)

static PartitionUpdate
PartitionUpdate.singleRowUpdate(CFMetaData metadata,
               java.nio.ByteBuffer key,
               Row row)

Creates an immutable partition update that contains a single row update.

static PartitionUpdate
PartitionUpdate.singleRowUpdate(CFMetaData metadata,
               DecoratedKey key,
               Row row)

Creates an immutable partition update that contains a single row update.

Constructors in org.apache.cassandra.db.partitions with parameters of type Row

Constructor and Description

ImmutableBTreePartition(CFMetaData metadata,
                       DecoratedKey partitionKey,
                       PartitionColumns columns,
                       Row staticRow,
                       java.lang.Object[] tree,
                       DeletionInfo deletionInfo,
                       EncodingStats stats)

Uses of Row in org.apache.cassandra.db.rows

Classes in org.apache.cassandra.db.rows that implement Row

Modifier and Type
Class and Description

class
AbstractRow

Base abstract class for Row implementations.

class
BTreeRow

Immutable implementation of a Row object.

Fields in org.apache.cassandra.db.rows declared as Row

Modifier and Type
Field and Description

static Row
Rows.EMPTY_STATIC_ROW

protected Row
AbstractUnfilteredRowIterator.staticRow

Row
UnfilteredRowIteratorSerializer.Header.staticRow

Methods in org.apache.cassandra.db.rows that return Row

Modifier and Type
Method and Description

protected Row
WithOnlyQueriedData.applyToRow(Row row)

protected Row
WithOnlyQueriedData.applyToStatic(Row row)

Row
BTreeRow.Builder.build()

Row
Row.Builder.build()

Builds and return built row.

Row
UnfilteredSerializer.deserializeRowBody(DataInputPlus in,
                  SerializationHeader header,
                  SerializationHelper helper,
                  int flags,
                  int extendedFlags,
                  Row.Builder builder)

Row
UnfilteredSerializer.deserializeStaticRow(DataInputPlus in,
                    SerializationHeader header,
                    SerializationHelper helper)

Row
BTreeRow.filter(ColumnFilter filter,
      CFMetaData metadata)

Row
Row.filter(ColumnFilter filter,
      CFMetaData metadata)

Returns a copy of this row that:
   1) only includes the data for the column included by filter.

Row
BTreeRow.filter(ColumnFilter filter,
      DeletionTime activeDeletion,
      boolean setActiveDeletionToRow,
      CFMetaData metadata)

Row
Row.filter(ColumnFilter filter,
      DeletionTime activeDeletion,
      boolean setActiveDeletionToRow,
      CFMetaData metadata)

Returns a copy of this row that:
   1) only includes the data for the column included by filter.

Row
BTreeRow.markCounterLocalToBeCleared()

Row
Row.markCounterLocalToBeCleared()

Returns a copy of this row where all counter cells have they "local" shard marked for clearing.

Row
Row.Merger.merge(DeletionTime activeDeletion)

static Row
Rows.merge(Row row1,
     Row row2,
     int nowInSec)

Row[]
Row.Merger.mergedRows()

Row
BTreeRow.purge(DeletionPurger purger,
     int nowInSec)

Row
Row.purge(DeletionPurger purger,
     int nowInSec)

Returns a copy of this row without any deletion info that should be purged according to purger.

Row
AbstractUnfilteredRowIterator.staticRow()

Row
BaseRowIterator.staticRow()

The static part corresponding to this partition (this can be an empty
 row).

Row
LazilyInitializedUnfilteredRowIterator.staticRow()

Row
UnfilteredRowIteratorWithLowerBound.staticRow()

Row
WrappingUnfilteredRowIterator.staticRow()

Row
BTreeRow.updateAllTimestamp(long newTimestamp)

Returns a copy of the row where all timestamps for live data have replaced by newTimestamp and
 all deletion timestamp by newTimestamp - 1.

Row
Row.updateAllTimestamp(long newTimestamp)

returns a copy of this row where all live timestamp have been replaced by newTimestamp and every deletion timestamp
 by newTimestamp - 1.

Row
BTreeRow.withOnlyQueriedData(ColumnFilter filter)

Row
Row.withOnlyQueriedData(ColumnFilter filter)

Returns a copy of this row which only include the data queried by filter, excluding anything _fetched_ for
 internal reasons but not queried by the user (see ColumnFilter for details).

Methods in org.apache.cassandra.db.rows with parameters of type Row

Modifier and Type
Method and Description

void
Row.Merger.add(int i,
   Row row)

protected Row
WithOnlyQueriedData.applyToRow(Row row)

protected Row
WithOnlyQueriedData.applyToStatic(Row row)

static EncodingStats
EncodingStats.Collector.collect(Row staticRow,
       java.util.Iterator<Row> rows,
       DeletionInfo deletionInfo)

static int
Rows.collectStats(Row row,
            PartitionStatisticsCollector collector)

Collect statistics ont a given row.

static Row.Builder
Rows.copy(Row row,
    Row.Builder builder)

static void
Rows.diff(RowDiffListener diffListener,
    Row merged,
    Row... inputs)

Given the result (merged) of merging multiple inputs, signals the difference between
 each input and merged to diffListener.

static void
Rows.diff(RowDiffListener diffListener,
    Row merged,
    Row... inputs)

Given the result (merged) of merging multiple inputs, signals the difference between
 each input and merged to diffListener.

static boolean
UnfilteredSerializer.hasExtendedFlags(Row row)

static Row
Rows.merge(Row row1,
     Row row2,
     int nowInSec)

static long
Rows.merge(Row existing,
     Row update,
     Row.Builder builder,
     int nowInSec)

Merges two rows into the given builder, mainly for merging memtable rows.

static UnfilteredRowIterator
UnfilteredRowIterators.noRowsIterator(CFMetaData cfm,
              DecoratedKey partitionKey,
              Row staticRow,
              DeletionTime partitionDeletion,
              boolean isReverseOrder)

Returns an empty atom iterator for a given partition.

void
UnfilteredRowIterators.MergeListener.onMergedRows(Row merged,
            Row[] versions)

void
UnfilteredRowIterators.MergeListener.onMergedRows(Row merged,
            Row[] versions)

void
UnfilteredSerializer.serializeStaticRow(Row row,
                  SerializationHeader header,
                  DataOutputPlus out,
                  int version)

Method parameters in org.apache.cassandra.db.rows with type arguments of type Row

Modifier and Type
Method and Description

static EncodingStats
EncodingStats.Collector.collect(Row staticRow,
       java.util.Iterator<Row> rows,
       DeletionInfo deletionInfo)

Constructors in org.apache.cassandra.db.rows with parameters of type Row

Constructor and Description

AbstractUnfilteredRowIterator(CFMetaData metadata,
                             DecoratedKey partitionKey,
                             DeletionTime partitionLevelDeletion,
                             PartitionColumns columns,
                             Row staticRow,
                             boolean isReverseOrder,
                             EncodingStats stats)

RowAndDeletionMergeIterator(CFMetaData metadata,
                           DecoratedKey partitionKey,
                           DeletionTime partitionLevelDeletion,
                           ColumnFilter selection,
                           Row staticRow,
                           boolean isReversed,
                           EncodingStats stats,
                           java.util.Iterator<Row> rows,
                           java.util.Iterator<RangeTombstone> ranges,
                           boolean removeShadowedData)

Constructor parameters in org.apache.cassandra.db.rows with type arguments of type Row

Constructor and Description

RowAndDeletionMergeIterator(CFMetaData metadata,
                           DecoratedKey partitionKey,
                           DeletionTime partitionLevelDeletion,
                           ColumnFilter selection,
                           Row staticRow,
                           boolean isReversed,
                           EncodingStats stats,
                           java.util.Iterator<Row> rows,
                           java.util.Iterator<RangeTombstone> ranges,
                           boolean removeShadowedData)

Uses of Row in org.apache.cassandra.db.transform

Methods in org.apache.cassandra.db.transform that return Row

Modifier and Type
Method and Description

protected Row
Transformation.applyToRow(Row row)

Applied to any row we encounter in a rows iterator

protected Row
Transformation.applyToStatic(Row row)

Applied to the static row of any rows iterator.

Row
BaseRows.staticRow()

Methods in org.apache.cassandra.db.transform with parameters of type Row

Modifier and Type
Method and Description

protected Row
Transformation.applyToRow(Row row)

Applied to any row we encounter in a rows iterator

protected Row
Transformation.applyToStatic(Row row)

Applied to the static row of any rows iterator.

Uses of Row in org.apache.cassandra.index

Methods in org.apache.cassandra.index with parameters of type Row

Modifier and Type
Method and Description

void
Index.Indexer.insertRow(Row row)

Notification that a new row was inserted into the Memtable holding the partition.

void
Index.Indexer.removeRow(Row row)

Notification that a row was removed from the partition.

void
Index.Indexer.updateRow(Row oldRowData,
         Row newRowData)

Notification of a modification to a row in the base table's Memtable.

Uses of Row in org.apache.cassandra.index.internal

Methods in org.apache.cassandra.index.internal with parameters of type Row

Modifier and Type
Method and Description

abstract IndexEntry
CassandraIndex.decodeEntry(DecoratedKey indexedValue,
           Row indexEntry)

Used at search time to convert a row in the index table into a simple struct containing the values required
 to retrieve the corresponding row from the base table.

abstract boolean
CassandraIndex.isStale(Row row,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

Check whether a value retrieved from an index is still valid by comparing it to current row from the base table.

Uses of Row in org.apache.cassandra.index.internal.composites

Methods in org.apache.cassandra.index.internal.composites with parameters of type Row

Modifier and Type
Method and Description

IndexEntry
ClusteringColumnIndex.decodeEntry(DecoratedKey indexedValue,
           Row indexEntry)

IndexEntry
CollectionKeyIndexBase.decodeEntry(DecoratedKey indexedValue,
           Row indexEntry)

IndexEntry
CollectionValueIndex.decodeEntry(DecoratedKey indexedValue,
           Row indexEntry)

IndexEntry
PartitionKeyIndex.decodeEntry(DecoratedKey indexedValue,
           Row indexEntry)

IndexEntry
RegularColumnIndex.decodeEntry(DecoratedKey indexedValue,
           Row indexEntry)

boolean
ClusteringColumnIndex.isStale(Row data,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

boolean
CollectionEntryIndex.isStale(Row data,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

boolean
CollectionKeyIndex.isStale(Row data,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

boolean
CollectionValueIndex.isStale(Row data,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

boolean
PartitionKeyIndex.isStale(Row data,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

boolean
RegularColumnIndex.isStale(Row data,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

Uses of Row in org.apache.cassandra.index.internal.keys

Methods in org.apache.cassandra.index.internal.keys with parameters of type Row

Modifier and Type
Method and Description

IndexEntry
KeysIndex.decodeEntry(DecoratedKey indexedValue,
           Row indexEntry)

boolean
KeysIndex.isStale(Row row,
       java.nio.ByteBuffer indexValue,
       int nowInSec)

Uses of Row in org.apache.cassandra.index.sasi.conf

Methods in org.apache.cassandra.index.sasi.conf with parameters of type Row

Modifier and Type
Method and Description

static java.nio.ByteBuffer
ColumnIndex.getValueOf(ColumnDefinition column,
          Row row,
          int nowInSecs)

long
ColumnIndex.index(DecoratedKey key,
     Row row)

Uses of Row in org.apache.cassandra.index.transactions

Methods in org.apache.cassandra.index.transactions with parameters of type Row

Modifier and Type
Method and Description

void
UpdateTransaction.onInserted(Row row)

void
CleanupTransaction.onRowDelete(Row row)

void
CompactionTransaction.onRowMerge(Row merged,
          Row... versions)

void
CompactionTransaction.onRowMerge(Row merged,
          Row... versions)

void
UpdateTransaction.onUpdated(Row existing,
         Row updated)

Uses of Row in org.apache.cassandra.io.sstable

Methods in org.apache.cassandra.io.sstable that return Row

Modifier and Type
Method and Description

abstract Row
SSTableSimpleIterator.readStaticRow()

Row
SSTableIdentityIterator.staticRow()

Uses of Row in org.apache.cassandra.service.pager

Methods in org.apache.cassandra.service.pager with parameters of type Row

Modifier and Type
Method and Description

static PagingState.RowMark
PagingState.RowMark.create(CFMetaData metadata,
      Row row,
      int protocolVersion)

protected void
RangeNamesQueryPager.recordLast(DecoratedKey key,
          Row last)

protected void
RangeSliceQueryPager.recordLast(DecoratedKey key,
          Row last)

protected void
SinglePartitionPager.recordLast(DecoratedKey key,
          Row last)

Uses of Row in org.apache.cassandra.streaming

Methods in org.apache.cassandra.streaming that return Row

Modifier and Type
Method and Description

Row
StreamReader.StreamDeserializer.staticRow()

Uses of Row in org.apache.cassandra.utils.memory

Methods in org.apache.cassandra.utils.memory that return Row

Modifier and Type
Method and Description

abstract Row
EnsureOnHeap.applyToRow(Row row)

abstract Row
EnsureOnHeap.applyToStatic(Row row)

Methods in org.apache.cassandra.utils.memory that return types with arguments of type Row

Modifier and Type
Method and Description

abstract java.util.Iterator<Row>
EnsureOnHeap.applyToPartition(java.util.Iterator<Row> partition)

abstract SearchIterator<Clustering,Row>
EnsureOnHeap.applyToPartition(SearchIterator<Clustering,Row> partition)

Methods in org.apache.cassandra.utils.memory with parameters of type Row

Modifier and Type
Method and Description

abstract Row
EnsureOnHeap.applyToRow(Row row)

abstract Row
EnsureOnHeap.applyToStatic(Row row)

MemtableAllocator.DataReclaimer
MemtableAllocator.DataReclaimer.reclaim(Row row)

MemtableAllocator.DataReclaimer
MemtableAllocator.DataReclaimer.reclaimImmediately(Row row)

Method parameters in org.apache.cassandra.utils.memory with type arguments of type Row

Modifier and Type
Method and Description

abstract java.util.Iterator<Row>
EnsureOnHeap.applyToPartition(java.util.Iterator<Row> partition)

abstract SearchIterator<Clustering,Row>
EnsureOnHeap.applyToPartition(SearchIterator<Clustering,Row> partition)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation