<commit_before>#include "transactionrecord.h"

#include "headers.h"

/* Return positive answer if transaction should be shown in list.
 */
bool TransactionRecord::showTransaction(const CWalletTx &wtx)
{
    if (wtx.IsCoinBase())
    {
        // Don't show generated coin until confirmed by at least one block after it
        // so we don't get the user's hopes up until it looks like it's probably accepted.
        //
        // It is not an error when generated blocks are not accepted.  By design,
        // some percentage of blocks, like 10% or more, will end up not accepted.
        // This is the normal mechanism by which the network copes with latency.
        //
        // We display regular transactions right away before any confirmation
        // because they can always get into some block eventually.  Generated coins
        // are special because if their block is not accepted, they are not valid.
        //
        if (wtx.GetDepthInMainChain() < 2)
        {
            return false;
        }
    }
    return true;
}

/*
 * Decompose CWallet transaction to model transaction records.
 */
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
    QList<TransactionRecord> parts;
    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();
    int64 nCredit = wtx.GetCredit(true);
    int64 nDebit = wtx.GetDebit();
    int64 nNet = nCredit - nDebit;
    uint256 hash = wtx.GetHash();
    std::map<std::string, std::string> mapValue = wtx.mapValue;

    if (showTransaction(wtx))
    {
        if (nNet > 0 || wtx.IsCoinBase())
        {
            //
            // Credit
            //
            TransactionRecord sub(hash, nTime);

            sub.credit = nNet;

            if (wtx.IsCoinBase())
            {
                // Generated
                sub.type = TransactionRecord::Generated;

                if (nCredit == 0)
                {
                    int64 nUnmatured = 0;
                    BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                        nUnmatured += wallet->GetCredit(txout);
                    sub.credit = nUnmatured;
                }
            }
            else
            {
                bool foundAddress = false;
                // Received by Bitcoin Address
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                {
                    if(wallet->IsMine(txout))
                    {
                        CBitcoinAddress address;
                        if (ExtractAddress(txout.scriptPubKey, address) && wallet->HaveKey(address))
                        {
                            sub.type = TransactionRecord::RecvWithAddress;
                            sub.address = address.ToString();
                            foundAddress = true;
                            break;
                        }
                    }
                }
                if(!foundAddress)
                {
                    // Received by IP connection, or other non-address transaction like OP_EVAL
                    sub.type = TransactionRecord::RecvFromOther;
                    sub.address = mapValue["from"];
                }
            }
            parts.append(sub);
        }
        else
        {
            bool fAllFromMe = true;
            BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                fAllFromMe = fAllFromMe && wallet->IsMine(txin);

            bool fAllToMe = true;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                fAllToMe = fAllToMe && wallet->IsMine(txout);

            if (fAllFromMe && fAllToMe)
            {
                // Payment to self
                int64 nChange = wtx.GetChange();

                parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "",
                                -(nDebit - nChange), nCredit - nChange));
            }
            else if (fAllFromMe)
            {
                //
                // Debit
                //
                int64 nTxFee = nDebit - wtx.GetValueOut();

                for (int nOut = 0; nOut < wtx.vout.size(); nOut++)
                {
                    const CTxOut& txout = wtx.vout[nOut];
                    TransactionRecord sub(hash, nTime);
                    sub.idx = parts.size();

                    if(wallet->IsMine(txout))
                    {
                        // Ignore parts sent to self, as this is usually the change
                        // from a transaction sent back to our own address.
                        continue;
                    }

                    CBitcoinAddress address;
                    if (ExtractAddress(txout.scriptPubKey, address))
                    {
                        // Sent to Bitcoin Address
                        sub.type = TransactionRecord::SendToAddress;
                        sub.address = address.ToString();
                    }
                    else
                    {
                        // Sent to IP, or other non-address transaction like OP_EVAL
                        sub.type = TransactionRecord::SendToOther;
                        sub.address = mapValue["to"];
                    }

                    int64 nValue = txout.nValue;
                    /* Add fee to first output */
                    if (nTxFee > 0)
                    {
                        nValue += nTxFee;
                        nTxFee = 0;
                    }
                    sub.debit = -nValue;

                    parts.append(sub);
                }
            }
            else
            {
                //
                // Mixed debit transaction, can't break down payees
                //
                bool fAllMine = true;
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                    fAllMine = fAllMine && wallet->IsMine(txout);
                BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                    fAllMine = fAllMine && wallet->IsMine(txin);

                parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0));
            }
        }
    }

    return parts;
}

void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
    // Determine transaction status

    // Find the block the tx is in
    CBlockIndex* pindex = NULL;
    std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);
    if (mi != mapBlockIndex.end())
        pindex = (*mi).second;

    // Sort order, unrecorded transactions sort to the top
    status.sortKey = strprintf("%010d-%01d-%010u-%03d",
        (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
        (wtx.IsCoinBase() ? 1 : 0),
        wtx.nTimeReceived,
        idx);
    status.confirmed = wtx.IsConfirmed();
    status.depth = wtx.GetDepthInMainChain();
    status.cur_num_blocks = nBestHeight;

    if (!wtx.IsFinal())
    {
        if (wtx.nLockTime < LOCKTIME_THRESHOLD)
        {
            status.status = TransactionStatus::OpenUntilBlock;
            status.open_for = nBestHeight - wtx.nLockTime;
        }
        else
        {
            status.status = TransactionStatus::OpenUntilDate;
            status.open_for = wtx.nLockTime;
        }
    }
    else
    {
        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
        {
            status.status = TransactionStatus::Offline;
        }
        else if (status.depth < NumConfirmations)
        {
            status.status = TransactionStatus::Unconfirmed;
        }
        else
        {
            status.status = TransactionStatus::HaveConfirmations;
        }
    }

    // For generated transactions, determine maturity
    if(type == TransactionRecord::Generated)
    {
        int64 nCredit = wtx.GetCredit(true);
        if (nCredit == 0)
        {
            status.maturity = TransactionStatus::Immature;

            if (wtx.IsInMainChain())
            {
                status.matures_in = wtx.GetBlocksToMaturity();

                // Check if the block was requested by anyone
                if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
                    status.maturity = TransactionStatus::MaturesWarning;
            }
            else
            {
                status.maturity = TransactionStatus::NotAccepted;
            }
        }
        else
        {
            status.maturity = TransactionStatus::Mature;
        }
    }
}

bool TransactionRecord::statusUpdateNeeded()
{
    return status.cur_num_blocks != nBestHeight;
}

std::string TransactionRecord::getTxID()
{
    return hash.ToString() + strprintf("-%03d", idx);
}

