<commit_before>#include "SDBPRequestMessage.h"

bool SDBPRequestMessage::Read(ReadBuffer& buffer)
{
    int         read;
    unsigned    i, numNodes;
    uint64_t    nodeID;
    ReadBuffer  optional;

    if (buffer.GetLength() < 1)
        return false;

    switch (buffer.GetCharAt(0))
    {
        /* Master query */
        case CLIENTREQUEST_GET_MASTER:
            read = buffer.Readf("%c:%U",
             &request->type, &request->commandID);
            break;

        /* Get config state: databases, tables, shards, quora */
        case CLIENTREQUEST_GET_CONFIG_STATE:
            read = buffer.Readf("%c:%U",
             &request->type, &request->commandID);
            break;

        /* Quorum management */
        case CLIENTREQUEST_CREATE_QUORUM:
            read = buffer.Readf("%c:%U:%u",
             &request->type, &request->commandID, &numNodes);
            if (read < 0 || read == (signed)buffer.GetLength())
                return false;
            buffer.Advance(read);
            for (i = 0; i < numNodes; i++)
            {
                read = buffer.Readf(":%U", &nodeID);
                if (read < 0)
                    return false;
                buffer.Advance(read);
                request->nodes.Append(nodeID);
            }
            if (buffer.GetLength() == 0)
                return true;
            else
                return false;
            break;
        case CLIENTREQUEST_DELETE_QUORUM:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID, &request->quorumID);
            break;
        case CLIENTREQUEST_ADD_NODE:
            read = buffer.Readf("%c:%U:%U:%U",
             &request->type, &request->commandID, &request->quorumID, &request->nodeID);
            break;
        case CLIENTREQUEST_REMOVE_NODE:
            read = buffer.Readf("%c:%U:%U:%U",
             &request->type, &request->commandID, &request->quorumID, &request->nodeID);
            break;
        case CLIENTREQUEST_ACTIVATE_NODE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID, &request->nodeID);
            break;

        /* Database management */
        case CLIENTREQUEST_CREATE_DATABASE:
            read = buffer.Readf("%c:%U:%#B",
             &request->type, &request->commandID, &request->name);
            break;
        case CLIENTREQUEST_RENAME_DATABASE:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID, &request->databaseID,
             &request->name);
            break;
        case CLIENTREQUEST_DELETE_DATABASE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID, &request->databaseID);
            break;
        case CLIENTREQUEST_SPLIT_SHARD:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->shardID, &request->key);
            break;
        case CLIENTREQUEST_MIGRATE_SHARD:
            read = buffer.Readf("%c:%U:%U:%U",
             &request->type, &request->commandID, &request->shardID, &request->quorumID);
            return true;

        /* Table management */
        case CLIENTREQUEST_CREATE_TABLE:
            read = buffer.Readf("%c:%U:%U:%U:%#B",
             &request->type, &request->commandID, &request->databaseID,
             &request->quorumID, &request->name);
            break;
        case CLIENTREQUEST_RENAME_TABLE:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->name);
            break;
        case CLIENTREQUEST_DELETE_TABLE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID,
             &request->tableID);
            break;
        case CLIENTREQUEST_TRUNCATE_TABLE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID,
             &request->tableID);
            break;

        /* Data operations */
        case CLIENTREQUEST_GET:
            read = buffer.Readf("%c:%U:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->paxosID,
             &request->key);
            break;
        case CLIENTREQUEST_SET:
        case CLIENTREQUEST_SET_IF_NOT_EXISTS:
        case CLIENTREQUEST_GET_AND_SET:
            read = buffer.Readf("%c:%U:%U:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->value);
            break;
        case CLIENTREQUEST_TEST_AND_SET:
            read = buffer.Readf("%c:%U:%U:%#B:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->test, &request->value);
            break;
        case CLIENTREQUEST_TEST_AND_DELETE:
            read = buffer.Readf("%c:%U:%U:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->test);
            break;
        case CLIENTREQUEST_ADD:
            read = buffer.Readf("%c:%U:%U:%#B:%I",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->number);
            break;
        case CLIENTREQUEST_APPEND:
            read = buffer.Readf("%c:%U:%U:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->value);
            break;
        case CLIENTREQUEST_DELETE:
        case CLIENTREQUEST_REMOVE:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key);
            break;

        case CLIENTREQUEST_LIST_KEYS:
        case CLIENTREQUEST_LIST_KEYVALUES:
        case CLIENTREQUEST_COUNT:
            read = buffer.Readf("%c:%U:%U:%#B:%#B:%#B:%U:%U",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->endKey, &request->prefix,
             &request->count, &request->offset);
            break;

        case CLIENTREQUEST_SUBMIT:
            read = buffer.Readf("%c:%U",
             &request->type, &request->quorumID);
            break;

        case CLIENTREQUEST_BULK_LOADING:
            read = buffer.Readf("%c:%U",
             &request->type, &request->commandID);
            break;

        default:
            return false;
    }

    return (read == (signed)buffer.GetLength() ? true : false);
}

bool SDBPRequestMessage::Write(Buffer& buffer)
{
    uint64_t*   it;

    switch (request->type)
    {
        /* Master query */
        case CLIENTREQUEST_GET_MASTER:
            buffer.Appendf("%c:%U",
             request->type, request->commandID);
            return true;

        /* Get config state: databases, tables, shards, quora */
        case CLIENTREQUEST_GET_CONFIG_STATE:
            buffer.Appendf("%c:%U",
             request->type, request->commandID);
            return true;

        /* Quorum management */
        case CLIENTREQUEST_CREATE_QUORUM:
            buffer.Appendf("%c:%U:%u",
             request->type, request->commandID, request->nodes.GetLength());
            for (it = request->nodes.First(); it != NULL; it = request->nodes.Next(it))
                buffer.Appendf(":%U", *it);
            return true;
        case CLIENTREQUEST_DELETE_QUORUM:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID, request->quorumID);
            return true;
        case CLIENTREQUEST_ADD_NODE:
            buffer.Appendf("%c:%U:%U:%U",
             request->type, request->commandID, request->quorumID, request->nodeID);
            return true;
        case CLIENTREQUEST_REMOVE_NODE:
            buffer.Appendf("%c:%U:%U:%U",
             request->type, request->commandID, request->quorumID, request->nodeID);
            return true;
        case CLIENTREQUEST_ACTIVATE_NODE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID, request->nodeID);
            return true;

        /* Database management */
        case CLIENTREQUEST_CREATE_DATABASE:
            buffer.Appendf("%c:%U:%#B",
             request->type, request->commandID, &request->name);
            return true;
        case CLIENTREQUEST_RENAME_DATABASE:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID, request->databaseID,
             &request->name);
            return true;
        case CLIENTREQUEST_DELETE_DATABASE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID, request->databaseID);
            return true;
        case CLIENTREQUEST_SPLIT_SHARD:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID, request->shardID, &request->key);
            return true;
        case CLIENTREQUEST_MIGRATE_SHARD:
            buffer.Appendf("%c:%U:%U:%U",
             request->type, request->commandID, request->shardID, request->quorumID);
            return true;

        /* Table management */
        case CLIENTREQUEST_CREATE_TABLE:
            buffer.Appendf("%c:%U:%U:%U:%#B",
             request->type, request->commandID, request->databaseID,
             request->quorumID, &request->name);
            return true;
        case CLIENTREQUEST_RENAME_TABLE:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID,
             request->tableID, &request->name);
            return true;
        case CLIENTREQUEST_DELETE_TABLE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID,
             request->tableID);
            return true;
        case CLIENTREQUEST_TRUNCATE_TABLE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID,
             request->tableID);
            return true;

        /* Data operations */
        case CLIENTREQUEST_GET:
            buffer.Appendf("%c:%U:%U:%U:%#B",
             request->type, request->commandID,
             request->tableID, request->paxosID,
             &request->key);
            return true;
        case CLIENTREQUEST_SET:
        case CLIENTREQUEST_SET_IF_NOT_EXISTS:
        case CLIENTREQUEST_GET_AND_SET:
            buffer.Appendf("%c:%U:%U:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->value);
            return true;
        case CLIENTREQUEST_TEST_AND_SET:
            buffer.Appendf("%c:%U:%U:%#B:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->test, &request->value);
            return true;
        case CLIENTREQUEST_ADD:
            buffer.Appendf("%c:%U:%U:%#B:%I",
             request->type, request->commandID,
             request->tableID, &request->key, request->number);
            return true;
        case CLIENTREQUEST_APPEND:
            buffer.Appendf("%c:%U:%U:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->value);
            return true;
        case CLIENTREQUEST_DELETE:
        case CLIENTREQUEST_REMOVE:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID,
             request->tableID, &request->key);
            return true;

        case CLIENTREQUEST_TEST_AND_DELETE:
            buffer.Appendf("%c:%U:%U:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->test);
            return true;

        case CLIENTREQUEST_LIST_KEYS:
        case CLIENTREQUEST_LIST_KEYVALUES:
        case CLIENTREQUEST_COUNT:
            buffer.Appendf("%c:%U:%U:%#B:%#B:%#B:%U:%U",
             request->type, request->commandID,
             request->tableID, &request->key, &request->endKey, &request->prefix,
             request->count, request->offset);
            return true;

        case CLIENTREQUEST_SUBMIT:
            buffer.Appendf("%c:%U", request->type, request->quorumID);
            return true;

        case CLIENTREQUEST_BULK_LOADING:
            buffer.Appendf("%c:%U", request->type, request->commandID);
            return true;

        default:
            return false;
    }
}
<commit_msg>Fixed freeze/unfreeze from client library.<commit_after>#include "SDBPRequestMessage.h"

bool SDBPRequestMessage::Read(ReadBuffer& buffer)
{
    int         read;
    unsigned    i, numNodes;
    uint64_t    nodeID;
    ReadBuffer  optional;

    if (buffer.GetLength() < 1)
        return false;

    switch (buffer.GetCharAt(0))
    {
        /* Master query */
        case CLIENTREQUEST_GET_MASTER:
            read = buffer.Readf("%c:%U",
             &request->type, &request->commandID);
            break;

        /* Get config state: databases, tables, shards, quora */
        case CLIENTREQUEST_GET_CONFIG_STATE:
            read = buffer.Readf("%c:%U",
             &request->type, &request->commandID);
            break;

        /* Quorum management */
        case CLIENTREQUEST_CREATE_QUORUM:
            read = buffer.Readf("%c:%U:%u",
             &request->type, &request->commandID, &numNodes);
            if (read < 0 || read == (signed)buffer.GetLength())
                return false;
            buffer.Advance(read);
            for (i = 0; i < numNodes; i++)
            {
                read = buffer.Readf(":%U", &nodeID);
                if (read < 0)
                    return false;
                buffer.Advance(read);
                request->nodes.Append(nodeID);
            }
            if (buffer.GetLength() == 0)
                return true;
            else
                return false;
            break;
        case CLIENTREQUEST_DELETE_QUORUM:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID, &request->quorumID);
            break;
        case CLIENTREQUEST_ADD_NODE:
            read = buffer.Readf("%c:%U:%U:%U",
             &request->type, &request->commandID, &request->quorumID, &request->nodeID);
            break;
        case CLIENTREQUEST_REMOVE_NODE:
            read = buffer.Readf("%c:%U:%U:%U",
             &request->type, &request->commandID, &request->quorumID, &request->nodeID);
            break;
        case CLIENTREQUEST_ACTIVATE_NODE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID, &request->nodeID);
            break;

        /* Database management */
        case CLIENTREQUEST_CREATE_DATABASE:
            read = buffer.Readf("%c:%U:%#B",
             &request->type, &request->commandID, &request->name);
            break;
        case CLIENTREQUEST_RENAME_DATABASE:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID, &request->databaseID,
             &request->name);
            break;
        case CLIENTREQUEST_DELETE_DATABASE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID, &request->databaseID);
            break;
        case CLIENTREQUEST_SPLIT_SHARD:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->shardID, &request->key);
            break;
        case CLIENTREQUEST_MIGRATE_SHARD:
            read = buffer.Readf("%c:%U:%U:%U",
             &request->type, &request->commandID, &request->shardID, &request->quorumID);
            return true;

        /* Table management */
        case CLIENTREQUEST_CREATE_TABLE:
            read = buffer.Readf("%c:%U:%U:%U:%#B",
             &request->type, &request->commandID, &request->databaseID,
             &request->quorumID, &request->name);
            break;
        case CLIENTREQUEST_RENAME_TABLE:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->name);
            break;
        case CLIENTREQUEST_DELETE_TABLE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID,
             &request->tableID);
            break;
        case CLIENTREQUEST_TRUNCATE_TABLE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID,
             &request->tableID);
            break;
        case CLIENTREQUEST_FREEZE_TABLE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID,
             &request->tableID);
            break;
        case CLIENTREQUEST_UNFREEZE_TABLE:
            read = buffer.Readf("%c:%U:%U",
             &request->type, &request->commandID,
             &request->tableID);
            break;

        /* Data operations */
        case CLIENTREQUEST_GET:
            read = buffer.Readf("%c:%U:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->paxosID,
             &request->key);
            break;
        case CLIENTREQUEST_SET:
        case CLIENTREQUEST_SET_IF_NOT_EXISTS:
        case CLIENTREQUEST_GET_AND_SET:
            read = buffer.Readf("%c:%U:%U:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->value);
            break;
        case CLIENTREQUEST_TEST_AND_SET:
            read = buffer.Readf("%c:%U:%U:%#B:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->test, &request->value);
            break;
        case CLIENTREQUEST_TEST_AND_DELETE:
            read = buffer.Readf("%c:%U:%U:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->test);
            break;
        case CLIENTREQUEST_ADD:
            read = buffer.Readf("%c:%U:%U:%#B:%I",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->number);
            break;
        case CLIENTREQUEST_APPEND:
            read = buffer.Readf("%c:%U:%U:%#B:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->value);
            break;
        case CLIENTREQUEST_DELETE:
        case CLIENTREQUEST_REMOVE:
            read = buffer.Readf("%c:%U:%U:%#B",
             &request->type, &request->commandID,
             &request->tableID, &request->key);
            break;

        case CLIENTREQUEST_LIST_KEYS:
        case CLIENTREQUEST_LIST_KEYVALUES:
        case CLIENTREQUEST_COUNT:
            read = buffer.Readf("%c:%U:%U:%#B:%#B:%#B:%U:%U",
             &request->type, &request->commandID,
             &request->tableID, &request->key, &request->endKey, &request->prefix,
             &request->count, &request->offset);
            break;

        case CLIENTREQUEST_SUBMIT:
            read = buffer.Readf("%c:%U",
             &request->type, &request->quorumID);
            break;

        case CLIENTREQUEST_BULK_LOADING:
            read = buffer.Readf("%c:%U",
             &request->type, &request->commandID);
            break;

        default:
            return false;
    }

    return (read == (signed)buffer.GetLength() ? true : false);
}

bool SDBPRequestMessage::Write(Buffer& buffer)
{
    uint64_t*   it;

    switch (request->type)
    {
        /* Master query */
        case CLIENTREQUEST_GET_MASTER:
            buffer.Appendf("%c:%U",
             request->type, request->commandID);
            return true;

        /* Get config state: databases, tables, shards, quora */
        case CLIENTREQUEST_GET_CONFIG_STATE:
            buffer.Appendf("%c:%U",
             request->type, request->commandID);
            return true;

        /* Quorum management */
        case CLIENTREQUEST_CREATE_QUORUM:
            buffer.Appendf("%c:%U:%u",
             request->type, request->commandID, request->nodes.GetLength());
            for (it = request->nodes.First(); it != NULL; it = request->nodes.Next(it))
                buffer.Appendf(":%U", *it);
            return true;
        case CLIENTREQUEST_DELETE_QUORUM:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID, request->quorumID);
            return true;
        case CLIENTREQUEST_ADD_NODE:
            buffer.Appendf("%c:%U:%U:%U",
             request->type, request->commandID, request->quorumID, request->nodeID);
            return true;
        case CLIENTREQUEST_REMOVE_NODE:
            buffer.Appendf("%c:%U:%U:%U",
             request->type, request->commandID, request->quorumID, request->nodeID);
            return true;
        case CLIENTREQUEST_ACTIVATE_NODE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID, request->nodeID);
            return true;

        /* Database management */
        case CLIENTREQUEST_CREATE_DATABASE:
            buffer.Appendf("%c:%U:%#B",
             request->type, request->commandID, &request->name);
            return true;
        case CLIENTREQUEST_RENAME_DATABASE:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID, request->databaseID,
             &request->name);
            return true;
        case CLIENTREQUEST_DELETE_DATABASE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID, request->databaseID);
            return true;
        case CLIENTREQUEST_SPLIT_SHARD:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID, request->shardID, &request->key);
            return true;
        case CLIENTREQUEST_MIGRATE_SHARD:
            buffer.Appendf("%c:%U:%U:%U",
             request->type, request->commandID, request->shardID, request->quorumID);
            return true;

        /* Table management */
        case CLIENTREQUEST_CREATE_TABLE:
            buffer.Appendf("%c:%U:%U:%U:%#B",
             request->type, request->commandID, request->databaseID,
             request->quorumID, &request->name);
            return true;
        case CLIENTREQUEST_RENAME_TABLE:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID,
             request->tableID, &request->name);
            return true;
        case CLIENTREQUEST_DELETE_TABLE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID,
             request->tableID);
            return true;
        case CLIENTREQUEST_TRUNCATE_TABLE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID,
             request->tableID);
            return true;
        case CLIENTREQUEST_FREEZE_TABLE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID,
             request->tableID);
            return true;
        case CLIENTREQUEST_UNFREEZE_TABLE:
            buffer.Appendf("%c:%U:%U",
             request->type, request->commandID,
             request->tableID);
            return true;

        /* Data operations */
        case CLIENTREQUEST_GET:
            buffer.Appendf("%c:%U:%U:%U:%#B",
             request->type, request->commandID,
             request->tableID, request->paxosID,
             &request->key);
            return true;
        case CLIENTREQUEST_SET:
        case CLIENTREQUEST_SET_IF_NOT_EXISTS:
        case CLIENTREQUEST_GET_AND_SET:
            buffer.Appendf("%c:%U:%U:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->value);
            return true;
        case CLIENTREQUEST_TEST_AND_SET:
            buffer.Appendf("%c:%U:%U:%#B:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->test, &request->value);
            return true;
        case CLIENTREQUEST_ADD:
            buffer.Appendf("%c:%U:%U:%#B:%I",
             request->type, request->commandID,
             request->tableID, &request->key, request->number);
            return true;
        case CLIENTREQUEST_APPEND:
            buffer.Appendf("%c:%U:%U:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->value);
            return true;
        case CLIENTREQUEST_DELETE:
        case CLIENTREQUEST_REMOVE:
            buffer.Appendf("%c:%U:%U:%#B",
             request->type, request->commandID,
             request->tableID, &request->key);
            return true;

        case CLIENTREQUEST_TEST_AND_DELETE:
            buffer.Appendf("%c:%U:%U:%#B:%#B",
             request->type, request->commandID,
             request->tableID, &request->key, &request->test);
            return true;

        case CLIENTREQUEST_LIST_KEYS:
        case CLIENTREQUEST_LIST_KEYVALUES:
        case CLIENTREQUEST_COUNT:
            buffer.Appendf("%c:%U:%U:%#B:%#B:%#B:%U:%U",
             request->type, request->commandID,
             request->tableID, &request->key, &request->endKey, &request->prefix,
             request->count, request->offset);
            return true;

        case CLIENTREQUEST_SUBMIT:
            buffer.Appendf("%c:%U", request->type, request->quorumID);
            return true;

        case CLIENTREQUEST_BULK_LOADING:
            buffer.Appendf("%c:%U", request->type, request->commandID);
            return true;

        default:
            return false;
    }
}
<|endoftext|>


<commit_before>// motor_test.cpp

#include<cstdio>
#include"motor_softpwm.hpp"

int main()
{
	MotorSoftPwm test1(1,70,70,10);
	test1.motorMove();
    test1.setpwm(2,70,70,10);
    test1.motorMove();
    test1.setpwm(0,70,70,10);
	test1.motorMove();
	test1.setpwm(3,70,70,10);
	test1.motorMove();
	test1.setpwm(4,70,70,10);
	test1.motorMove();
	return 0;
}

	<commit_msg>indent<commit_after>// motor_test.cpp

#include<cstdio>
#include"motor_softpwm.hpp"

int main()
{
	MotorSoftPwm test1(1,70,70,10);

	test1.motorMove();
    test1.setpwm(2,70,70,10);
    test1.motorMove();
    test1.setpwm(0,70,70,10);
	test1.motorMove();
	test1.setpwm(3,70,70,10);
	test1.motorMove();
	test1.setpwm(4,70,70,10);
	test1.motorMove();
	return 0;
}
<|endoftext|>


<commit_before>#ifndef INCLUDED_TOBY_VARIANT_H
#define INCLUDED_TOBY_VARIANT_H

#include <cstddef>
#include <stdexcept>

#include <spdlog/spdlog.h>

namespace toby {
namespace detail {
inline auto logger() { return spdlog::get("variant"); }

template <typename I, I N, typename... Ts>
struct variant_construct;

template <typename I, I N>
struct variant_construct<I, N> {
  static I construct();
};

template <typename I, I N, typename T, typename... Ts>
struct variant_construct<I, N, T, Ts...>
    : private variant_construct<I, N + 1, Ts...> {
  using super = variant_construct<I, N + 1, Ts...>;

  static I construct(void* storage, const T& value) {
    logger()->debug() << "copy construct<" << N << ">";
    new (storage) T(value);
    return N;
  }
  static I construct(void* storage, T&& value) {
    logger()->debug() << "move construct<" << N << ">";
    new (storage) T(std::forward<T>(value));
    return N;
  }
  using super::construct;
};

template <typename I, I N, typename... Ts>
struct variant_visit;

template <typename I, I N>
struct variant_visit<I, N> {
  template <typename R, typename F>
  static R visit_helper_const(I tag, const void*, F&&) {
    throw std::logic_error("variant tag invalid: " + std::to_string(tag));
  }
  template <typename R, typename F>
  static R visit_helper_rvalue(I tag, void*, F&&) {
    throw std::logic_error("variant tag invalid: " + std::to_string(tag));
  }
};

template <typename I, I N, typename T, typename... Ts>
struct variant_visit<I, N, T, Ts...> : private variant_visit<I, N + 1, Ts...> {
  using super = variant_visit<I, N + 1, Ts...>;

  template <typename R, typename F>
  static R visit_helper_const(I tag, const void* storage, F&& f) {
    logger()->debug() << "visit_helper<" << N << "> const& (" << tag << ")";
    if (tag == N) {
      return f(*reinterpret_cast<const T*>(storage));
    }
    return super::template visit_helper_const<R>(tag, storage,
                                                 std::forward<F>(f));
  }
  template <typename R, typename F>
  static R visit_helper_rvalue(I tag, void* storage, F&& f) {
    logger()->debug() << "visit_helper<" << N << "> && (" << tag << ")";
    if (tag == N) {
      return f(std::move(*reinterpret_cast<T*>(storage)));
    }
    return super::template visit_helper_rvalue<R>(tag, storage,
                                                  std::forward<F>(f));
  }
};

template <uintmax_t N, typename Enable = void>
struct smallest_unisnged_type;

template <uintmax_t N>
struct smallest_unisnged_type<
    N, typename std::enable_if_t<N <= std::numeric_limits<uint8_t>::max()>> {
  using type = uint8_t;
};

template <uintmax_t N>
using smallest_unisnged_type_t = typename smallest_unisnged_type<N>::type;

template <typename... Ts>
struct variant_helper {
  using tag_type = smallest_unisnged_type_t<sizeof...(Ts)>;
  using super_construct = variant_construct<tag_type, 0, Ts...>;
  using super_visit = variant_visit<tag_type, 0, Ts...>;
};
}

template <typename... Ts>
class variant : private detail::variant_helper<Ts...>::super_construct,
                private detail::variant_helper<Ts...>::super_visit {
  using helper = detail::variant_helper<Ts...>;
  using super_construct = typename helper::super_construct;
  using super_visit = typename helper::super_visit;

  typename std::aligned_union_t<0, char, Ts...> storage;
  typename helper::tag_type tag;

  using super_construct::construct;

  void destruct() {
    std::move(*this).template visit<void>([this](auto&& v) {
      using T = std::decay_t<decltype(v)>;
      reinterpret_cast<T*>(&storage)->~T();
    });
  }

 public:
  template <typename T, typename = decltype(construct(
                            &storage, std::forward<T>(std::declval<T>())))>
  variant(T&& value) {
    tag = construct(&storage, std::forward<T>(value));
  }

  variant(const variant& other) {
    detail::logger()->debug("variant copy constructor");
    other.visit<void>(
        [this](auto&& value) { tag = construct(&storage, value); });
  }
  variant(variant&& other) {
    detail::logger()->debug("variant move constructor");
    std::move(other).template visit<void>([this](auto&& value) {
      tag = construct(&storage, std::forward<decltype(value)>(value));
    });
  }
  variant& operator=(const variant& other) {
    detail::logger()->debug("variant copy assignment");
    destruct();
    other.visit<void>(
        [this](auto&& value) { tag = construct(&storage, value); });
    return *this;
  }
  variant& operator=(variant&& other) {
    detail::logger()->debug("variant move assignment");
    destruct();
    std::move(other).template visit<void>([this](auto&& value) {
      tag = construct(&storage, std::forward<decltype(value)>(value));
    });
    return *this;
  }

  ~variant() { destruct(); }

  template <typename R, typename F>
  auto visit(F&& f) const& {
    detail::logger()->debug("visit const &");
    return super_visit::template visit_helper_const<R>(tag, &storage,
                                                       std::forward<F>(f));
  }
  template <typename R, typename F>
  auto visit(F&& f) && {
    detail::logger()->debug("visit &&");
    return std::move(*this).super_visit::template visit_helper_rvalue<R>(
        tag, &storage, std::forward<F>(f));
  }
};

template <typename... Ts>
std::ostream& operator<<(std::ostream& os, const variant<Ts...>& v) {
  os << "variant[" << v.tag << "]: ";
  v.template visit<void>([&os](const auto& x) { os << x; });
  return os;
}

}  // namespace toby

#endif
<commit_msg>variant: make storage and tag public so logging compiles<commit_after>#ifndef INCLUDED_TOBY_VARIANT_H
#define INCLUDED_TOBY_VARIANT_H

#include <cstddef>
#include <stdexcept>

#include <spdlog/spdlog.h>

namespace toby {
namespace detail {
inline auto logger() { return spdlog::get("variant"); }

template <typename I, I N, typename... Ts>
struct variant_construct;

template <typename I, I N>
struct variant_construct<I, N> {
  static I construct();
};

template <typename I, I N, typename T, typename... Ts>
struct variant_construct<I, N, T, Ts...>
    : private variant_construct<I, N + 1, Ts...> {
  using super = variant_construct<I, N + 1, Ts...>;

  static I construct(void* storage, const T& value) {
    logger()->debug() << "copy construct<" << N << ">";
    new (storage) T(value);
    return N;
  }
  static I construct(void* storage, T&& value) {
    logger()->debug() << "move construct<" << N << ">";
    new (storage) T(std::forward<T>(value));
    return N;
  }
  using super::construct;
};

template <typename I, I N, typename... Ts>
struct variant_visit;

template <typename I, I N>
struct variant_visit<I, N> {
  template <typename R, typename F>
  static R visit_helper_const(I tag, const void*, F&&) {
    throw std::logic_error("variant tag invalid: " + std::to_string(tag));
  }
  template <typename R, typename F>
  static R visit_helper_rvalue(I tag, void*, F&&) {
    throw std::logic_error("variant tag invalid: " + std::to_string(tag));
  }
};

template <typename I, I N, typename T, typename... Ts>
struct variant_visit<I, N, T, Ts...> : private variant_visit<I, N + 1, Ts...> {
  using super = variant_visit<I, N + 1, Ts...>;

  template <typename R, typename F>
  static R visit_helper_const(I tag, const void* storage, F&& f) {
    logger()->debug() << "visit_helper<" << N << "> const& (" << tag << ")";
    if (tag == N) {
      return f(*reinterpret_cast<const T*>(storage));
    }
    return super::template visit_helper_const<R>(tag, storage,
                                                 std::forward<F>(f));
  }
  template <typename R, typename F>
  static R visit_helper_rvalue(I tag, void* storage, F&& f) {
    logger()->debug() << "visit_helper<" << N << "> && (" << tag << ")";
    if (tag == N) {
      return f(std::move(*reinterpret_cast<T*>(storage)));
    }
    return super::template visit_helper_rvalue<R>(tag, storage,
                                                  std::forward<F>(f));
  }
};

template <uintmax_t N, typename Enable = void>
struct smallest_unisnged_type;

template <uintmax_t N>
struct smallest_unisnged_type<
    N, typename std::enable_if_t<N <= std::numeric_limits<uint8_t>::max()>> {
  using type = uint8_t;
};

template <uintmax_t N>
using smallest_unisnged_type_t = typename smallest_unisnged_type<N>::type;

template <typename... Ts>
struct variant_helper {
  using tag_type = smallest_unisnged_type_t<sizeof...(Ts)>;
  using super_construct = variant_construct<tag_type, 0, Ts...>;
  using super_visit = variant_visit<tag_type, 0, Ts...>;
};
}

template <typename... Ts>
class variant : private detail::variant_helper<Ts...>::super_construct,
                private detail::variant_helper<Ts...>::super_visit {
  using helper = detail::variant_helper<Ts...>;
  using super_construct = typename helper::super_construct;
  using super_visit = typename helper::super_visit;

public:
  typename std::aligned_union_t<0, char, Ts...> storage;
  typename helper::tag_type tag;

private:
  using super_construct::construct;

  void destruct() {
    std::move(*this).template visit<void>([this](auto&& v) {
      using T = std::decay_t<decltype(v)>;
      reinterpret_cast<T*>(&storage)->~T();
    });
  }

 public:
  template <typename T, typename = decltype(construct(
                            &storage, std::forward<T>(std::declval<T>())))>
  variant(T&& value) {
    tag = construct(&storage, std::forward<T>(value));
  }

  variant(const variant& other) {
    detail::logger()->debug("variant copy constructor");
    other.visit<void>(
        [this](auto&& value) { tag = construct(&storage, value); });
  }
  variant(variant&& other) {
    detail::logger()->debug("variant move constructor");
    std::move(other).template visit<void>([this](auto&& value) {
      tag = construct(&storage, std::forward<decltype(value)>(value));
    });
  }
  variant& operator=(const variant& other) {
    detail::logger()->debug("variant copy assignment");
    destruct();
    other.visit<void>(
        [this](auto&& value) { tag = construct(&storage, value); });
    return *this;
  }
  variant& operator=(variant&& other) {
    detail::logger()->debug("variant move assignment");
    destruct();
    std::move(other).template visit<void>([this](auto&& value) {
      tag = construct(&storage, std::forward<decltype(value)>(value));
    });
    return *this;
  }

  ~variant() { destruct(); }

  template <typename R, typename F>
  auto visit(F&& f) const& {
    detail::logger()->debug("visit const &");
    return super_visit::template visit_helper_const<R>(tag, &storage,
                                                       std::forward<F>(f));
  }
  template <typename R, typename F>
  auto visit(F&& f) && {
    detail::logger()->debug("visit &&");
    return std::move(*this).super_visit::template visit_helper_rvalue<R>(
        tag, &storage, std::forward<F>(f));
  }
};

template <typename... Ts>
std::ostream& operator<<(std::ostream& os, const variant<Ts...>& v) {
  os << "variant[" << v.tag << "]: ";
  v.template visit<void>([&os](const auto& x) { os << x; });
  return os;
}

}  // namespace toby

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <iostream>
#include <fstream>

#include "util.h"
#include "hash.h"
#include "init.h" // for pwalletMain
#include "rpcserver.h"
#include "ui_interface.h"
#include "base58.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string.hpp>

using namespace json_spirit;
using namespace std;

void EnsureWalletIsUnlocked();

namespace bt = boost::posix_time;

// Extended DecodeDumpTime implementation, see this page for details:
// http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
const std::locale formats[] = {
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
};

const size_t formats_n = sizeof(formats)/sizeof(formats[0]);

std::time_t pt_to_time_t(const bt::ptime& pt)
{
    bt::ptime timet_start(boost::gregorian::date(1970,1,1));
    bt::time_duration diff = pt - timet_start;
    return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
}

int64_t DecodeDumpTime(const std::string& s)
{
    bt::ptime pt;

    for(size_t i=0; i<formats_n; ++i)
    {
        std::istringstream is(s);
        is.imbue(formats[i]);
        is >> pt;
        if(pt != bt::ptime()) break;
    };

    return pt_to_time_t(pt);
}

std::string static EncodeDumpTime(int64_t nTime)
{
    return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}

std::string static EncodeDumpString(const std::string &str)
{
    std::stringstream ret;
    BOOST_FOREACH(unsigned char c, str)
    {
        if (c <= 32 || c >= 128 || c == '%')
        {
            ret << '%' << HexStr(&c, &c + 1);
        } else
        {
            ret << c;
        };
    };
    return ret.str();
}

std::string DecodeDumpString(const std::string &str)
{
    std::stringstream ret;
    for (unsigned int pos = 0; pos < str.length(); pos++)
    {
        unsigned char c = str[pos];
        if (c == '%' && pos+2 < str.length())
        {
            c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4)
                | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
            pos += 2;
        };
        ret << c;
    };
    return ret.str();
}

class CTxDump
{
public:
    CBlockIndex *pindex;
    int64_t nValue;
    bool fSpent;
    CWalletTx* ptx;
    int nOut;
    CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
    {
        pindex = NULL;
        nValue = 0;
        fSpent = false;
        this->ptx = ptx;
        this->nOut = nOut;
    }
};

Value importprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "importprivkey <okcashprivkey> [label]\n"
            "Adds a private key (as returned by dumpprivkey) to your wallet.");

    string strSecret = params[0].get_str();
    string strLabel = "";
    if (params.size() > 1)
        strLabel = params[1].get_str();

    // Whether to perform rescan after import
    bool fRescan = true;
    if (params.size() > 2)
        fRescan = params[2].get_bool();

    CBitcoinSecret vchSecret;
    bool fGood = vchSecret.SetString(strSecret);

    if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
    if (fWalletUnlockStakingOnly)
        throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");

    CKey key = vchSecret.GetKey();
    CPubKey pubkey = key.GetPubKey();
    CKeyID vchAddress = pubkey.GetID();
    {
        LOCK2(cs_main, pwalletMain->cs_wallet);

        pwalletMain->MarkDirty();
        pwalletMain->SetAddressBookName(vchAddress, strLabel);

        // Don't throw error in case a key is already there
        if (pwalletMain->HaveKey(vchAddress))
            return Value::null;

        pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;

        if (!pwalletMain->AddKeyPubKey(key, pubkey))
            throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");

        // whenever a key is imported, we need to scan the whole chain
        pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'

        if (fRescan) {
            pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
            pwalletMain->ReacceptWalletTransactions();
        }
    }

    return Value::null;
}