<commit_msg>Restructure credit transaction decomposition (solves issue #689)<commit_after>#include "transactionrecord.h"

#include "headers.h"

/* Return positive answer if transaction should be shown in list.
 */
bool TransactionRecord::showTransaction(const CWalletTx &wtx)
{
    if (wtx.IsCoinBase())
    {
        // Don't show generated coin until confirmed by at least one block after it
        // so we don't get the user's hopes up until it looks like it's probably accepted.
        //
        // It is not an error when generated blocks are not accepted.  By design,
        // some percentage of blocks, like 10% or more, will end up not accepted.
        // This is the normal mechanism by which the network copes with latency.
        //
        // We display regular transactions right away before any confirmation
        // because they can always get into some block eventually.  Generated coins
        // are special because if their block is not accepted, they are not valid.
        //
        if (wtx.GetDepthInMainChain() < 2)
        {
            return false;
        }
    }
    return true;
}

/*
 * Decompose CWallet transaction to model transaction records.
 */
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
    QList<TransactionRecord> parts;
    int64 nTime = wtx.nTimeDisplayed = wtx.GetTxTime();
    int64 nCredit = wtx.GetCredit(true);
    int64 nDebit = wtx.GetDebit();
    int64 nNet = nCredit - nDebit;
    uint256 hash = wtx.GetHash();
    std::map<std::string, std::string> mapValue = wtx.mapValue;

    if (showTransaction(wtx))
    {
        if (nNet > 0 || wtx.IsCoinBase())
        {
            //
            // Credit
            //
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
            {
                if(wallet->IsMine(txout))
                {
                    TransactionRecord sub(hash, nTime);
                    CBitcoinAddress address;
                    sub.idx = parts.size(); // sequence number
                    sub.credit = txout.nValue;
                    if (wtx.IsCoinBase())
                    {
                        // Generated
                        sub.type = TransactionRecord::Generated;
                    }
                    else if (ExtractAddress(txout.scriptPubKey, address) && wallet->HaveKey(address))
                    {
                        // Received by Bitcoin Address
                        sub.type = TransactionRecord::RecvWithAddress;
                        sub.address = address.ToString();
                    }
                    else
                    {
                        // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
                        sub.type = TransactionRecord::RecvFromOther;
                        sub.address = mapValue["from"];
                    }

                    parts.append(sub);
                }
            }
        }
        else
        {
            bool fAllFromMe = true;
            BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                fAllFromMe = fAllFromMe && wallet->IsMine(txin);

            bool fAllToMe = true;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                fAllToMe = fAllToMe && wallet->IsMine(txout);

            if (fAllFromMe && fAllToMe)
            {
                // Payment to self
                int64 nChange = wtx.GetChange();

                parts.append(TransactionRecord(hash, nTime, TransactionRecord::SendToSelf, "",
                                -(nDebit - nChange), nCredit - nChange));
            }
            else if (fAllFromMe)
            {
                //
                // Debit
                //
                int64 nTxFee = nDebit - wtx.GetValueOut();

                for (int nOut = 0; nOut < wtx.vout.size(); nOut++)
                {
                    const CTxOut& txout = wtx.vout[nOut];
                    TransactionRecord sub(hash, nTime);
                    sub.idx = parts.size();

                    if(wallet->IsMine(txout))
                    {
                        // Ignore parts sent to self, as this is usually the change
                        // from a transaction sent back to our own address.
                        continue;
                    }

                    CBitcoinAddress address;
                    if (ExtractAddress(txout.scriptPubKey, address))
                    {
                        // Sent to Bitcoin Address
                        sub.type = TransactionRecord::SendToAddress;
                        sub.address = address.ToString();
                    }
                    else
                    {
                        // Sent to IP, or other non-address transaction like OP_EVAL
                        sub.type = TransactionRecord::SendToOther;
                        sub.address = mapValue["to"];
                    }

                    int64 nValue = txout.nValue;
                    /* Add fee to first output */
                    if (nTxFee > 0)
                    {
                        nValue += nTxFee;
                        nTxFee = 0;
                    }
                    sub.debit = -nValue;

                    parts.append(sub);
                }
            }
            else
            {
                //
                // Mixed debit transaction, can't break down payees
                //
                bool fAllMine = true;
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                    fAllMine = fAllMine && wallet->IsMine(txout);
                BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                    fAllMine = fAllMine && wallet->IsMine(txin);

                parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0));
            }
        }
    }

    return parts;
}

void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
    // Determine transaction status

    // Find the block the tx is in
    CBlockIndex* pindex = NULL;
    std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(wtx.hashBlock);
    if (mi != mapBlockIndex.end())
        pindex = (*mi).second;

    // Sort order, unrecorded transactions sort to the top
    status.sortKey = strprintf("%010d-%01d-%010u-%03d",
        (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
        (wtx.IsCoinBase() ? 1 : 0),
        wtx.nTimeReceived,
        idx);
    status.confirmed = wtx.IsConfirmed();
    status.depth = wtx.GetDepthInMainChain();
    status.cur_num_blocks = nBestHeight;

    if (!wtx.IsFinal())
    {
        if (wtx.nLockTime < LOCKTIME_THRESHOLD)
        {
            status.status = TransactionStatus::OpenUntilBlock;
            status.open_for = nBestHeight - wtx.nLockTime;
        }
        else
        {
            status.status = TransactionStatus::OpenUntilDate;
            status.open_for = wtx.nLockTime;
        }
    }
    else
    {
        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
        {
            status.status = TransactionStatus::Offline;
        }
        else if (status.depth < NumConfirmations)
        {
            status.status = TransactionStatus::Unconfirmed;
        }
        else
        {
            status.status = TransactionStatus::HaveConfirmations;
        }
    }

    // For generated transactions, determine maturity
    if(type == TransactionRecord::Generated)
    {
        int64 nCredit = wtx.GetCredit(true);
        if (nCredit == 0)
        {
            status.maturity = TransactionStatus::Immature;

            if (wtx.IsInMainChain())
            {
                status.matures_in = wtx.GetBlocksToMaturity();

                // Check if the block was requested by anyone
                if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
                    status.maturity = TransactionStatus::MaturesWarning;
            }
            else
            {
                status.maturity = TransactionStatus::NotAccepted;
            }
        }
        else
        {
            status.maturity = TransactionStatus::Mature;
        }
    }
}

bool TransactionRecord::statusUpdateNeeded()
{
    return status.cur_num_blocks != nBestHeight;
}

std::string TransactionRecord::getTxID()
{
    return hash.ToString() + strprintf("-%03d", idx);
}

<|endoftext|>


<commit_before>#include "utils.h"
#include "crypto/sha2.h"
#include "flaggedarrayset.h"
#include "relayprocess.h"

#include <stdio.h>
#include <sys/time.h>
#include <algorithm>
#include <random>
#include <string.h>
#include <unistd.h>

void fill_txv(std::vector<unsigned char>& block, std::vector<std::shared_ptr<std::vector<unsigned char> > >& txVectors, float includeP) {
	std::vector<unsigned char>::const_iterator readit = block.begin();
	move_forward(readit, sizeof(struct bitcoin_msg_header), block.end());
	move_forward(readit, 80, block.end());
	uint32_t txcount = read_varint(readit, block.end());

	std::default_random_engine engine; std::uniform_real_distribution<double> distribution(0.0, 1.0);

	for (uint32_t i = 0; i < txcount; i++) {
		std::vector<unsigned char>::const_iterator txstart = readit;

		move_forward(readit, 4, block.end());

		uint32_t txins = read_varint(readit, block.end());
		for (uint32_t j = 0; j < txins; j++) {
			move_forward(readit, 36, block.end());
			uint32_t scriptlen = read_varint(readit, block.end());
			move_forward(readit, scriptlen + 4, block.end());
		}

		uint32_t txouts = read_varint(readit, block.end());
		for (uint32_t j = 0; j < txouts; j++) {
			move_forward(readit, 8, block.end());
			uint32_t scriptlen = read_varint(readit, block.end());
			move_forward(readit, scriptlen, block.end());
		}

		move_forward(readit, 4, block.end());

		if (distribution(engine) < includeP)
			txVectors.push_back(std::make_shared<std::vector<unsigned char> >(txstart, readit));
	}

	std::shuffle(txVectors.begin(), txVectors.end(), std::default_random_engine());
}

int pipefd[2];
uint32_t block_tx_count;
std::shared_ptr<std::vector<unsigned char> > decompressed_block;
RelayNodeCompressor receiver;

void recv_block() {
	auto res = receiver.decompress_relay_block(pipefd[0], block_tx_count);
	if (std::get<2>(res)) {
		printf("ERROR Decompressing block %s\n", std::get<2>(res));
		exit(2);
	}
	decompressed_block = std::get<1>(res);
}

void compress_block(std::vector<unsigned char>& data, std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors) {
	std::vector<unsigned char> fullhash(32);
	getblockhash(fullhash, data, sizeof(struct bitcoin_msg_header));

	RelayNodeCompressor sender;
	receiver.reset();

	for (auto& v : txVectors)
		if (sender.get_relay_transaction(v).use_count())
			receiver.recv_tx(v);

	struct timeval start, compressed;
	gettimeofday(&start, NULL);
	auto res = sender.maybe_compress_block(fullhash, data, true);
	gettimeofday(&compressed, NULL);
	printf("Compressed from %lu to %lu in %ld ms with %lu txn pre-relayed\n", data.size(), std::get<0>(res)->size(), int64_t(compressed.tv_sec - start.tv_sec)*1000 + (int64_t(compressed.tv_usec) - start.tv_usec)/1000, txVectors.size());

	struct relay_msg_header header;
	memcpy(&header, &(*std::get<0>(res))[0], sizeof(header));
	block_tx_count = ntohl(header.length);

	if (pipe(pipefd)) {
		printf("Failed to create pipe?\n");
		exit(3);
	}

	std::thread recv(recv_block);
	write(pipefd[1], &(*std::get<0>(res))[sizeof(header)], std::get<0>(res)->size() - sizeof(header));
	recv.join();

	if (*decompressed_block != data) {
		printf("Re-constructed block did not match!\n");
		exit(4);
	}
}