Value importwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "importwallet <filename>\n"
            "Imports keys from a wallet dump file (see dumpwallet).");

    EnsureWalletIsUnlocked();

    ifstream file;
    file.open(params[0].get_str().c_str());
    if (!file.is_open())
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");

    int64_t nTimeBegin = pindexBest->nTime;

    bool fGood = true;

    while (file.good()) {
        std::string line;
        std::getline(file, line);
        if (line.empty() || line[0] == '#')
            continue;

        std::vector<std::string> vstr;
        boost::split(vstr, line, boost::is_any_of(" "));
        if (vstr.size() < 2)
            continue;
        CBitcoinSecret vchSecret;
        if (!vchSecret.SetString(vstr[0]))
            continue;
        CKey key = vchSecret.GetKey();
        CPubKey pubkey = key.GetPubKey();
        CKeyID keyid = pubkey.GetID();
        if (pwalletMain->HaveKey(keyid)) {
            LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
            continue;
        }
        int64_t nTime = DecodeDumpTime(vstr[1]);
        std::string strLabel;
        bool fLabel = true;
        for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
            if (boost::algorithm::starts_with(vstr[nStr], "#"))
                break;
            if (vstr[nStr] == "change=1")
                fLabel = false;
            if (vstr[nStr] == "reserve=1")
                fLabel = false;
            if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
                strLabel = DecodeDumpString(vstr[nStr].substr(6));
                fLabel = true;
            }
        }
        LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
        if (!pwalletMain->AddKey(key)) {
            fGood = false;
            continue;
        }
        pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
        if (fLabel)
            pwalletMain->SetAddressBookName(keyid, strLabel);
        nTimeBegin = std::min(nTimeBegin, nTime);
    }
    file.close();

    CBlockIndex *pindex = pindexBest;
    while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)
        pindex = pindex->pprev;

    if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
        pwalletMain->nTimeFirstKey = nTimeBegin;

    LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1);
    pwalletMain->ScanForWalletTransactions(pindex);
    pwalletMain->ReacceptWalletTransactions();
    pwalletMain->MarkDirty();

    if (!fGood)
        throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");

    return Value::null;
}

Value dumpprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "dumpprivkey <okcashaddress>\n"
            "Reveals the private key corresponding to <okcashaddress>.");

    EnsureWalletIsUnlocked();

    string strAddress = params[0].get_str();
    CBitcoinAddress address;
    if (!address.SetString(strAddress))
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Okcash address");
    if (fWalletUnlockStakingOnly)
        throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");
    CKeyID keyID;
    if (!address.GetKeyID(keyID))
        throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
    CKey vchSecret;
    if (!pwalletMain->GetKey(keyID, vchSecret))
        throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
    return CBitcoinSecret(vchSecret).ToString();
}

Value dumpwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "dumpwallet <filename>\n"
            "Dumps all wallet keys in a human-readable format.");

    EnsureWalletIsUnlocked();

    ofstream file;
    file.open(params[0].get_str().c_str());
    if (!file.is_open())
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");

    std::map<CKeyID, int64_t> mapKeyBirth;

    std::set<CKeyID> setKeyPool;

    pwalletMain->GetKeyBirthTimes(mapKeyBirth);

    pwalletMain->GetAllReserveKeys(setKeyPool);

    // sort time/key pairs
    std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
    for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
        vKeyBirth.push_back(std::make_pair(it->second, it->first));
    }
    mapKeyBirth.clear();
    std::sort(vKeyBirth.begin(), vKeyBirth.end());

    // produce output
    file << strprintf("# Wallet dump created by Okcash %s (%s)\n", CLIENT_BUILD, CLIENT_DATE);
    file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
    file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString());
    file << strprintf("#   mined on %s\n", EncodeDumpTime(pindexBest->nTime));
    file << "\n";
    for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
        const CKeyID &keyid = it->second;
        std::string strTime = EncodeDumpTime(it->first);
        std::string strAddr = CBitcoinAddress(keyid).ToString();

        CKey key;
        if (pwalletMain->GetKey(keyid, key)) {
            if (pwalletMain->mapAddressBook.count(keyid)) {
                file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr);
            } else if (setKeyPool.count(keyid)) {
                file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
            } else {
                file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
            }
        }
    }
    file << "\n";
    file << "# End of dump\n";
    file.close();
    return Value::null;
}
<commit_msg>timestamp/ psize/ okchtaddrss<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <iostream>
#include <fstream>