void run_test(std::vector<unsigned char>& data) {
	std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors;
	compress_block(data, txVectors);

	fill_txv(data, txVectors, 1.0);
	compress_block(data, txVectors);

	txVectors.clear();
	fill_txv(data, txVectors, 0.5);
	compress_block(data, txVectors);

	txVectors.clear();
	fill_txv(data, txVectors, 0.9);
	compress_block(data, txVectors);
}

int main() {
	std::vector<unsigned char> data(sizeof(struct bitcoin_msg_header));
	std::vector<unsigned char> lastBlock;

	std::vector<std::shared_ptr<std::vector<unsigned char> > > allTxn;

	FILE* f = fopen("block.txt", "r");
	while (true) {
		char hex[2];
		if (fread(hex, 1, 1, f) != 1)
			break;
		else if (hex[0] == '\n') {
			if (data.size()) {
				run_test(data);
				fill_txv(data, allTxn, 0.9);
				lastBlock = data;
			}
			data = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header));
		} else if (fread(hex + 1, 1, 1, f) != 1)
			break;
		else {
			if (hex[0] >= 'a')
				hex[0] -= 'a' - '9' - 1;
			if (hex[1] >= 'a')
				hex[1] -= 'a' - '9' - 1;
			data.push_back((hex[0] - '0') << 4 | (hex[1] - '0'));
		}
	}

	compress_block(lastBlock, allTxn);
	return 0;
}
<commit_msg>Time decompress in test as well<commit_after>#include "utils.h"
#include "crypto/sha2.h"
#include "flaggedarrayset.h"
#include "relayprocess.h"

#include <stdio.h>
#include <sys/time.h>
#include <algorithm>
#include <random>
#include <string.h>
#include <unistd.h>

void fill_txv(std::vector<unsigned char>& block, std::vector<std::shared_ptr<std::vector<unsigned char> > >& txVectors, float includeP) {
	std::vector<unsigned char>::const_iterator readit = block.begin();
	move_forward(readit, sizeof(struct bitcoin_msg_header), block.end());
	move_forward(readit, 80, block.end());
	uint32_t txcount = read_varint(readit, block.end());

	std::default_random_engine engine; std::uniform_real_distribution<double> distribution(0.0, 1.0);

	for (uint32_t i = 0; i < txcount; i++) {
		std::vector<unsigned char>::const_iterator txstart = readit;

		move_forward(readit, 4, block.end());

		uint32_t txins = read_varint(readit, block.end());
		for (uint32_t j = 0; j < txins; j++) {
			move_forward(readit, 36, block.end());
			uint32_t scriptlen = read_varint(readit, block.end());
			move_forward(readit, scriptlen + 4, block.end());
		}

		uint32_t txouts = read_varint(readit, block.end());
		for (uint32_t j = 0; j < txouts; j++) {
			move_forward(readit, 8, block.end());
			uint32_t scriptlen = read_varint(readit, block.end());
			move_forward(readit, scriptlen, block.end());
		}

		move_forward(readit, 4, block.end());

		if (distribution(engine) < includeP)
			txVectors.push_back(std::make_shared<std::vector<unsigned char> >(txstart, readit));
	}

	std::shuffle(txVectors.begin(), txVectors.end(), std::default_random_engine());
}

int pipefd[2];
uint32_t block_tx_count;
std::shared_ptr<std::vector<unsigned char> > decompressed_block;
RelayNodeCompressor receiver;

void recv_block() {
	struct timeval start, decompressed;
	gettimeofday(&start, NULL);
	auto res = receiver.decompress_relay_block(pipefd[0], block_tx_count);
	gettimeofday(&decompressed, NULL);

	if (std::get<2>(res)) {
		printf("ERROR Decompressing block %s\n", std::get<2>(res));
		exit(2);
	} else
		printf("Decompressed block in %lu ms\n", int64_t(decompressed.tv_sec - start.tv_sec)*1000 + (int64_t(decompressed.tv_usec) - start.tv_usec)/1000);
	decompressed_block = std::get<1>(res);
}

void compress_block(std::vector<unsigned char>& data, std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors) {
	std::vector<unsigned char> fullhash(32);
	getblockhash(fullhash, data, sizeof(struct bitcoin_msg_header));

	RelayNodeCompressor sender;
	receiver.reset();

	for (auto& v : txVectors)
		if (sender.get_relay_transaction(v).use_count())
			receiver.recv_tx(v);

	struct timeval start, compressed;
	gettimeofday(&start, NULL);
	auto res = sender.maybe_compress_block(fullhash, data, true);
	gettimeofday(&compressed, NULL);
	printf("Compressed from %lu to %lu in %ld ms with %lu txn pre-relayed\n", data.size(), std::get<0>(res)->size(), int64_t(compressed.tv_sec - start.tv_sec)*1000 + (int64_t(compressed.tv_usec) - start.tv_usec)/1000, txVectors.size());

	struct relay_msg_header header;
	memcpy(&header, &(*std::get<0>(res))[0], sizeof(header));
	block_tx_count = ntohl(header.length);

	if (pipe(pipefd)) {
		printf("Failed to create pipe?\n");
		exit(3);
	}

	std::thread recv(recv_block);
	write(pipefd[1], &(*std::get<0>(res))[sizeof(header)], std::get<0>(res)->size() - sizeof(header));
	recv.join();

	if (*decompressed_block != data) {
		printf("Re-constructed block did not match!\n");
		exit(4);
	}
}

void run_test(std::vector<unsigned char>& data) {
	std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors;
	compress_block(data, txVectors);

	fill_txv(data, txVectors, 1.0);
	compress_block(data, txVectors);

	txVectors.clear();
	fill_txv(data, txVectors, 0.5);
	compress_block(data, txVectors);

	txVectors.clear();
	fill_txv(data, txVectors, 0.9);
	compress_block(data, txVectors);
}

int main() {
	std::vector<unsigned char> data(sizeof(struct bitcoin_msg_header));
	std::vector<unsigned char> lastBlock;

	std::vector<std::shared_ptr<std::vector<unsigned char> > > allTxn;

	FILE* f = fopen("block.txt", "r");
	while (true) {
		char hex[2];
		if (fread(hex, 1, 1, f) != 1)
			break;
		else if (hex[0] == '\n') {
			if (data.size()) {
				run_test(data);
				fill_txv(data, allTxn, 0.9);
				lastBlock = data;
			}
			data = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header));
		} else if (fread(hex + 1, 1, 1, f) != 1)
			break;
		else {
			if (hex[0] >= 'a')
				hex[0] -= 'a' - '9' - 1;
			if (hex[1] >= 'a')
				hex[1] -= 'a' - '9' - 1;
			data.push_back((hex[0] - '0') << 4 | (hex[1] - '0'));
		}
	}

	compress_block(lastBlock, allTxn);
	return 0;
}
<|endoftext|>


<commit_before>#include "CUDADenseGraphBFSearcher.h"
#include <sqaodc/common/internal/ShapeChecker.h>
#include <sqaodc/cpu/SharedFormulas.h>
#include "Device.h"
#include <cmath>
#include <float.h>
#include <algorithm>
#include <limits>

namespace sqint = sqaod_internal;
namespace sqcpu = sqaod_cpu;
using namespace sqaod_cuda;

template<class real>
CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher() {
    tileSize_ = 1u << 18; /* FIXME: give a correct size */
    deviceAssigned_ = false;
}

template<class real>
CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher(Device &device) {
    tileSize_ = 1u << 18; /* FIXME: give a correct size */
    deviceAssigned_ = false;
    assignDevice(device);
}

template<class real>
CUDADenseGraphBFSearcher<real>::~CUDADenseGraphBFSearcher() {
}

template<class real>
void CUDADenseGraphBFSearcher<real>::deallocate() {
    if (h_packedXmin_.d_data != NULL)
        HostObjectAllocator().deallocate(h_packedXmin_);
    batchSearch_.deallocate();
}

template<class real>
void CUDADenseGraphBFSearcher<real>::assignDevice(sqaod::cuda::Device &device) {
    assignDevice(static_cast<Device&>(device));
}