#include "init.h" // for pwalletMain
#include "rpcserver.h"
#include "ui_interface.h"
#include "base58.h"

#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string.hpp>

using namespace json_spirit;
using namespace std;

void EnsureWalletIsUnlocked();

namespace bt = boost::posix_time;

// Extended DecodeDumpTime implementation, see this page for details:
// http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
const std::locale formats[] = {
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
    std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
};

const size_t formats_n = sizeof(formats)/sizeof(formats[0]);

std::time_t pt_to_time_t(const bt::ptime& pt)
{
    bt::ptime timet_start(boost::gregorian::date(1970,1,1));
    bt::time_duration diff = pt - timet_start;
    return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
}

int64_t DecodeDumpTime(const std::string& s)
{
    bt::ptime pt;

    for(size_t i=0; i<formats_n; ++i)
    {
        std::istringstream is(s);
        is.imbue(formats[i]);
        is >> pt;
        if(pt != bt::ptime()) break;
    };

    return pt_to_time_t(pt);
}

std::string static EncodeDumpTime(int64_t nTime)
{
    return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}

std::string static EncodeDumpString(const std::string &str)
{
    std::stringstream ret;
    BOOST_FOREACH(unsigned char c, str)
    {
        if (c <= 32 || c >= 128 || c == '%')
        {
            ret << '%' << HexStr(&c, &c + 1);
        } else
        {
            ret << c;
        };
    };
    return ret.str();
}

std::string DecodeDumpString(const std::string &str)
{
    std::stringstream ret;
    for (unsigned int pos = 0; pos < str.length(); pos++)
    {
        unsigned char c = str[pos];
        if (c == '%' && pos+2 < str.length())
        {
            c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4)
                | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
            pos += 2;
        };
        ret << c;
    };
    return ret.str();
}

class CTxDump
{
public:
    CBlockIndex *pindex;
    int64_t nValue;
    bool fSpent;
    CWalletTx* ptx;
    int nOut;
    CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
    {
        pindex = NULL;
        nValue = 0;
        fSpent = false;
        this->ptx = ptx;
        this->nOut = nOut;
    }
};

Value importprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 4)
        throw runtime_error(
            "importprivkey <okcashprivkey> [label] [rescan=true] [timestamp=1]\n"
            "Adds a private key (as returned by dumpprivkey) to your wallet.");

    string strSecret = params[0].get_str();
    string strLabel = "";
    if (params.size() > 1)
        strLabel = params[1].get_str();

    // Whether to perform rescan after import
    bool fRescan = true;
    if (params.size() > 2)
        fRescan = params[2].get_bool();

    int64_t nCreateTime = 1;
    if (params.size() > 3)
        nCreateTime = params[3].get_int64();

    CBitcoinSecret vchSecret;
    bool fGood = vchSecret.SetString(strSecret);

    if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
    if (fWalletUnlockStakingOnly)
        throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");

    CKey key = vchSecret.GetKey();
    CPubKey pubkey = key.GetPubKey();
    CKeyID vchAddress = pubkey.GetID();
    {
        LOCK2(cs_main, pwalletMain->cs_wallet);

        pwalletMain->MarkDirty();
        pwalletMain->SetAddressBookName(vchAddress, strLabel);

        // Don't throw error in case a key is already there
        if (pwalletMain->HaveKey(vchAddress))
            return Value::null;

        pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = nCreateTime;

        if (!pwalletMain->AddKeyPubKey(key, pubkey))
            throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");

        // whenever a key is imported, we need to scan the whole chain
        pwalletMain->nTimeFirstKey = nCreateTime; // 0 would be considered 'no value'

        if (fRescan) {
            pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
            pwalletMain->ReacceptWalletTransactions();
        }
    }

    SecureMsgAddWalletAddresses();

    return Value::null;
}

Value importwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "importwallet <filename>\n"
            "Imports keys from a wallet dump file (see dumpwallet).");

    EnsureWalletIsUnlocked();

    ifstream file;
    file.open(params[0].get_str().c_str());
    if (!file.is_open())
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");

    int64_t nTimeBegin = pindexBest->nTime;

    bool fGood = true;

    while (file.good()) {
        std::string line;
        std::getline(file, line);
        if (line.empty() || line[0] == '#')
            continue;

        std::vector<std::string> vstr;
        boost::split(vstr, line, boost::is_any_of(" "));
        if (vstr.size() < 2)
            continue;
        CBitcoinSecret vchSecret;
        if (!vchSecret.SetString(vstr[0]))
            continue;
        CKey key = vchSecret.GetKey();
        CPubKey pubkey = key.GetPubKey();
        CKeyID keyid = pubkey.GetID();
        if (pwalletMain->HaveKey(keyid)) {
            LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
            continue;
        }
        int64_t nTime = DecodeDumpTime(vstr[1]);
        std::string strLabel;
        bool fLabel = true;
        for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
            if (boost::algorithm::starts_with(vstr[nStr], "#"))
                break;
            if (vstr[nStr] == "change=1")
                fLabel = false;
            if (vstr[nStr] == "reserve=1")
                fLabel = false;
            if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
                strLabel = DecodeDumpString(vstr[nStr].substr(6));
                fLabel = true;
            }
        }
        LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
        if (!pwalletMain->AddKey(key)) {
            fGood = false;
            continue;
        }
        pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
        if (fLabel)
            pwalletMain->SetAddressBookName(keyid, strLabel);
        nTimeBegin = std::min(nTimeBegin, nTime);
    }
    file.close();

    CBlockIndex *pindex = pindexBest;
    while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)
        pindex = pindex->pprev;

    if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
        pwalletMain->nTimeFirstKey = nTimeBegin;

    LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1);
    pwalletMain->ScanForWalletTransactions(pindex);
    pwalletMain->ReacceptWalletTransactions();
    pwalletMain->MarkDirty();

    if (!fGood)
        throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");

    return Value::null;
}

Value dumpprivkey(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "dumpprivkey <okcashaddress/public_key_hex>\n"
            "Reveals the private key corresponding to <okcashaddress>.");

    EnsureWalletIsUnlocked();

    if (fWalletUnlockStakingOnly)
        throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");

    string strAddress = params[0].get_str();

    CBitcoinAddress address;
    CKeyID keyID;
    bool fIsPubkey = false;
    if (IsHex(strAddress) && strAddress.size() > 60) // pubkey input
    {
        CPubKey pk(ParseHex(strAddress));
        if (!pk.IsValid())
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid public key");
        keyID = pk.GetID();
        fIsPubkey = true;
    } else
    {
        if (!address.SetString(strAddress))
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Okcash address");
        if (!address.GetKeyID(keyID))
            throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
    };

    CKey vchSecret;
    if (!pwalletMain->GetKey(keyID, vchSecret))
        throw JSONRPCError(RPC_WALLET_ERROR, std::string("Private key for ")+(fIsPubkey ? "public key " : "address ") + strAddress + " is not known");
    return CBitcoinSecret(vchSecret).ToString();
}

Value dumpwallet(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "dumpwallet <filename>\n"
            "Dumps all wallet keys in a human-readable format.");

    EnsureWalletIsUnlocked();

    ofstream file;
    file.open(params[0].get_str().c_str());
    if (!file.is_open())
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");

    std::map<CKeyID, int64_t> mapKeyBirth;

    std::set<CKeyID> setKeyPool;

    pwalletMain->GetKeyBirthTimes(mapKeyBirth);

    pwalletMain->GetAllReserveKeys(setKeyPool);

    // sort time/key pairs
    std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
    for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
        vKeyBirth.push_back(std::make_pair(it->second, it->first));
    }
    mapKeyBirth.clear();
    std::sort(vKeyBirth.begin(), vKeyBirth.end());

    // produce output
    file << strprintf("# Wallet dump created by Okcash %s (%s)\n", CLIENT_BUILD, CLIENT_DATE);
    file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
    file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString());
    file << strprintf("#   mined on %s\n", EncodeDumpTime(pindexBest->nTime));
    file << "\n";
    for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
        const CKeyID &keyid = it->second;
        std::string strTime = EncodeDumpTime(it->first);
        std::string strAddr = CBitcoinAddress(keyid).ToString();

        CKey key;
        if (pwalletMain->GetKey(keyid, key)) {
            if (pwalletMain->mapAddressBook.count(keyid)) {
                file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid]), strAddr);
            } else if (setKeyPool.count(keyid)) {
                file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
            } else {
                file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
            }
        }
    }
    file << "\n";
    file << "# End of dump\n";
    file.close();
    return Value::null;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Magnus Jonsson, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/allocate_resources.hpp"
#include "libtorrent/size_type.hpp"
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/torrent.hpp"

#include <cassert>
#include <algorithm>
#include <boost/limits.hpp>

#if defined(_MSC_VER) && _MSC_VER < 1310
#define for if (false) {} else for
#else
#include <boost/iterator/transform_iterator.hpp>
#endif

namespace libtorrent
{
	int saturated_add(int a, int b)
	{
		assert(a >= 0);
		assert(b >= 0);
		assert(std::numeric_limits<int>::max() + std::numeric_limits<int>::max() < 0);

		int sum = a + b;
		if(sum < 0)
			sum = std::numeric_limits<int>::max();

		assert(sum >= a && sum >= b);
		return sum;
	}

	namespace
	{
		// give num_resources to r,
		// return how how many were actually accepted.
		int give(resource_request& r, int num_resources)
		{
			assert(num_resources >= 0);
			assert(r.given <= r.max);

			int accepted = std::min(num_resources, r.max - r.given);
			assert(accepted >= 0);

			r.given += accepted;
			assert(r.given <= r.max);

			return accepted;
		}

#ifndef NDEBUG

		template<class It, class T>
		class allocate_resources_contract_check
		{
			int m_resources;
			It m_start;
			It m_end;
			resource_request T::* m_res;

		public:
			allocate_resources_contract_check(
				int resources
				, It start
				, It end
				, resource_request T::* res)
				: m_resources(resources)
				, m_start(start)
				, m_end(end)
				, m_res(res)
			{
				assert(m_resources >= 0);
				for (It i = m_start, end(m_end); i != end; ++i)
				{
					assert(((*i).*m_res).used >= 0);
					assert(((*i).*m_res).max >= 0);
					assert(((*i).*m_res).given >= 0);
				}
			}

			~allocate_resources_contract_check()
			{
				int sum_given = 0;
				int sum_max = 0;
				int sum_min = 0;
				for (It i = m_start, end(m_end); i != end; ++i)
				{
					assert(((*i).*m_res).max >= 0);
					assert(((*i).*m_res).min >= 0);
					assert(((*i).*m_res).max >= ((*i).*m_res).min);
					assert(((*i).*m_res).given >= 0);
					assert(((*i).*m_res).given <= ((*i).*m_res).max);

					sum_given = saturated_add(sum_given, ((*i).*m_res).given);
					sum_max = saturated_add(sum_max, ((*i).*m_res).max);
					sum_min = saturated_add(sum_min, ((*i).*m_res).min);
				}
				assert(sum_given == std::min(std::max(m_resources, sum_min), sum_max));
			}
		};

#endif

		template<class It, class T>
		void allocate_resources_impl(
			int resources
			, It start
			, It end
			, resource_request T::* res)
		{
	#ifndef NDEBUG
			allocate_resources_contract_check<It, T> contract_check(
				resources
				, start
				, end
				, res);
	#endif

			if(resources == std::numeric_limits<int>::max())
			{
				// No competition for resources.
				// Just give everyone what they want.
				for (It i = start; i != end; ++i)
				{
					((*i).*res).given = ((*i).*res).max;
				}
				return;
			}

			// Resources are scarce

			int sum_max = 0;
			int sum_min = 0;
			for (It i = start; i != end; ++i)
			{
				sum_max = saturated_add(sum_max, ((*i).*res).max);
				assert(((*i).*res).min < std::numeric_limits<int>::max());
				assert(((*i).*res).min >= 0);
				assert(((*i).*res).min <= ((*i).*res).max);
				sum_min += ((*i).*res).min;
				((*i).*res).given = ((*i).*res).min;
			}

			if (resources == 0 || sum_max == 0)
				return;

			resources = std::max(resources, sum_min);
			int resources_to_distribute = std::min(resources, sum_max) - sum_min;
			assert(resources_to_distribute >= 0);

			while (resources_to_distribute > 0)
			{
				size_type total_used = 0;
				size_type max_used = 0;
				for (It i = start; i != end; ++i)
				{
					resource_request& r = (*i).*res;
					if(r.given == r.max) continue;

					assert(r.given < r.max);

					max_used = std::max(max_used, (size_type)r.used + 1);
					total_used += (size_type)r.used + 1;
				}

				size_type kNumer = resources_to_distribute;
				size_type kDenom = total_used;

				if (kNumer * max_used <= kDenom)
				{
					kNumer = 1;
					kDenom = max_used;
				}

				for (It i = start; i != end && resources_to_distribute > 0; ++i)
				{
					resource_request& r = (*i).*res;
					if(r.given == r.max) continue;

					assert(r.given < r.max);

					size_type used = (size_type)r.used + 1;
					size_type toGive = used * kNumer / kDenom;
					if(toGive > std::numeric_limits<int>::max())
						toGive = std::numeric_limits<int>::max();
					resources_to_distribute -= give(r, (int)toGive);
				}

				assert(resources_to_distribute >= 0);
			}
		}

		peer_connection& pick_peer(
			std::pair<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> > const& p)
		{
			return *p.second;
		}

		peer_connection& pick_peer2(
			std::pair<address, peer_connection*> const& p)
		{
			return *p.second;
		}

		torrent& deref(std::pair<sha1_hash, boost::shared_ptr<torrent> > const& p)
		{
			return *p.second;
		}

	} // namespace anonymous

/*
	void allocate_resources(
		int resources
		, std::map<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> >& c
		, resource_request peer_connection::* res)
	{
		typedef std::map<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> >::iterator orig_iter;
		typedef std::pair<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> > in_param;
		typedef boost::transform_iterator<peer_connection& (*)(in_param const&), orig_iter> new_iter;

		allocate_resources_impl(
			resources
			, new_iter(c.begin(), &pick_peer)
			, new_iter(c.end(), &pick_peer)
			, res);
	}
*/
#if defined(_MSC_VER) && _MSC_VER < 1310

	namespace detail
	{
		struct iterator_wrapper
		{
			typedef std::map<sha1_hash, boost::shared_ptr<torrent> >::iterator orig_iter;

			orig_iter iter;

			iterator_wrapper(orig_iter i): iter(i) {}
			void operator++() { ++iter; }
			torrent& operator*() { return *(iter->second); }
			bool operator==(const iterator_wrapper& i) const
			{ return iter == i.iter; }
			bool operator!=(const iterator_wrapper& i) const
			{ return iter != i.iter; }
		};

		struct iterator_wrapper2
		{
			typedef std::map<address, peer_connection*>::iterator orig_iter;

			orig_iter iter;

			iterator_wrapper2(orig_iter i): iter(i) {}
			void operator++() { ++iter; }
			peer_connection& operator*() { return *(iter->second); }
			bool operator==(const iterator_wrapper2& i) const
			{ return iter == i.iter; }
			bool operator!=(const iterator_wrapper2& i) const
			{ return iter != i.iter; }
		};

	}

	void allocate_resources(
		int resources
		, std::map<sha1_hash, boost::shared_ptr<torrent> >& c
		, resource_request torrent::* res)
	{
		allocate_resources_impl(
			resources
			, detail::iterator_wrapper(c.begin())
			, detail::iterator_wrapper(c.end())
			, res);
	}

	void allocate_resources(
		int resources
		, std::map<address, peer_connection*>& c
		, resource_request peer_connection::* res)
	{
		allocate_resources_impl(
			resources
			, detail::iterator_wrapper2(c.begin())
			, detail::iterator_wrapper2(c.end())
			, res);
	}

#else

	void allocate_resources(
		int resources
		, std::map<sha1_hash, boost::shared_ptr<torrent> >& c
		, resource_request torrent::* res)
	{
		typedef std::map<sha1_hash, boost::shared_ptr<torrent> >::iterator orig_iter;
		typedef std::pair<sha1_hash, boost::shared_ptr<torrent> > in_param;
		typedef boost::transform_iterator<torrent& (*)(in_param const&), orig_iter> new_iter;

		allocate_resources_impl(
			resources
			, new_iter(c.begin(), &deref)
			, new_iter(c.end(), &deref)
			, res);
	}