template<class real>
void CUDADenseGraphBFSearcher<real>::assignDevice(Device &device) {
    throwErrorIf(deviceAssigned_, "Device already assigned.");
    batchSearch_.assignDevice(device);
    devCopy_.assignDevice(device);
    deviceAssigned_ = true;
}

template<class real>
void CUDADenseGraphBFSearcher<real>::setQUBO(const Matrix &W, sq::OptimizeMethod om) {
    throwErrorIf(!deviceAssigned_, "Device not set.");
    sqint::matrixCheckIfSymmetric(W, __func__);
    throwErrorIf(63 < W.rows, "N must be smaller than 64, N=%d.", W.rows);

    N_ = W.rows;
    W_ = sqcpu::symmetrize(W);
    om_ = om;
    if (om_ == sq::optMaximize)
        W_ *= real(-1.);

    setState(solProblemSet);
}

template<class real>
sq::Preferences CUDADenseGraphBFSearcher<real>::getPreferences() const {
    sq::Preferences prefs = Base::getPreferences();
    prefs.pushBack(sq::Preference(sq::pnDevice, "cuda"));
    return prefs;
}

template<class real>
const sq::BitSetArray &CUDADenseGraphBFSearcher<real>::get_x() const {
    if (!isSolutionAvailable())
        const_cast<This*>(this)->makeSolution(); /* synchronized there */
    return xList_;
}

template<class real>
const sq::VectorType<real> &CUDADenseGraphBFSearcher<real>::get_E() const {
    if (!isEAvailable())
        const_cast<This*>(this)->calculate_E();
    return E_;
}

template<class real>
void CUDADenseGraphBFSearcher<real>::prepare() {
    throwErrorIfProblemNotSet();
    deallocate();

    x_ = 0;
    sq::PackedBitSet maxTileSize = 1ull << N_;
    if (maxTileSize < (sq::PackedBitSet)tileSize_) {
        tileSize_ = maxTileSize;
        sq::log("Tile size is adjusted to %d for N=%d", maxTileSize, N_);
    }
    batchSearch_.setQUBO(W_, tileSize_);
    HostObjectAllocator().allocate(&h_packedXmin_, tileSize_ * 2);

    Emin_ = std::numeric_limits<real>::max();
    xList_.clear();
    xMax_ = 1ull << N_;

    setState(solPrepared);

#ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST
    rangeMap_.clear();
#endif
}

template<class real>
void CUDADenseGraphBFSearcher<real>::calculate_E() {
    throwErrorIfNotPrepared();
    if (xList_.empty())
        E_.resize(1);
    else
        E_.resize(xList_.size());
    E_ = Emin_;
    if (om_ == sq::optMaximize)
        E_ *= real(-1.);

    setState(solEAvailable);
}

template<class real>
void CUDADenseGraphBFSearcher<real>::makeSolution() {
    throwErrorIfNotPrepared();

    batchSearch_.synchronize();
    const DevicePackedBitSetArray &dPackedXmin = batchSearch_.get_xMins();
    sq::SizeType nXMin = std::min(tileSize_, dPackedXmin.size);
    devCopy_(&h_packedXmin_, dPackedXmin);
    devCopy_.synchronize();

    xList_.clear();
    for (sq::IdxType idx = 0; idx < (sq::IdxType)nXMin; ++idx) {
        sq::BitSet bits;
        unpackBitSet(&bits, h_packedXmin_[idx], N_);
        xList_.pushBack(bits); // FIXME: apply move
    }
    setState(solSolutionAvailable);
    calculate_E();

#ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST
    assert(rangeMap_.size() == 1);
    sq::PackedBitSetPair pair = rangeMap_[0];
    assert((pair.bits0 == 0) && (pair.bits1 == xMax_));
#endif
}

template<class real>
bool CUDADenseGraphBFSearcher<real>::searchRange(sq::PackedBitSet *curXEnd) {
    throwErrorIfNotPrepared();
    clearState(solSolutionAvailable);

    /* FIXME: Use multiple searchers, multi GPU */

    sq::PackedBitSet xBegin = x_;
    sq::PackedBitSet xEnd = std::min(x_ + tileSize_, xMax_);
    if (xBegin < xEnd) {
        batchSearch_.calculate_E(xBegin, xEnd);
        batchSearch_.synchronize();

        real newEmin = batchSearch_.get_Emin();
        if (newEmin < Emin_) {
            batchSearch_.partition_xMins(false);
            Emin_ = newEmin;
        }
        else if (newEmin == Emin_) {
            batchSearch_.partition_xMins(true);
        }
    }

#ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST
    if (xBegin < xEnd)
        rangeMap_.insert(xBegin, xEnd);
#endif
    x_ = xEnd;
    if (curXEnd != NULL)
        *curXEnd = x_;
    return x_ == xMax_;
}

template class sqaod_cuda::CUDADenseGraphBFSearcher<float>;
template class sqaod_cuda::CUDADenseGraphBFSearcher<double>;
<commit_msg>Suppress warning on VS.<commit_after>#include "CUDADenseGraphBFSearcher.h"
#include <sqaodc/common/internal/ShapeChecker.h>
#include <sqaodc/cpu/SharedFormulas.h>
#include "Device.h"
#include <cmath>
#include <float.h>
#include <algorithm>
#include <limits>

namespace sqint = sqaod_internal;
namespace sqcpu = sqaod_cpu;
using namespace sqaod_cuda;

template<class real>
CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher() {
    tileSize_ = 1u << 18; /* FIXME: give a correct size */
    deviceAssigned_ = false;
}

template<class real>
CUDADenseGraphBFSearcher<real>::CUDADenseGraphBFSearcher(Device &device) {
    tileSize_ = 1u << 18; /* FIXME: give a correct size */
    deviceAssigned_ = false;
    assignDevice(device);
}

template<class real>
CUDADenseGraphBFSearcher<real>::~CUDADenseGraphBFSearcher() {
}

template<class real>
void CUDADenseGraphBFSearcher<real>::deallocate() {
    if (h_packedXmin_.d_data != NULL)
        HostObjectAllocator().deallocate(h_packedXmin_);
    batchSearch_.deallocate();
}

template<class real>
void CUDADenseGraphBFSearcher<real>::assignDevice(sqaod::cuda::Device &device) {
    assignDevice(static_cast<Device&>(device));
}

template<class real>
void CUDADenseGraphBFSearcher<real>::assignDevice(Device &device) {
    throwErrorIf(deviceAssigned_, "Device already assigned.");
    batchSearch_.assignDevice(device);
    devCopy_.assignDevice(device);
    deviceAssigned_ = true;
}

template<class real>
void CUDADenseGraphBFSearcher<real>::setQUBO(const Matrix &W, sq::OptimizeMethod om) {
    throwErrorIf(!deviceAssigned_, "Device not set.");
    sqint::matrixCheckIfSymmetric(W, __func__);
    throwErrorIf(63 < W.rows, "N must be smaller than 64, N=%d.", W.rows);

    N_ = W.rows;
    W_ = sqcpu::symmetrize(W);
    om_ = om;
    if (om_ == sq::optMaximize)
        W_ *= real(-1.);

    setState(solProblemSet);
}

template<class real>
sq::Preferences CUDADenseGraphBFSearcher<real>::getPreferences() const {
    sq::Preferences prefs = Base::getPreferences();
    prefs.pushBack(sq::Preference(sq::pnDevice, "cuda"));
    return prefs;
}

template<class real>
const sq::BitSetArray &CUDADenseGraphBFSearcher<real>::get_x() const {
    if (!isSolutionAvailable())
        const_cast<This*>(this)->makeSolution(); /* synchronized there */
    return xList_;
}

template<class real>
const sq::VectorType<real> &CUDADenseGraphBFSearcher<real>::get_E() const {
    if (!isEAvailable())
        const_cast<This*>(this)->calculate_E();
    return E_;
}

template<class real>
void CUDADenseGraphBFSearcher<real>::prepare() {
    throwErrorIfProblemNotSet();
    deallocate();

    x_ = 0;
    sq::PackedBitSet maxTileSize = 1ull << N_;
    if (maxTileSize < (sq::PackedBitSet)tileSize_) {
        tileSize_ = (sq::SizeType)maxTileSize;
        sq::log("Tile size is adjusted to %d for N=%d", maxTileSize, N_);
    }
    batchSearch_.setQUBO(W_, tileSize_);
    HostObjectAllocator().allocate(&h_packedXmin_, tileSize_ * 2);

    Emin_ = std::numeric_limits<real>::max();
    xList_.clear();
    xMax_ = 1ull << N_;

    setState(solPrepared);

#ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST
    rangeMap_.clear();
#endif
}