	void allocate_resources(
		int resources
		, std::map<address, peer_connection*>& c
		, resource_request peer_connection::* res)
	{
		typedef std::map<address, peer_connection*>::iterator orig_iter;
		typedef std::pair<address, peer_connection*> in_param;
		typedef boost::transform_iterator<peer_connection& (*)(in_param const&), orig_iter> new_iter;

		allocate_resources_impl(
			resources
			, new_iter(c.begin(), &pick_peer2)
			, new_iter(c.end(), &pick_peer2)
			, res);
	}
#endif

} // namespace libtorrent
<commit_msg>added BOOST lib 1.32.0 compiling supported in Win32 platform<commit_after>/*

Copyright (c) 2003, Magnus Jonsson, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

//The Standard Library defines the two template functions std::min()
//and std::max() in the <algorithm> header. In general, you should
//use these template functions for calculating the min and max values
//of a pair. Unfortunately, Visual C++ does not define these function
// templates. This is because the names min and max clash with
//the traditional min and max macros defined in <windows.h>.
//As a workaround, Visual C++ defines two alternative templates with
//identical functionality called _cpp_min() and _cpp_max(). You can
//use them instead of std::min() and std::max().To disable the
//generation of the min and max macros in Visual C++, #define
//NOMINMAX before #including <windows.h>.
#ifdef _WIN32
    //support boost1.32.0(2004-11-19 18:47)
    //now all libs can be compiled and linked with static module
	#define NOMINMAX
#endif

#include "libtorrent/allocate_resources.hpp"
#include "libtorrent/size_type.hpp"
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/torrent.hpp"

#include <cassert>
#include <algorithm>
#include <boost/limits.hpp>

#if defined(_MSC_VER) && _MSC_VER < 1310
#define for if (false) {} else for
#else
#include <boost/iterator/transform_iterator.hpp>
#endif

namespace libtorrent
{
	int saturated_add(int a, int b)
	{
		assert(a >= 0);
		assert(b >= 0);
		assert(std::numeric_limits<int>::max() + std::numeric_limits<int>::max() < 0);

		int sum = a + b;
		if(sum < 0)
			sum = std::numeric_limits<int>::max();

		assert(sum >= a && sum >= b);
		return sum;
	}

	namespace
	{
		// give num_resources to r,
		// return how how many were actually accepted.
		int give(resource_request& r, int num_resources)
		{
			assert(num_resources >= 0);
			assert(r.given <= r.max);

			int accepted = std::min(num_resources, r.max - r.given);
			assert(accepted >= 0);

			r.given += accepted;
			assert(r.given <= r.max);

			return accepted;
		}

#ifndef NDEBUG

		template<class It, class T>
		class allocate_resources_contract_check
		{
			int m_resources;
			It m_start;
			It m_end;
			resource_request T::* m_res;

		public:
			allocate_resources_contract_check(
				int resources
				, It start
				, It end
				, resource_request T::* res)
				: m_resources(resources)
				, m_start(start)
				, m_end(end)
				, m_res(res)
			{
				assert(m_resources >= 0);
				for (It i = m_start, end(m_end); i != end; ++i)
				{
					assert(((*i).*m_res).used >= 0);
					assert(((*i).*m_res).max >= 0);
					assert(((*i).*m_res).given >= 0);
				}
			}

			~allocate_resources_contract_check()
			{
				int sum_given = 0;
				int sum_max = 0;
				int sum_min = 0;
				for (It i = m_start, end(m_end); i != end; ++i)
				{
					assert(((*i).*m_res).max >= 0);
					assert(((*i).*m_res).min >= 0);
					assert(((*i).*m_res).max >= ((*i).*m_res).min);
					assert(((*i).*m_res).given >= 0);
					assert(((*i).*m_res).given <= ((*i).*m_res).max);

					sum_given = saturated_add(sum_given, ((*i).*m_res).given);
					sum_max = saturated_add(sum_max, ((*i).*m_res).max);
					sum_min = saturated_add(sum_min, ((*i).*m_res).min);
				}
				assert(sum_given == std::min(std::max(m_resources, sum_min), sum_max));
			}
		};

#endif

		template<class It, class T>
		void allocate_resources_impl(
			int resources
			, It start
			, It end
			, resource_request T::* res)
		{
	#ifndef NDEBUG
			allocate_resources_contract_check<It, T> contract_check(
				resources
				, start
				, end
				, res);
	#endif

			if(resources == std::numeric_limits<int>::max())
			{
				// No competition for resources.
				// Just give everyone what they want.
				for (It i = start; i != end; ++i)
				{
					((*i).*res).given = ((*i).*res).max;
				}
				return;
			}

			// Resources are scarce

			int sum_max = 0;
			int sum_min = 0;
			for (It i = start; i != end; ++i)
			{
				sum_max = saturated_add(sum_max, ((*i).*res).max);
				assert(((*i).*res).min < std::numeric_limits<int>::max());
				assert(((*i).*res).min >= 0);
				assert(((*i).*res).min <= ((*i).*res).max);
				sum_min += ((*i).*res).min;
				((*i).*res).given = ((*i).*res).min;
			}

			if (resources == 0 || sum_max == 0)
				return;

			resources = std::max(resources, sum_min);
			int resources_to_distribute = std::min(resources, sum_max) - sum_min;
			assert(resources_to_distribute >= 0);

			while (resources_to_distribute > 0)
			{
				size_type total_used = 0;
				size_type max_used = 0;
				for (It i = start; i != end; ++i)
				{
					resource_request& r = (*i).*res;
					if(r.given == r.max) continue;

					assert(r.given < r.max);

					max_used = std::max(max_used, (size_type)r.used + 1);
					total_used += (size_type)r.used + 1;
				}

				size_type kNumer = resources_to_distribute;
				size_type kDenom = total_used;

				if (kNumer * max_used <= kDenom)
				{
					kNumer = 1;
					kDenom = max_used;
				}

				for (It i = start; i != end && resources_to_distribute > 0; ++i)
				{
					resource_request& r = (*i).*res;
					if(r.given == r.max) continue;

					assert(r.given < r.max);

					size_type used = (size_type)r.used + 1;
					size_type toGive = used * kNumer / kDenom;
					if(toGive > std::numeric_limits<int>::max())
						toGive = std::numeric_limits<int>::max();
					resources_to_distribute -= give(r, (int)toGive);
				}

				assert(resources_to_distribute >= 0);
			}
		}

		peer_connection& pick_peer(
			std::pair<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> > const& p)
		{
			return *p.second;
		}

		peer_connection& pick_peer2(
			std::pair<address, peer_connection*> const& p)
		{
			return *p.second;
		}

		torrent& deref(std::pair<sha1_hash, boost::shared_ptr<torrent> > const& p)
		{
			return *p.second;
		}

	} // namespace anonymous

/*
	void allocate_resources(
		int resources
		, std::map<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> >& c
		, resource_request peer_connection::* res)
	{
		typedef std::map<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> >::iterator orig_iter;
		typedef std::pair<boost::shared_ptr<socket>, boost::shared_ptr<peer_connection> > in_param;
		typedef boost::transform_iterator<peer_connection& (*)(in_param const&), orig_iter> new_iter;

		allocate_resources_impl(
			resources
			, new_iter(c.begin(), &pick_peer)
			, new_iter(c.end(), &pick_peer)
			, res);
	}
*/
#if defined(_MSC_VER) && _MSC_VER < 1310

	namespace detail
	{
		struct iterator_wrapper
		{
			typedef std::map<sha1_hash, boost::shared_ptr<torrent> >::iterator orig_iter;

			orig_iter iter;

			iterator_wrapper(orig_iter i): iter(i) {}
			void operator++() { ++iter; }
			torrent& operator*() { return *(iter->second); }
			bool operator==(const iterator_wrapper& i) const
			{ return iter == i.iter; }
			bool operator!=(const iterator_wrapper& i) const
			{ return iter != i.iter; }
		};

		struct iterator_wrapper2
		{
			typedef std::map<address, peer_connection*>::iterator orig_iter;

			orig_iter iter;

			iterator_wrapper2(orig_iter i): iter(i) {}
			void operator++() { ++iter; }
			peer_connection& operator*() { return *(iter->second); }
			bool operator==(const iterator_wrapper2& i) const
			{ return iter == i.iter; }
			bool operator!=(const iterator_wrapper2& i) const
			{ return iter != i.iter; }
		};

	}

	void allocate_resources(
		int resources
		, std::map<sha1_hash, boost::shared_ptr<torrent> >& c
		, resource_request torrent::* res)
	{
		allocate_resources_impl(
			resources
			, detail::iterator_wrapper(c.begin())
			, detail::iterator_wrapper(c.end())
			, res);
	}

	void allocate_resources(
		int resources
		, std::map<address, peer_connection*>& c
		, resource_request peer_connection::* res)
	{
		allocate_resources_impl(
			resources
			, detail::iterator_wrapper2(c.begin())
			, detail::iterator_wrapper2(c.end())
			, res);
	}

#else

	void allocate_resources(
		int resources
		, std::map<sha1_hash, boost::shared_ptr<torrent> >& c
		, resource_request torrent::* res)
	{
		typedef std::map<sha1_hash, boost::shared_ptr<torrent> >::iterator orig_iter;
		typedef std::pair<sha1_hash, boost::shared_ptr<torrent> > in_param;
		typedef boost::transform_iterator<torrent& (*)(in_param const&), orig_iter> new_iter;

		allocate_resources_impl(
			resources
			, new_iter(c.begin(), &deref)
			, new_iter(c.end(), &deref)
			, res);
	}

	void allocate_resources(
		int resources
		, std::map<address, peer_connection*>& c
		, resource_request peer_connection::* res)
	{
		typedef std::map<address, peer_connection*>::iterator orig_iter;
		typedef std::pair<address, peer_connection*> in_param;
		typedef boost::transform_iterator<peer_connection& (*)(in_param const&), orig_iter> new_iter;

		allocate_resources_impl(
			resources
			, new_iter(c.begin(), &pick_peer2)
			, new_iter(c.end(), &pick_peer2)
			, res);
	}