template<class real>
void CUDADenseGraphBFSearcher<real>::calculate_E() {
    throwErrorIfNotPrepared();
    if (xList_.empty())
        E_.resize(1);
    else
        E_.resize(xList_.size());
    E_ = Emin_;
    if (om_ == sq::optMaximize)
        E_ *= real(-1.);

    setState(solEAvailable);
}

template<class real>
void CUDADenseGraphBFSearcher<real>::makeSolution() {
    throwErrorIfNotPrepared();

    batchSearch_.synchronize();
    const DevicePackedBitSetArray &dPackedXmin = batchSearch_.get_xMins();
    sq::SizeType nXMin = std::min(tileSize_, dPackedXmin.size);
    devCopy_(&h_packedXmin_, dPackedXmin);
    devCopy_.synchronize();

    xList_.clear();
    for (sq::IdxType idx = 0; idx < (sq::IdxType)nXMin; ++idx) {
        sq::BitSet bits;
        unpackBitSet(&bits, h_packedXmin_[idx], N_);
        xList_.pushBack(bits); // FIXME: apply move
    }
    setState(solSolutionAvailable);
    calculate_E();

#ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST
    assert(rangeMap_.size() == 1);
    sq::PackedBitSetPair pair = rangeMap_[0];
    assert((pair.bits0 == 0) && (pair.bits1 == xMax_));
#endif
}

template<class real>
bool CUDADenseGraphBFSearcher<real>::searchRange(sq::PackedBitSet *curXEnd) {
    throwErrorIfNotPrepared();
    clearState(solSolutionAvailable);

    /* FIXME: Use multiple searchers, multi GPU */

    sq::PackedBitSet xBegin = x_;
    sq::PackedBitSet xEnd = std::min(x_ + tileSize_, xMax_);
    if (xBegin < xEnd) {
        batchSearch_.calculate_E(xBegin, xEnd);
        batchSearch_.synchronize();

        real newEmin = batchSearch_.get_Emin();
        if (newEmin < Emin_) {
            batchSearch_.partition_xMins(false);
            Emin_ = newEmin;
        }
        else if (newEmin == Emin_) {
            batchSearch_.partition_xMins(true);
        }
    }

#ifdef SQAODC_ENABLE_RANGE_COVERAGE_TEST
    if (xBegin < xEnd)
        rangeMap_.insert(xBegin, xEnd);
#endif
    x_ = xEnd;
    if (curXEnd != NULL)
        *curXEnd = x_;
    return x_ == xMax_;
}

template class sqaod_cuda::CUDADenseGraphBFSearcher<float>;
template class sqaod_cuda::CUDADenseGraphBFSearcher<double>;
<|endoftext|>


<commit_before>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// User message widget
//==============================================================================

#include "usermessagewidget.h"

//==============================================================================

#include <Qt>

//==============================================================================

#include <QFont>
#include <QSizePolicy>
#include <QWidget>

//==============================================================================

namespace OpenCOR {
namespace Core {

//==============================================================================

void UserMessageWidget::constructor(const QString &pIcon,
                                    const QString &pMessage,
                                    const QString &pExtraMessage)
{
    // Some initialisations

    mIcon = QString();
    mMessage = QString();
    mExtraMessage = QString();

    // Customise our background

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Base);

    // Increase the size of our font

    QFont newFont = font();

    newFont.setPointSizeF(1.35*newFont.pointSize());

    setFont(newFont);

    // Some other customisations

    setContextMenuPolicy(Qt::NoContextMenu);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setWordWrap(true);

    // 'Initialise' our message

    setIconMessage(pIcon, pMessage, pExtraMessage);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(const QString &pIcon,
                                     const QString &pMessage,
                                     const QString &pExtraMessage,
                                     QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor(pIcon, pMessage, pExtraMessage);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(const QString &pIcon,
                                     const QString &pMessage,
                                     QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor(pIcon, pMessage);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor(pIcon);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor();
}

//==============================================================================

void UserMessageWidget::setIconMessage(const QString &pIcon,
                                       const QString &pMessage,
                                       const QString &pExtraMessage)
{
    // Set our message, if needed

    if (   pIcon.compare(mIcon)
        || pMessage.compare(mMessage)
        || pExtraMessage.compare(mExtraMessage)) {
        mIcon = pIcon;
        mMessage = pMessage;
        mExtraMessage = pExtraMessage;

        if (mExtraMessage.isEmpty())
            setText(QString("
"
                            "
"
                            "        "
                            "            "
                            "        	"
                            "        "
                            "
"
                            "                %2"
                            "
"
                            "        	"
                            "
"
                            "
").arg(mIcon, mMessage));
        else
            setText(QString("
"
                            "
"
                            "        "
                            "            "
                            "        	"
                            "        "
                            "
"
                            "                %2"
                            "
"
                            "
"
                            "                (%3)"
                            "
"
                            "        	"
                            "
"
                            "
").arg(mIcon, mMessage, mExtraMessage));
    }
}

//==============================================================================

void UserMessageWidget::setMessage(const QString &pMessage,
                                   const QString &pExtraMessage)
{
    // Set our message

    setIconMessage(mIcon, pMessage, pExtraMessage);
}

//==============================================================================

}   // namespace Core
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up of Core::UserMessageWidget.<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// User message widget
//==============================================================================

#include "usermessagewidget.h"

//==============================================================================

#include <Qt>

//==============================================================================

#include <QFont>
#include <QSizePolicy>
#include <QWidget>

//==============================================================================

namespace OpenCOR {
namespace Core {

//==============================================================================

void UserMessageWidget::constructor(const QString &pIcon,
                                    const QString &pMessage,
                                    const QString &pExtraMessage)
{
    // Some initialisations

    mIcon = QString();
    mMessage = QString();
    mExtraMessage = QString();

    // Customise our background

    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Base);

    // Increase the size of our font

    QFont newFont = font();

    newFont.setPointSizeF(1.35*newFont.pointSize());

    setFont(newFont);

    // Some other customisations

    setContextMenuPolicy(Qt::NoContextMenu);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setWordWrap(true);

    // 'Initialise' our message

    setIconMessage(pIcon, pMessage, pExtraMessage);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(const QString &pIcon,
                                     const QString &pMessage,
                                     const QString &pExtraMessage,
                                     QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor(pIcon, pMessage, pExtraMessage);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(const QString &pIcon,
                                     const QString &pMessage,
                                     QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor(pIcon, pMessage);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor(pIcon);
}

//==============================================================================

UserMessageWidget::UserMessageWidget(QWidget *pParent) :
    QLabel(pParent)
{
    // Construct our object

    constructor();
}

//==============================================================================

void UserMessageWidget::setIconMessage(const QString &pIcon,
                                       const QString &pMessage,
                                       const QString &pExtraMessage)
{
    // Set our message, if needed

    if (   pIcon.compare(mIcon)
        || pMessage.compare(mMessage)
        || pExtraMessage.compare(mExtraMessage)) {
        mIcon = pIcon;
        mMessage = pMessage;
        mExtraMessage = pExtraMessage;

        if (mExtraMessage.isEmpty())
            setText(QString("
"
                            "
"
                            "
"
                            "            "
                            "                "
                            "            	"
                            "            "
                            "
"
                            "                    %2"
                            "
"
                            "            	"
                            "
"
                            "
"
                            "
").arg(mIcon, mMessage));
        else
            setText(QString("
"
                            "
"
                            "
"
                            "            "
                            "                "
                            "            	"
                            "            "
                            "
"
                            "                    %2"
                            "
"
                            "
"
                            "                    (%3)"
                            "
"
                            "            	"
                            "
"
                            "
"
                            "
").arg(mIcon, mMessage, mExtraMessage));
    }
}

//==============================================================================

void UserMessageWidget::setMessage(const QString &pMessage,
                                   const QString &pExtraMessage)
{
    // Set our message

    setIconMessage(mIcon, pMessage, pExtraMessage);
}

//==============================================================================

}   // namespace Core
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>inline
cov_mat_kth::cov_mat_kth( const std::string in_path,
			  const std::string in_actionNames,
			  const int in_scale_factor,
			  const int in_shift,
			  const int in_scene, //only for kth
			  const int in_segment_length
)
:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length)
{
  actions.load( actionNames );
}

inline
void
cov_mat_kth::calculate( field<string> in_all_people, int  in_dim  )
{
  all_people = in_all_people;
  dim = in_dim;
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

  field <std::string> parallel_names(n_peo*n_actions,4);
  int sc = total_scenes; //Solo estoy usando 1
  int k =0;

      for (int pe = 0; pe< n_peo; ++pe)
      {
	for (int act=0; act<n_actions; ++act)
	{

	std::stringstream load_folder;
	std::stringstream load_feat_video_i;
	std::stringstream load_labels_video_i;

	load_folder << path <<"./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
	load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	parallel_names(k,0) = load_feat_video_i.str();
	parallel_names(k,1) = load_labels_video_i.str();
	parallel_names(k,2) = std::to_string(pe);
	parallel_names(k,3) = std::to_string(act);
	k++;

      }
    }

   //Aca podria hacer el paparelo

    for (int k = 0; k< parallel_names.n_rows; ++k)
    {

      std::string load_feat_video_i   = parallel_names(k,0);
      std::string load_labels_video_i = parallel_names(k,1);

      int pe   = atoi( parallel_names(k,2).c_str() );
      int act  = atoi( parallel_names(k,3).c_str() );

      cov_mat_kth::one_video(load_feat_video_i, load_labels_video_i, sc, pe, act );

    }

}

inline
void
cov_mat_kth::one_video( std::string load_feat_video_i,	std::string load_labels_video_i, int sc, int pe, int act )
{
  cout << load_feat_video_i << endl;
  mat mat_features_video_i;
  vec lab_video_i;

  mat_features_video_i.load( load_feat_video_i, hdf5_binary );
  lab_video_i.load( load_labels_video_i, hdf5_binary );
  int n_vec = lab_video_i.n_elem;
  int last = lab_video_i( n_vec - 1 );
  //cout << last << endl;

  int s = 0;

  std::stringstream save_folder;
  save_folder << "./kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;

  for (int l=2; l<last-segment_length; l = l+4 )
  {
    running_stat_vec<rowvec> stat_seg(true);
    //int k =0;

    //cout << " " << l;

    for (int j=l; j< l + segment_length; ++j)
    {
      //k++;
      //cout << " " << j;
      uvec indices = find(lab_video_i == j);
      mat tmp_feat = mat_features_video_i.cols(indices);
      //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl;
      for (int v=0; v < tmp_feat.n_cols; ++v)
      {
	vec sample = tmp_feat.col(v);
	stat_seg (sample);

      }

    }

    //cout << endl;
    //cout << " " << stat_seg.count();

    if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores
    {
    std::stringstream save_cov_seg;
    save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

    std::stringstream save_LogMcov_seg;
    save_LogMcov_seg << save_folder.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

    double THRESH = 0.000001;
    mat cov_seg_i = stat_seg.cov();

    //Following Mehrtash suggestions as per email dated June26th 2014
    cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t());
    vec D;
    mat V;
    eig_sym(D, V, cov_seg_i);
    uvec q1 = find(D < THRESH);

    if (q1.n_elem>0)
    {
      for (uword pos = 0; pos < q1.n_elem; ++pos)
      {
	D( q1(pos) ) = THRESH;

      }

      cov_seg_i = V*diagmat(D)*V.t();

    }
    //end suggestion

     eig_sym(D, V, cov_seg_i);
     mat log_M = V*diagmat( log(D) )*V.t();
     cov_seg_i.save( save_cov_seg.str(), hdf5_binary );
     log_M.save( save_LogMcov_seg.str(), hdf5_binary );
     s++;

    }

    else {
     //cout << " " << stat_seg.count();
     //getchar();

    }
  }

  std::stringstream save_seg;
  vec total_seg;
  total_seg.zeros(1);
  total_seg( 0 ) = s;
  save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
  total_seg.save( save_seg.str(), raw_ascii );
  cout << "Total # of segments " << s << endl;
  //cout << "press a key " ;
  //getchar();
}

<commit_msg>Changing code to make it easy tu run in parallel<commit_after>inline
cov_mat_kth::cov_mat_kth( const std::string in_path,
			  const std::string in_actionNames,
			  const int in_scale_factor,
			  const int in_shift,
			  const int in_scene, //only for kth
			  const int in_segment_length
)
:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), total_scenes(in_scene), segment_length(in_segment_length)
{
  actions.load( actionNames );
}

inline
void
cov_mat_kth::calculate( field<string> in_all_people, int  in_dim  )
{
  all_people = in_all_people;
  dim = in_dim;
  int n_actions = actions.n_rows;
  int n_peo =  all_people.n_rows;
  //all_people.print("people");

  field <std::string> parallel_names(n_peo*n_actions,4);
  int sc = total_scenes; //Solo estoy usando 1
  int k =0;

      for (int pe = 0; pe< n_peo; ++pe)
      {
	for (int act=0; act<n_actions; ++act)
	{

	std::stringstream load_folder;
	std::stringstream load_feat_video_i;
	std::stringstream load_labels_video_i;

	load_folder << path <<"./kth-features_dim" << dim <<  "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
	load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";
	load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

	parallel_names(k,0) = load_feat_video_i.str();
	parallel_names(k,1) = load_labels_video_i.str();
	parallel_names(k,2) = std::stoi(pe);
	parallel_names(k,3) = std::stoi(act);
	k++;

      }
    }

   //Aca podria hacer el paparelo

    for (int k = 0; k< parallel_names.n_rows; ++k)
    {

      std::string load_feat_video_i   = parallel_names(k,0);
      std::string load_labels_video_i = parallel_names(k,1);

      int pe   = atoi( parallel_names(k,2).c_str() );
      int act  = atoi( parallel_names(k,3).c_str() );

      cov_mat_kth::one_video(load_feat_video_i, load_labels_video_i, sc, pe, act );

    }

}

inline
void
cov_mat_kth::one_video( std::string load_feat_video_i,	std::string load_labels_video_i, int sc, int pe, int act )
{
  cout << load_feat_video_i << endl;
  mat mat_features_video_i;
  vec lab_video_i;

  mat_features_video_i.load( load_feat_video_i, hdf5_binary );
  lab_video_i.load( load_labels_video_i, hdf5_binary );
  int n_vec = lab_video_i.n_elem;
  int last = lab_video_i( n_vec - 1 );
  //cout << last << endl;

  int s = 0;

  std::stringstream save_folder;
  save_folder << "./kth-cov-mat_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;

  for (int l=2; l<last-segment_length; l = l+4 )
  {
    running_stat_vec<rowvec> stat_seg(true);
    //int k =0;

    //cout << " " << l;

    for (int j=l; j< l + segment_length; ++j)
    {
      //k++;
      //cout << " " << j;
      uvec indices = find(lab_video_i == j);
      mat tmp_feat = mat_features_video_i.cols(indices);
      //cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl;
      for (int v=0; v < tmp_feat.n_cols; ++v)
      {
	vec sample = tmp_feat.col(v);
	stat_seg (sample);

      }

    }

    //cout << endl;
    //cout << " " << stat_seg.count();

    if (stat_seg.count()>100) // Cuando en el segmento hay mas de 100 vectores
    {
    std::stringstream save_cov_seg;
    save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

    std::stringstream save_LogMcov_seg;
    save_LogMcov_seg << save_folder.str() << "/LogMcov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".h5";

    double THRESH = 0.000001;
    mat cov_seg_i = stat_seg.cov();

    //Following Mehrtash suggestions as per email dated June26th 2014
    cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t());
    vec D;
    mat V;
    eig_sym(D, V, cov_seg_i);
    uvec q1 = find(D < THRESH);

    if (q1.n_elem>0)
    {
      for (uword pos = 0; pos < q1.n_elem; ++pos)
      {
	D( q1(pos) ) = THRESH;

      }

      cov_seg_i = V*diagmat(D)*V.t();

    }
    //end suggestion

     eig_sym(D, V, cov_seg_i);
     mat log_M = V*diagmat( log(D) )*V.t();
     cov_seg_i.save( save_cov_seg.str(), hdf5_binary );
     log_M.save( save_LogMcov_seg.str(), hdf5_binary );
     s++;

    }

    else {
     //cout << " " << stat_seg.count();
     //getchar();

    }
  }

  std::stringstream save_seg;
  vec total_seg;
  total_seg.zeros(1);
  total_seg( 0 ) = s;
  save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim  << ".dat";
  total_seg.save( save_seg.str(), raw_ascii );
  cout << "Total # of segments " << s << endl;
  //cout << "press a key " ;
  //getchar();
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qmakeprojectimporter.h"

#include "qmakebuildinfo.h"
#include "qmakekitinformation.h"
#include "qmakebuildconfiguration.h"
#include "qmakeproject.h"

#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/target.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
#include <qtsupport/qtversionfactory.h>
#include <qtsupport/qtversionmanager.h>
#include <utils/qtcprocess.h>

#include <QDir>
#include <QFileInfo>
#include <QStringList>

#include <QMessageBox>

static const Core::Id QT_IS_TEMPORARY("Qmake.TempQt");

namespace QmakeProjectManager {
namespace Internal {

QmakeProjectImporter::QmakeProjectImporter(const QString &path) :
    ProjectExplorer::ProjectImporter(path)
{ }

QList<ProjectExplorer::BuildInfo *> QmakeProjectImporter::import(const Utils::FileName &importPath,
                                                                 bool silent)
{
    QList<ProjectExplorer::BuildInfo *> result;
    QFileInfo fi = importPath.toFileInfo();
    if (!fi.exists() && !fi.isDir())
        return result;

    QStringList makefiles = QDir(importPath.toString()).entryList(QStringList(QLatin1String("Makefile*")));

    QtSupport::BaseQtVersion *version = 0;
    bool temporaryVersion = false;

    foreach (const QString &file, makefiles) {
        // find interesting makefiles
        QString makefile = importPath.toString() + QLatin1Char('/') + file;
        Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile);
        QFileInfo qmakeFi = qmakeBinary.toFileInfo();
        Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(qmakeFi.canonicalFilePath());
        if (canonicalQmakeBinary.isEmpty())
            continue;
        if (QtSupport::QtVersionManager::makefileIsFor(makefile, projectFilePath()) != QtSupport::QtVersionManager::SameProject)
            continue;

        // Find version:
        foreach (QtSupport::BaseQtVersion *v, QtSupport::QtVersionManager::versions()) {
            QFileInfo vfi = v->qmakeCommand().toFileInfo();
            Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath());
            if (current == canonicalQmakeBinary) {
                version = v;
                break;
            }
        }

        // Create a new version if not found:
        if (!version) {
            // Do not use the canonical path here...
            version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary);
            if (!version)
                continue;

            setIsUpdating(true);
            QtSupport::QtVersionManager::addVersion(version);
            setIsUpdating(false);
            temporaryVersion = true;
        }

        // find qmake arguments and mkspec
        QPair<QtSupport::BaseQtVersion::QmakeBuildConfigs, QString> makefileBuildConfig =
                QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());

        QString additionalArguments = makefileBuildConfig.second;
        Utils::FileName parsedSpec =
                QmakeBuildConfiguration::extractSpecFromArguments(&additionalArguments, importPath.toString(), version);
        Utils::FileName versionSpec = version->mkspec();
        if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromLatin1("default"))
            parsedSpec = versionSpec;

        QString specArgument;
        // Compare mkspecs and add to additional arguments
        if (parsedSpec != versionSpec)
            specArgument = QLatin1String("-spec ") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput());
        Utils::QtcProcess::addArgs(&specArgument, additionalArguments);

        // Find kits (can be more than one, e.g. (Linux-)Desktop and embedded linux):
        QList<ProjectExplorer::Kit *> kitList;
        foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) {
            QtSupport::BaseQtVersion *kitVersion = QtSupport::QtKitInformation::qtVersion(k);
            Utils::FileName kitSpec = QmakeKitInformation::mkspec(k);
            ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
            if (kitSpec.isEmpty() && kitVersion)
                kitSpec = kitVersion->mkspecFor(tc);

            if (kitVersion == version
                    && kitSpec == parsedSpec)
                kitList.append(k);
        }
        if (kitList.isEmpty())
            kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec));

        foreach (ProjectExplorer::Kit *k, kitList) {
            addProject(k);

            QmakeBuildConfigurationFactory *factory
                    = qobject_cast<QmakeBuildConfigurationFactory *>(
                        ProjectExplorer::IBuildConfigurationFactory::find(k, projectFilePath()));

            if (!factory)
                continue;

            // create info:
            QmakeBuildInfo *info = new QmakeBuildInfo(factory);
            if (makefileBuildConfig.first & QtSupport::BaseQtVersion::DebugBuild) {
                info->type = ProjectExplorer::BuildConfiguration::Debug;
                info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Debug");
            } else {
                info->type = ProjectExplorer::BuildConfiguration::Release;
                info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Release");
            }
            info->kitId = k->id();
            info->buildDirectory = Utils::FileName::fromString(fi.absoluteFilePath());
            info->additionalArguments = additionalArguments;
            info->makefile = makefile;

            bool found = false;
            foreach (ProjectExplorer::BuildInfo *bInfo, result) {
                if (*static_cast<QmakeBuildInfo *>(bInfo) == *info) {
                    found = true;
                    break;
                }
            }
            if (found)
                delete info;
            else
                result << info;
        }
    }

    if (result.isEmpty() && !silent)
        QMessageBox::critical(Core::ICore::mainWindow(),
                              QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No Build Found"),
                              QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No build found in %1 matching project %2.")
                .arg(importPath.toUserOutput()).arg(projectFilePath()));

    return result;
}

QStringList QmakeProjectImporter::importCandidates(const Utils::FileName &projectPath)
{
    QStringList candidates;

    QFileInfo pfi = projectPath.toFileInfo();
    const QString prefix = pfi.baseName();
    candidates << pfi.absolutePath();

    QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::kits();
    foreach (ProjectExplorer::Kit *k, kitList) {
        QFileInfo fi(QmakeProject::shadowBuildDirectory(projectPath.toString(), k, QString()));
        const QString baseDir = fi.absolutePath();

        foreach (const QString &dir, QDir(baseDir).entryList()) {
            const QString path = baseDir + QLatin1Char('/') + dir;
            if (dir.startsWith(prefix) && !candidates.contains(path))
                candidates << path;
        }
    }
    return candidates;
}

ProjectExplorer::Target *QmakeProjectImporter::preferredTarget(const QList<ProjectExplorer::Target *> &possibleTargets)
{
    // Select active target
    // a) The default target
    // b) Simulator target
    // c) Desktop target
    // d) the first target
    ProjectExplorer::Target *activeTarget = possibleTargets.isEmpty() ? 0 : possibleTargets.at(0);
    int activeTargetPriority = 0;
    foreach (ProjectExplorer::Target *t, possibleTargets) {
        QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit());
        if (t->kit() == ProjectExplorer::KitManager::defaultKit()) {
            activeTarget = t;
            activeTargetPriority = 3;
        } else if (activeTargetPriority < 2 && version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)) {
            activeTarget = t;
            activeTargetPriority = 2;
        } else if (activeTargetPriority < 1 && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)) {
            activeTarget = t;
            activeTargetPriority = 1;
        }
    }
    return activeTarget;
}