#endif

} // namespace libtorrent
<|endoftext|>


<commit_before>// Copyright (c) 2011-2014 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "call_graph.h"
#include "function.h"
#include "function_statistics.h"

namespace amxprof {

namespace {

class Deleter : public CallGraph::Visitor {
 public:
  virtual void Visit(const CallGraphNode *node) {
    delete node;
  }
};

} // anonymous namespace

bool CallGraph::CompareStats::operator()(const FunctionStatistics *lhs,
                                         const FunctionStatistics *rhs) const {
  return lhs->function()->address() < rhs->function()->address();
}

CallGraph::CallGraph(CallGraphNode *root)
 : root_(root),
   sentinel_(new CallGraphNode(this, 0))
{
  if (!root) {
    root_ = sentinel_;
  }
}

CallGraph::~CallGraph() {
  Deleter deleter;
  Traverse(&deleter);
}

CallGraphNode *CallGraph::AddCallee(FunctionStatistics *stats) {
  Nodes::iterator iterator = nodes_.find(stats);
  if (iterator == nodes_.end()) {
    CallGraphNode *node = new CallGraphNode(this, stats, root_);
    nodes_.insert(std::make_pair(stats, node));
    return root_->AddCallee(node);
  }
  return root_->AddCallee(iterator->second);
}

void CallGraph::Traverse(Visitor *visitor) const {
  visitor->Visit(sentinel_);
  for (Nodes::const_iterator iterator = nodes_.begin();
       iterator != nodes_.end(); ++iterator) {
    visitor->Visit(iterator->second);
  }
}

CallGraphNode::CallGraphNode(CallGraph *graph, FunctionStatistics *stats, CallGraphNode *caller)
 : graph_(graph),
   stats_(stats),
   caller_(caller)
{
}

CallGraphNode *CallGraphNode::AddCallee(CallGraphNode *node) {
  callees_.insert(node);
  return node;
}

} // namespace amxprof
<commit_msg>Fix crash when adding node to CG without root<commit_after>// Copyright (c) 2011-2014 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#include "call_graph.h"
#include "function.h"
#include "function_statistics.h"

namespace amxprof {

namespace {

class Deleter : public CallGraph::Visitor {
 public:
  virtual void Visit(const CallGraphNode *node) {
    delete node;
  }
};

} // anonymous namespace

bool CallGraph::CompareStats::operator()(const FunctionStatistics *lhs,
                                         const FunctionStatistics *rhs) const {
  return lhs->function()->address() < rhs->function()->address();
}

CallGraph::CallGraph(CallGraphNode *root)
 : root_(root),
   sentinel_(new CallGraphNode(this, 0))
{
  if (!root) {
    root_ = sentinel_;
  }
}

CallGraph::~CallGraph() {
  Deleter deleter;
  Traverse(&deleter);
}

CallGraphNode *CallGraph::AddCallee(FunctionStatistics *stats) {
  CallGraphNode *node = 0;
  Nodes::iterator iterator = nodes_.find(stats);
  if (iterator == nodes_.end()) {
    node = new CallGraphNode(this, stats, root_);
    nodes_.insert(std::make_pair(stats, node));
  } else {
    node = iterator->second;
  }
  return root_ != 0 ? root_->AddCallee(node) : node;
}

void CallGraph::Traverse(Visitor *visitor) const {
  visitor->Visit(sentinel_);
  for (Nodes::const_iterator iterator = nodes_.begin();
       iterator != nodes_.end(); ++iterator) {
    visitor->Visit(iterator->second);
  }
}

CallGraphNode::CallGraphNode(CallGraph *graph,
                             FunctionStatistics *stats,
                             CallGraphNode *caller)
 : graph_(graph),
   stats_(stats),
   caller_(caller)
{
}

CallGraphNode *CallGraphNode::AddCallee(CallGraphNode *node) {
  callees_.insert(node);
  return node;
}

} // namespace amxprof
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/*
 *  IgbFiletoMatrix_Plugin.cc
 *
 *  Written by:
 *   Karli Gillette
 *   Department of Bioengineering
 *   University of Utah
 *
 */

#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/IEPlugin/IgbFileToMatrix_Plugin.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/Utils/Legacy/StringUtil.h>
#include <Core/Logging/LoggerInterface.h>
#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/Datatypes/DenseMatrix.h>

#include <string.h>
#include <stdlib.h>
#include <string>
#include <stdio.h>
#include <vector>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/iter_find.hpp>
#include <cmath>

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;
using namespace SCIRun;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core::Datatypes;

MatrixHandle SCIRun::IgbFileMatrix_reader(LoggerHandle pr, const char *filename)
{

    string line;
    vector<string> strs;
    int x_size=0;
    int t_size=0;
    int count=0;

    ifstream myfile (filename);
    if (myfile.is_open())
    {
        //while ( myfile.good() )
        for(int i=0; i<5; i++)
        {
            getline (myfile,line);

            boost::split(strs,line,boost::is_any_of(":, "));
            size_t sz;
            sz=line.size();

            for(int p=0;p<sz;p++)
            {

               std::cout << p << std::endl;

                if (boost::iequals(strs[p], "x"))
                {
                    x_size=atoi(strs[p+1].c_str());

                    count += 1;

                }
                if (boost::iequals(strs[p], "t"))
                {
                    t_size=atoi(strs[p+1].c_str());

                    count +=1;

                }

                if (count ==2 ) break;

            }

        	}
        myfile.close();
    }

        streamoff length=0;
        streamsize numbyts=0;
        //char * buffer;

        ifstream is;
        is.open (filename, ios::in |  ios::binary );
        if (is.is_open())
        {
            // get length of file:
            is.seekg (0, ios::end);
            length = is.tellg();
            is.seekg (1024, ios::beg);

            vector<float> vec;
            vec.resize(x_size*t_size);

            is.read ((char*)&vec[0],x_size * t_size * sizeof(float));
            if (!is)
            {
                numbyts=is.gcount();
                cout << "Error reading binary data. Number of bytes read: " << numbyts << endl;

            }
            is.close();

            // auto result(boost::make_shared<DenseMatrix>(x_size,t_size));

            DenseMatrixHandle result;

            result.reset(new DenseMatrix(x_size,t_size));

                for(size_t p=0;p<t_size;p++ )
                {

                    for(size_t pp=0;pp<x_size;pp++ )
                    {

                        (*result)(pp, p) = vec[(p*x_size)+pp];

                    }
                }

        return(result);
        }
}

<commit_msg>Changes to IGB importer to allow for imcomplete files<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/*
 *  IgbFiletoMatrix_Plugin.cc
 *
 *  Written by:
 *   Karli Gillette
 *   Department of Bioengineering
 *   University of Utah
 *
 */

#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/IEPlugin/IgbFileToMatrix_Plugin.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/Utils/Legacy/StringUtil.h>
#include <Core/Logging/LoggerInterface.h>
#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/Datatypes/DenseMatrix.h>

#include <string.h>
#include <stdlib.h>
#include <string>
#include <stdio.h>
#include <vector>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/iter_find.hpp>
#include <cmath>

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;
using namespace SCIRun;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Logging;
using namespace SCIRun::Core::Datatypes;

MatrixHandle SCIRun::IgbFileMatrix_reader(LoggerHandle pr, const char *filename)
{

    string line;
    vector<string> strs;
    int x_size=0;
    int t_size=0;
    int count=0;

    ifstream myfile (filename);
    if (myfile.is_open())
    {
        //while ( myfile.good() )
        for(int i=0; i<5; i++)
        {
            getline (myfile,line);

            boost::split(strs,line,boost::is_any_of(":, "));
            size_t sz;
            sz=line.size();

            for(int p=0;p<sz;p++)
            {

               std::cout << p << std::endl;

                if (boost::iequals(strs[p], "x"))
                {
                    x_size=atoi(strs[p+1].c_str());
                    count += 1;

                }
                if (boost::iequals(strs[p], "t"))
                {
                    t_size=atoi(strs[p+1].c_str());
                    count +=1;

                }

                if (count ==2 ) break;

            }

        	}
        myfile.close();
    }

        streamoff length=0;
        streamsize numbyts=0;
        //char * buffer;

        ifstream is;
        is.open (filename, ios::in |  ios::binary );
        if (is.is_open())
        {
            // get length of file:
            is.seekg (0, ios::end);
            length = is.tellg();
            is.seekg (1024, ios::beg);
             t_size=t_size;
            length=length-1024;

            vector<float> vec;
            vec.resize(length);
            is.read ((char*)&vec[0],length);

            if (!is)
            {
                numbyts=is.gcount();
                cout << "Error reading binary data. Number of bytes read: " << numbyts << endl;

            }
            is.close();

           auto result(boost::make_shared<DenseMatrix>(x_size,t_size));

                for(size_t p=0;p<t_size;p++ )
                {

                    for(size_t pp=0;pp<x_size;pp++ )
                    {

                        (*result)(pp, p) = vec[(p*x_size)+pp];

                    }
                }

        return(result);
        }
}

<|endoftext|>