void QmakeProjectImporter::cleanupKit(ProjectExplorer::Kit *k)
{
    QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::version(k->value(QT_IS_TEMPORARY, -1).toInt());
    if (version)
        QtSupport::QtVersionManager::removeVersion(version);
}

ProjectExplorer::Kit *QmakeProjectImporter::createTemporaryKit(QtSupport::BaseQtVersion *version,
                                                               bool temporaryVersion,
                                                               const Utils::FileName &parsedSpec)
{
    ProjectExplorer::Kit *k = new ProjectExplorer::Kit;
    QtSupport::QtKitInformation::setQtVersion(k, version);
    ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec));
    QmakeKitInformation::setMkspec(k, parsedSpec);

    markTemporary(k);
    if (temporaryVersion)
        k->setValue(QT_IS_TEMPORARY, version->uniqueId());

    k->setDisplayName(version->displayName());
    setIsUpdating(true);
    ProjectExplorer::KitManager::registerKit(k);
    setIsUpdating(false);
    return k;
}

} // namespace Internal
} // namespace QmakeProjectManager
<commit_msg>qmakeprojectmanager: Native separators in import() error message<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qmakeprojectimporter.h"

#include "qmakebuildinfo.h"
#include "qmakekitinformation.h"
#include "qmakebuildconfiguration.h"
#include "qmakeproject.h"

#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/target.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
#include <qtsupport/qtversionfactory.h>
#include <qtsupport/qtversionmanager.h>
#include <utils/qtcprocess.h>

#include <QDir>
#include <QFileInfo>
#include <QStringList>

#include <QMessageBox>

static const Core::Id QT_IS_TEMPORARY("Qmake.TempQt");

namespace QmakeProjectManager {
namespace Internal {

QmakeProjectImporter::QmakeProjectImporter(const QString &path) :
    ProjectExplorer::ProjectImporter(path)
{ }

QList<ProjectExplorer::BuildInfo *> QmakeProjectImporter::import(const Utils::FileName &importPath,
                                                                 bool silent)
{
    QList<ProjectExplorer::BuildInfo *> result;
    QFileInfo fi = importPath.toFileInfo();
    if (!fi.exists() && !fi.isDir())
        return result;

    QStringList makefiles = QDir(importPath.toString()).entryList(QStringList(QLatin1String("Makefile*")));

    QtSupport::BaseQtVersion *version = 0;
    bool temporaryVersion = false;

    foreach (const QString &file, makefiles) {
        // find interesting makefiles
        QString makefile = importPath.toString() + QLatin1Char('/') + file;
        Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile);
        QFileInfo qmakeFi = qmakeBinary.toFileInfo();
        Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(qmakeFi.canonicalFilePath());
        if (canonicalQmakeBinary.isEmpty())
            continue;
        if (QtSupport::QtVersionManager::makefileIsFor(makefile, projectFilePath()) != QtSupport::QtVersionManager::SameProject)
            continue;

        // Find version:
        foreach (QtSupport::BaseQtVersion *v, QtSupport::QtVersionManager::versions()) {
            QFileInfo vfi = v->qmakeCommand().toFileInfo();
            Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath());
            if (current == canonicalQmakeBinary) {
                version = v;
                break;
            }
        }

        // Create a new version if not found:
        if (!version) {
            // Do not use the canonical path here...
            version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary);
            if (!version)
                continue;

            setIsUpdating(true);
            QtSupport::QtVersionManager::addVersion(version);
            setIsUpdating(false);
            temporaryVersion = true;
        }

        // find qmake arguments and mkspec
        QPair<QtSupport::BaseQtVersion::QmakeBuildConfigs, QString> makefileBuildConfig =
                QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());

        QString additionalArguments = makefileBuildConfig.second;
        Utils::FileName parsedSpec =
                QmakeBuildConfiguration::extractSpecFromArguments(&additionalArguments, importPath.toString(), version);
        Utils::FileName versionSpec = version->mkspec();
        if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromLatin1("default"))
            parsedSpec = versionSpec;

        QString specArgument;
        // Compare mkspecs and add to additional arguments
        if (parsedSpec != versionSpec)
            specArgument = QLatin1String("-spec ") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput());
        Utils::QtcProcess::addArgs(&specArgument, additionalArguments);

        // Find kits (can be more than one, e.g. (Linux-)Desktop and embedded linux):
        QList<ProjectExplorer::Kit *> kitList;
        foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) {
            QtSupport::BaseQtVersion *kitVersion = QtSupport::QtKitInformation::qtVersion(k);
            Utils::FileName kitSpec = QmakeKitInformation::mkspec(k);
            ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
            if (kitSpec.isEmpty() && kitVersion)
                kitSpec = kitVersion->mkspecFor(tc);

            if (kitVersion == version
                    && kitSpec == parsedSpec)
                kitList.append(k);
        }
        if (kitList.isEmpty())
            kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec));

        foreach (ProjectExplorer::Kit *k, kitList) {
            addProject(k);

            QmakeBuildConfigurationFactory *factory
                    = qobject_cast<QmakeBuildConfigurationFactory *>(
                        ProjectExplorer::IBuildConfigurationFactory::find(k, projectFilePath()));

            if (!factory)
                continue;

            // create info:
            QmakeBuildInfo *info = new QmakeBuildInfo(factory);
            if (makefileBuildConfig.first & QtSupport::BaseQtVersion::DebugBuild) {
                info->type = ProjectExplorer::BuildConfiguration::Debug;
                info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Debug");
            } else {
                info->type = ProjectExplorer::BuildConfiguration::Release;
                info->displayName = QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "Release");
            }
            info->kitId = k->id();
            info->buildDirectory = Utils::FileName::fromString(fi.absoluteFilePath());
            info->additionalArguments = additionalArguments;
            info->makefile = makefile;

            bool found = false;
            foreach (ProjectExplorer::BuildInfo *bInfo, result) {
                if (*static_cast<QmakeBuildInfo *>(bInfo) == *info) {
                    found = true;
                    break;
                }
            }
            if (found)
                delete info;
            else
                result << info;
        }
    }

    if (result.isEmpty() && !silent)
        QMessageBox::critical(Core::ICore::mainWindow(),
                              QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No Build Found"),
                              QCoreApplication::translate("QmakeProjectManager::Internal::QmakeProjectImporter", "No build found in %1 matching project %2.")
                .arg(importPath.toUserOutput()).arg(QDir::toNativeSeparators(projectFilePath())));

    return result;
}

QStringList QmakeProjectImporter::importCandidates(const Utils::FileName &projectPath)
{
    QStringList candidates;

    QFileInfo pfi = projectPath.toFileInfo();
    const QString prefix = pfi.baseName();
    candidates << pfi.absolutePath();

    QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::kits();
    foreach (ProjectExplorer::Kit *k, kitList) {
        QFileInfo fi(QmakeProject::shadowBuildDirectory(projectPath.toString(), k, QString()));
        const QString baseDir = fi.absolutePath();

        foreach (const QString &dir, QDir(baseDir).entryList()) {
            const QString path = baseDir + QLatin1Char('/') + dir;
            if (dir.startsWith(prefix) && !candidates.contains(path))
                candidates << path;
        }
    }
    return candidates;
}

ProjectExplorer::Target *QmakeProjectImporter::preferredTarget(const QList<ProjectExplorer::Target *> &possibleTargets)
{
    // Select active target
    // a) The default target
    // b) Simulator target
    // c) Desktop target
    // d) the first target
    ProjectExplorer::Target *activeTarget = possibleTargets.isEmpty() ? 0 : possibleTargets.at(0);
    int activeTargetPriority = 0;
    foreach (ProjectExplorer::Target *t, possibleTargets) {
        QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit());
        if (t->kit() == ProjectExplorer::KitManager::defaultKit()) {
            activeTarget = t;
            activeTargetPriority = 3;
        } else if (activeTargetPriority < 2 && version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)) {
            activeTarget = t;
            activeTargetPriority = 2;
        } else if (activeTargetPriority < 1 && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)) {
            activeTarget = t;
            activeTargetPriority = 1;
        }
    }
    return activeTarget;
}

void QmakeProjectImporter::cleanupKit(ProjectExplorer::Kit *k)
{
    QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::version(k->value(QT_IS_TEMPORARY, -1).toInt());
    if (version)
        QtSupport::QtVersionManager::removeVersion(version);
}

ProjectExplorer::Kit *QmakeProjectImporter::createTemporaryKit(QtSupport::BaseQtVersion *version,
                                                               bool temporaryVersion,
                                                               const Utils::FileName &parsedSpec)
{
    ProjectExplorer::Kit *k = new ProjectExplorer::Kit;
    QtSupport::QtKitInformation::setQtVersion(k, version);
    ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec));
    QmakeKitInformation::setMkspec(k, parsedSpec);

    markTemporary(k);
    if (temporaryVersion)
        k->setValue(QT_IS_TEMPORARY, version->uniqueId());

    k->setDisplayName(version->displayName());
    setIsUpdating(true);
    ProjectExplorer::KitManager::registerKit(k);
    setIsUpdating(false);
    return k;
}

} // namespace Internal
} // namespace QmakeProjectManager
<|endoftext|>