<commit_before>//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>

#include "paddle/fluid/framework/details/all_reduce_op_handle.h"
#include "paddle/fluid/framework/details/container_cast.h"
#include "paddle/fluid/framework/details/reduce_and_gather.h"
#include "paddle/fluid/framework/details/variable_visitor.h"
#include "paddle/fluid/platform/profiler.h"

namespace paddle {
namespace framework {
namespace details {

#if defined(PADDLE_WITH_CUDA) && !defined(_WIN32)
AllReduceOpHandle::AllReduceOpHandle(ir::Node *node,
                                     const std::vector<Scope *> &local_scopes,
                                     const std::vector<platform::Place> &places,
                                     const platform::NCCLContextMap *ctxs)
    : OpHandleBase(node),
      local_scopes_(local_scopes),
      places_(places),
      nccl_ctxs_(ctxs) {
  if (nccl_ctxs_) {
    for (auto &p : places_) {
      this->SetDeviceContext(p, nccl_ctxs_->DevCtx(p));
    }
  }
}
#else
AllReduceOpHandle::AllReduceOpHandle(ir::Node *node,
                                     const std::vector<Scope *> &local_scopes,
                                     const std::vector<platform::Place> &places)
    : OpHandleBase(node), local_scopes_(local_scopes), places_(places) {}
#endif

void AllReduceOpHandle::RunImpl() {
  platform::RecordEvent record_event(Name(), dev_ctxes_.cbegin()->second);

// FIXME(typhoonzero): If scope0(global scope) have NCCL_ID_VAR,
// this is a distributed or inter-process call, find a better way.
#ifdef PADDLE_WITH_CUDA
  if (NoDummyInputSize() == 1 &&
      local_scopes_[0]->FindVar(NCCL_ID_VARNAME) == nullptr) {
#else
  if (NoDummyInputSize() == 1) {
#endif
    return;  // No need to all reduce when GPU count = 1;
  } else {
    // Wait input done
    WaitInputVarGenerated();
    auto in_var_handles = DynamicCast<VarHandle>(this->Inputs());
    auto out_var_handles = DynamicCast<VarHandle>(this->Outputs());
    PADDLE_ENFORCE_EQ(
        in_var_handles.size(), places_.size(),
        "The NoDummyInputSize should be equal to the number of places.");
    PADDLE_ENFORCE_EQ(
        in_var_handles.size(), out_var_handles.size(),
        "The NoDummyInputSize and NoDummyOutputSize should be equal.");

    std::vector<const LoDTensor *> lod_tensors;
    for (size_t i = 0; i < local_scopes_.size(); ++i) {
      auto *s = local_scopes_[i];
      auto &local_scope = *s->FindVar(kLocalExecScopeName)->Get<Scope *>();
      auto &lod_tensor =
          local_scope.FindVar(in_var_handles[i]->name_)->Get<LoDTensor>();
      lod_tensors.emplace_back(&lod_tensor);
      PADDLE_ENFORCE_EQ(in_var_handles[i]->name_, out_var_handles[i]->name_,
                        "The name of input and output should be equal.");
    }

    if (platform::is_gpu_place(lod_tensors[0]->place())) {
#if defined(PADDLE_WITH_CUDA) && !defined(_WIN32)
      PADDLE_ENFORCE(nccl_ctxs_, "nccl_ctxs should not be nullptr.");
      int dtype = -1;
      size_t numel = 0;
      std::vector<std::function<void()>> all_reduce_calls;
      for (size_t i = 0; i < local_scopes_.size(); ++i) {
        auto &p = places_[i];
        auto &lod_tensor = *lod_tensors[i];
        void *buffer = const_cast<void *>(lod_tensor.data<void>());

        if (dtype == -1) {
          dtype = platform::ToNCCLDataType(lod_tensor.type());
        }

        if (numel == 0) {
          numel = static_cast<size_t>(lod_tensor.numel());
        }

        int dev_id = boost::get<platform::CUDAPlace>(p).device;
        auto &nccl_ctx = nccl_ctxs_->at(dev_id);
        auto stream = nccl_ctx.stream();
        auto comm = nccl_ctx.comm_;
        all_reduce_calls.emplace_back([=] {
          PADDLE_ENFORCE(platform::dynload::ncclAllReduce(
              buffer, buffer, numel, static_cast<ncclDataType_t>(dtype),
              ncclSum, comm, stream));
        });
      }

      this->RunAndRecordEvent([&] {
        // TODO(Yancey1989): need allreduce operator to avoid this flag
        if (nccl_ctxs_->need_group_call_) {
          platform::NCCLGroupGuard guard;
          for (auto &call : all_reduce_calls) {
            call();
          }
        } else {
          // only used in executor_type == ParallalGraph, one thread one GPU
          // TODO(Yancey1989): use allreduce operator to avoid this tricky.
          PADDLE_ENFORCE(all_reduce_calls.size() == 1UL);
          all_reduce_calls[0]();
        }
      });

#else
      PADDLE_THROW("Not compiled with CUDA");
#endif
    } else {  // Special handle CPU only Operator's gradient. Like CRF
      auto &trg = *this->local_scopes_[0]
                       ->FindVar(kLocalExecScopeName)
                       ->Get<Scope *>()
                       ->FindVar(out_var_handles[0]->name_)
                       ->GetMutable<framework::LoDTensor>();

      // Reduce All Tensor to trg in CPU
      ReduceLoDTensor func(lod_tensors, &trg);
      VisitDataType(ToDataType(lod_tensors[0]->type()), func);

      for (size_t i = 1; i < local_scopes_.size(); ++i) {
        auto &scope =
            *local_scopes_[i]->FindVar(kLocalExecScopeName)->Get<Scope *>();
        auto &p = places_[i];
        auto *var = scope.FindVar(out_var_handles[i]->name_);
        auto *dev_ctx = dev_ctxes_.at(p);

        RunAndRecordEvent(p, [&trg, var, dev_ctx, p] {
          auto &tensor_gpu = *var->GetMutable<framework::LoDTensor>();
          auto &tensor_cpu = trg;
          TensorCopy(tensor_cpu, p, *dev_ctx, &tensor_gpu);
        });
      }
    }
  }
}

std::string AllReduceOpHandle::Name() const { return "all_reduce"; }
}  // namespace details
}  // namespace framework
}  // namespace paddle
<commit_msg>fix performance<commit_after>//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>

#include "paddle/fluid/framework/details/all_reduce_op_handle.h"
#include "paddle/fluid/framework/details/container_cast.h"
#include "paddle/fluid/framework/details/reduce_and_gather.h"
#include "paddle/fluid/framework/details/variable_visitor.h"
#include "paddle/fluid/platform/profiler.h"

namespace paddle {
namespace framework {
namespace details {

#if defined(PADDLE_WITH_CUDA) && !defined(_WIN32)
AllReduceOpHandle::AllReduceOpHandle(ir::Node *node,
                                     const std::vector<Scope *> &local_scopes,
                                     const std::vector<platform::Place> &places,
                                     const platform::NCCLContextMap *ctxs)
    : OpHandleBase(node),
      local_scopes_(local_scopes),
      places_(places),
      nccl_ctxs_(ctxs) {
  if (nccl_ctxs_) {
    for (auto &p : places_) {
      this->SetDeviceContext(p, nccl_ctxs_->DevCtx(p));
    }
  }
}
#else
AllReduceOpHandle::AllReduceOpHandle(ir::Node *node,
                                     const std::vector<Scope *> &local_scopes,
                                     const std::vector<platform::Place> &places)
    : OpHandleBase(node), local_scopes_(local_scopes), places_(places) {}
#endif

void AllReduceOpHandle::RunImpl() {
  platform::RecordEvent record_event(Name(), dev_ctxes_.cbegin()->second);

// FIXME(typhoonzero): If scope0(global scope) have NCCL_ID_VAR,
// this is a distributed or inter-process call, find a better way.
#ifdef PADDLE_WITH_CUDA
  if (NoDummyInputSize() == 1 &&
      local_scopes_[0]->FindVar(NCCL_ID_VARNAME) == nullptr) {
#else
  if (NoDummyInputSize() == 1) {
#endif
    return;  // No need to all reduce when GPU count = 1;
  } else {
    // Wait input done
    WaitInputVarGenerated();
    auto in_var_handles = DynamicCast<VarHandle>(this->Inputs());
    auto out_var_handles = DynamicCast<VarHandle>(this->Outputs());
    PADDLE_ENFORCE_EQ(
        in_var_handles.size(), places_.size(),
        "The NoDummyInputSize should be equal to the number of places.");
    PADDLE_ENFORCE_EQ(
        in_var_handles.size(), out_var_handles.size(),
        "The NoDummyInputSize and NoDummyOutputSize should be equal.");

    std::vector<const LoDTensor *> lod_tensors;
    for (size_t i = 0; i < local_scopes_.size(); ++i) {
      auto *s = local_scopes_[i];
      auto &local_scope = *s->FindVar(kLocalExecScopeName)->Get<Scope *>();
      auto &lod_tensor =
          local_scope.FindVar(in_var_handles[i]->name_)->Get<LoDTensor>();
      lod_tensors.emplace_back(&lod_tensor);
      PADDLE_ENFORCE_EQ(in_var_handles[i]->name_, out_var_handles[i]->name_,
                        "The name of input and output should be equal.");
    }

    if (platform::is_gpu_place(lod_tensors[0]->place())) {
#if defined(PADDLE_WITH_CUDA) && !defined(_WIN32)
      PADDLE_ENFORCE(nccl_ctxs_, "nccl_ctxs should not be nullptr.");
      int dtype = -1;
      size_t numel = 0;
      std::vector<std::function<void()>> all_reduce_calls;
      for (size_t i = 0; i < local_scopes_.size(); ++i) {
        auto &p = places_[i];
        auto &lod_tensor = *lod_tensors[i];
        void *buffer = const_cast<void *>(lod_tensor.data<void>());

        if (dtype == -1) {
          dtype = platform::ToNCCLDataType(lod_tensor.type());
        }

        if (numel == 0) {
          numel = static_cast<size_t>(lod_tensor.numel());
        }

        int dev_id = boost::get<platform::CUDAPlace>(p).device;
        auto &nccl_ctx = nccl_ctxs_->at(dev_id);
        auto stream = nccl_ctx.stream();
        auto comm = nccl_ctx.comm_;
        all_reduce_calls.emplace_back([=] {
          PADDLE_ENFORCE(platform::dynload::ncclAllReduce(
              buffer, buffer, numel, static_cast<ncclDataType_t>(dtype),
              ncclSum, comm, stream));
          if (!nccl_ctxs_->need_group_call_) cudaStreamSynchronize(stream);
        });
      }

      this->RunAndRecordEvent([&] {
        // TODO(Yancey1989): need allreduce operator to avoid this flag
        if (nccl_ctxs_->need_group_call_) {
          platform::NCCLGroupGuard guard;
          for (auto &call : all_reduce_calls) {
            call();
          }
        } else {
          // only used in executor_type == ParallalGraph, one thread one GPU
          // TODO(Yancey1989): use allreduce operator to avoid this tricky.
          PADDLE_ENFORCE(all_reduce_calls.size() == 1UL);
          all_reduce_calls[0]();
        }
      });

#else
      PADDLE_THROW("Not compiled with CUDA");
#endif
    } else {  // Special handle CPU only Operator's gradient. Like CRF
      auto &trg = *this->local_scopes_[0]
                       ->FindVar(kLocalExecScopeName)
                       ->Get<Scope *>()
                       ->FindVar(out_var_handles[0]->name_)
                       ->GetMutable<framework::LoDTensor>();

      // Reduce All Tensor to trg in CPU
      ReduceLoDTensor func(lod_tensors, &trg);
      VisitDataType(ToDataType(lod_tensors[0]->type()), func);

      for (size_t i = 1; i < local_scopes_.size(); ++i) {
        auto &scope =
            *local_scopes_[i]->FindVar(kLocalExecScopeName)->Get<Scope *>();
        auto &p = places_[i];
        auto *var = scope.FindVar(out_var_handles[i]->name_);
        auto *dev_ctx = dev_ctxes_.at(p);

        RunAndRecordEvent(p, [&trg, var, dev_ctx, p] {
          auto &tensor_gpu = *var->GetMutable<framework::LoDTensor>();
          auto &tensor_cpu = trg;
          TensorCopy(tensor_cpu, p, *dev_ctx, &tensor_gpu);
        });
      }
    }
  }
}

std::string AllReduceOpHandle::Name() const { return "all_reduce"; }
}  // namespace details
}  // namespace framework
}  // namespace paddle
<|endoftext|>


<commit_before>// Copyright (c) 2015-2017 Matthew Sitton <matthewsitton@gmail.com>
// See LICENSE in the project root for license information.

#pragma once
#include "streams.hpp"

namespace ORCore
{
    class CubebOutput: public Consumer
    {
    public:
        bool start();
        void stop();

        bool set_stream(Stream* stream)
        {
            m_stream = stream;
        }

    private:
        Stream* m_stream;
    };
}<commit_msg>include cubeb header to make sure builds are setup properly.<commit_after>// Copyright (c) 2015-2017 Matthew Sitton <matthewsitton@gmail.com>
// See LICENSE in the project root for license information.

#pragma once
#include "streams.hpp"

#include "cubeb/cubeb.h"

namespace ORCore
{
    class CubebOutput: public Consumer
    {
    public:
        bool start();
        void stop();

        bool set_stream(Stream* stream)
        {
            m_stream = stream;
        }

    private:
        Stream* m_stream;
    };
}<|endoftext|>


<commit_before>#include "S3StreamDefaults.h"
#include <ossim/base/ossimPreferences.h>

// defaults to a 1 megabyte block size
//
ossim_int64 ossim::S3StreamDefaults::m_readBlocksize = 1048576;

void ossim::S3StreamDefaults::loadDefaults()
{
   ossimString s3ReadBlocksize = ossimPreferences::instance()->findPreference("ossim.plugins.aws.s3.readBlocksize");

   if(!s3ReadBlocksize.empty())
   {
     ossim_int64 blockSize = s3ReadBlocksize.toInt64();
     if(blockSize > 0)
     {
         ossimString byteType(s3ReadBlocksize.begin()+(s3ReadBlocksize.size()-1), s3ReadBlocksize.end());
         byteType.upcase();
         m_readBlocksize = blockSize;
         if ( byteType == "K")
         {
            m_readBlocksize *=static_cast<ossim_int64>(1024);
         }
         else if ( byteType == "M")
         {
            m_readBlocksize *=static_cast<ossim_int64>(1048576);
         }
         else if ( byteType == "G")
         {
            m_readBlocksize *=static_cast<ossim_int64>(1073741824);
         }
         std::cout << "SET TO " << m_readBlocksize << " bytes\n";
     }
   }

}
<commit_msg>Remove print statement<commit_after>#include "S3StreamDefaults.h"
#include <ossim/base/ossimPreferences.h>

// defaults to a 1 megabyte block size
//
ossim_int64 ossim::S3StreamDefaults::m_readBlocksize = 1048576;

void ossim::S3StreamDefaults::loadDefaults()
{
   ossimString s3ReadBlocksize = ossimPreferences::instance()->findPreference("ossim.plugins.aws.s3.readBlocksize");

   if(!s3ReadBlocksize.empty())
   {
     ossim_int64 blockSize = s3ReadBlocksize.toInt64();
     if(blockSize > 0)
     {
         ossimString byteType(s3ReadBlocksize.begin()+(s3ReadBlocksize.size()-1), s3ReadBlocksize.end());
         byteType.upcase();
         m_readBlocksize = blockSize;
         if ( byteType == "K")
         {
            m_readBlocksize *=static_cast<ossim_int64>(1024);
         }
         else if ( byteType == "M")
         {
            m_readBlocksize *=static_cast<ossim_int64>(1048576);
         }
         else if ( byteType == "G")
         {
            m_readBlocksize *=static_cast<ossim_int64>(1073741824);
         }
     }
   }

}
<|endoftext|>


<commit_before>#pragma once

#include <stdint.h>

/* Comment out this line for a non-test network */
#define BTS_TEST_NETWORK
#define BTS_TEST_NETWORK_VERSION                            6 // autogenerated

/** @file bts/blockchain/config.hpp
 *  @brief Defines global constants that determine blockchain behavior
 */
#define BTS_BLOCKCHAIN_VERSION                              2
#define BTS_BLOCKCHAIN_DATABASE_VERSION                     6

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                                  "XTS"
#define BTS_BLOCKCHAIN_SYMBOL                               "XTS"
#define BTS_BLOCKCHAIN_NAME                                 "BitShares PLAY XTS"
#define BTS_BLOCKCHAIN_DESCRIPTION                          "BitShares PLAY Test Network"

#define BTS_BLOCKCHAIN_PRECISION                            100000
#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC       (60*60*24*2)
#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC                 (60*60*24) // 24 hours

#define BTS_BLOCKCHAIN_MIN_BURN_FEE                         BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE                    10000 // XTS
#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE             (BTS_BLOCKCHAIN_PRECISION*100)

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (2*60*60) // 2 hours
#else
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (30*24*60*60) // 1 month
#endif

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               40
#else
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               (60*60) // 1 hour
#endif

/**
 * The number of delegates that the blockchain is designed to support
 */
#define BTS_BLOCKCHAIN_HOUSE_EDGE                           (1) // 1% house edge
#define BTS_BLOCKCHAIN_NUM_DELEGATES                        uint32_t(101)
#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE                       (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES/10))
#define BTS_BLOCKCHAIN_MIN_FEEDS                            ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1)
#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY                     (BTS_BLOCKCHAIN_NUM_DELEGATES*4)

#define BTS_BLOCKCHAIN_ENABLE_NEGATIVE_VOTES                false

#define BTS_MAX_DELEGATE_PAY_PER_BLOCK                      int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) // 50 XTS

/**
 * To prevent a delegate from producing blocks on split network,
 * we check the connection count.  This means no blocks get produced
 * until at least a minimum number of clients are on line.
 */
#define BTS_MIN_DELEGATE_CONNECTION_COUNT                   1

/**
 * Defines the number of seconds that should elapse between blocks
 */
#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC                   int64_t(10)

/**
 *  The maximum size of the raw data contained in the blockchain, this size is
 *  notional based upon the serilized size of all user-generated transactions in
 *  all blocks for one year.
 *
 *  Actual size on disk will likely be 2 or 3x this size due to indexes and other
 *  storeage overhead.
 *
 *  Adjusting this value will change the effective fee charged on transactions
 */
#define BTS_BLOCKCHAIN_MAX_SIZE                             (1024*1024*1024*int64_t(100)) // 100 GB
#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                        1
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                        63
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE                   (1024*64)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                        19 // bytes
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                      8 // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                      3 // characters

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1  however, to support representing all share values as a double in
 *  languages like java script, we must stay within the epsilon so
 *
 *  10^15 / 2^53 < 1 allows all values to be represented as a double or an int64
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                           (1000*1000*int64_t(1000)*1000*int64_t(1000))

/**
 * Initial shares read from the genesis block are scaled to this number. It is divided
 * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES
 */
#define BTS_BLOCKCHAIN_INITIAL_SHARES                       (BTS_BLOCKCHAIN_MAX_SHARES/5)

/**
 *  The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                      ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/**
 *  The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                       (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))

/**
 * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                      (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))

#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE                     512 // just a random assumption used to calibrate TRX per SEC
#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND                   1  // (10)
#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE               10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE                       (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )

/**
    This constant defines the number of blocks a delegate must produce before
    they are expected to break even on registration costs with their earned income.

 *   Currently set to 2 hours of active block production to break even.
 */
#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE            (BTS_BLOCKCHAIN_BLOCKS_PER_DAY/12)

/**
    If you are going to create an asset, you expect that it will be used in transactions.  We would
    like to limit the issuance of assets that have no demand for transactions, so we charge a fee
    proportional to average transaction fees included in a block (AKA delegate pay).  This constant
    defines the number of blocks worth of transactions that justify the creation of a new asset.

    The fee is set such that the transactions of this asset alone could justify filling up 2 full weeks of
    block production.
 */
#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE               (BTS_BLOCKCHAIN_BLOCKS_PER_DAY * 14)
<commit_msg>revert bad commit<commit_after>#pragma once

#include <stdint.h>

/* Comment out this line for a non-test network */
#define BTS_TEST_NETWORK
#define BTS_TEST_NETWORK_VERSION                            5 // autogenerated

/** @file bts/blockchain/config.hpp
 *  @brief Defines global constants that determine blockchain behavior
 */
#define BTS_BLOCKCHAIN_VERSION                              1
#define BTS_BLOCKCHAIN_DATABASE_VERSION                     5

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                                  "PLS"
#define BTS_BLOCKCHAIN_SYMBOL                               "PLS"
#define BTS_BLOCKCHAIN_NAME                                 "BitShares PLS"
#define BTS_BLOCKCHAIN_DESCRIPTION                          "BitShares PLAY Test Network"

#define BTS_BLOCKCHAIN_PRECISION                            100000
#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC       (60*60*24*2)
#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC                 (60*60*24) // 24 hours

#define BTS_BLOCKCHAIN_MIN_BURN_FEE                         BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE                    10000 // XTS
#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE             (BTS_BLOCKCHAIN_PRECISION*100)

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (2*60*60) // 2 hours
#else
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (30*24*60*60) // 1 month
#endif

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               40
#else
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               (60*60) // 1 hour
#endif

/**
 * The number of delegates that the blockchain is designed to support
 */
#define BTS_BLOCKCHAIN_HOUSE_EDGE                           (1) // 1% house edge
#define BTS_BLOCKCHAIN_NUM_DELEGATES                        uint32_t(101)
#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE                       (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES/10))
#define BTS_BLOCKCHAIN_MIN_FEEDS                            ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1)
#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY                     (BTS_BLOCKCHAIN_NUM_DELEGATES*4)

#define BTS_BLOCKCHAIN_ENABLE_NEGATIVE_VOTES                false

#define BTS_MAX_DELEGATE_PAY_PER_BLOCK                      int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) // 50 XTS

/**
 * To prevent a delegate from producing blocks on split network,
 * we check the connection count.  This means no blocks get produced
 * until at least a minimum number of clients are on line.
 */
#define BTS_MIN_DELEGATE_CONNECTION_COUNT                   1

/**
 * Defines the number of seconds that should elapse between blocks
 */
#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC                   int64_t(10)

/**
 *  The maximum size of the raw data contained in the blockchain, this size is
 *  notional based upon the serilized size of all user-generated transactions in
 *  all blocks for one year.
 *
 *  Actual size on disk will likely be 2 or 3x this size due to indexes and other
 *  storeage overhead.
 *
 *  Adjusting this value will change the effective fee charged on transactions
 */
#define BTS_BLOCKCHAIN_MAX_SIZE                             (1024*1024*1024*int64_t(100)) // 100 GB
#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                        1
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                        63
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE                   (1024*64)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                        19 // bytes
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                      8 // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                      3 // characters

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1  however, to support representing all share values as a double in
 *  languages like java script, we must stay within the epsilon so
 *
 *  10^15 / 2^53 < 1 allows all values to be represented as a double or an int64
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                           (1000*1000*int64_t(1000)*1000*int64_t(1000))

/**
 * Initial shares read from the genesis block are scaled to this number. It is divided
 * by 100 so that new shares may be issued without exceeding BTS_BLOCKCHAIN_MAX_SHARES
 */
#define BTS_BLOCKCHAIN_INITIAL_SHARES                       (BTS_BLOCKCHAIN_MAX_SHARES/5)

/**
 *  The number of blocks expected per hour based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                      ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/**
 *  The number of blocks expected per day based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                       (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))

/**
 * The number of blocks expected per year based upon the BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC
 */
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                      (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))

#define BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE                     512 // just a random assumption used to calibrate TRX per SEC
#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND                   1  // (10)
#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE               10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)

/** defines the maximum block size allowed, 2 MB per hour */
#define BTS_BLOCKCHAIN_MAX_BLOCK_SIZE                       (10 * BTS_BLOCKCHAIN_AVERAGE_TRX_SIZE * BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE )

/**
    This constant defines the number of blocks a delegate must produce before
    they are expected to break even on registration costs with their earned income.

 *   Currently set to 2 hours of active block production to break even.
 */
#define BTS_BLOCKCHAIN_DELEGATE_REGISTRATION_FEE            (BTS_BLOCKCHAIN_BLOCKS_PER_DAY/12)

/**
    If you are going to create an asset, you expect that it will be used in transactions.  We would
    like to limit the issuance of assets that have no demand for transactions, so we charge a fee
    proportional to average transaction fees included in a block (AKA delegate pay).  This constant
    defines the number of blocks worth of transactions that justify the creation of a new asset.

    The fee is set such that the transactions of this asset alone could justify filling up 2 full weeks of
    block production.
 */
#define BTS_BLOCKCHAIN_ASSET_REGISTRATION_FEE               (BTS_BLOCKCHAIN_BLOCKS_PER_DAY * 14)
<|endoftext|>


<commit_before>#pragma once

#include <stdint.h>

/* Comment out this line for a non-test network */
// #define BTS_TEST_NETWORK
// #define BTS_TEST_NETWORK_VERSION                            10 // autogenerated

#define BTS_TEST_NETWORK_VERSION                            23 // autogenerated
#define BTS_BLOCKCHAIN_DATABASE_VERSION                     uint64_t( 21 )

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                                  "PLS"
#define BTS_BLOCKCHAIN_SYMBOL                               "PLS"
#define BTS_BLOCKCHAIN_NAME                                 "DAC PLAY"
#define BTS_BLOCKCHAIN_DESCRIPTION                          "DAC PLAY Network"

#define BTS_BLOCKCHAIN_PRECISION                            100000

#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC                   int64_t(10)
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                      ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                       (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                      (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))

#define BTS_BLOCKCHAIN_NUM_DELEGATES                        uint32_t(101)
#define BTS_MAX_DELEGATE_PAY_PER_BLOCK                      int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) // 50 XTS
#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY                     ( BTS_BLOCKCHAIN_BLOCKS_PER_HOUR * 3 )

#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE                       (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES/10))
#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC       (60*60*24*2)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                        19 // bytes
#define BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE                   32 // bytes
#define BTS_BLOCKCHAIN_MAX_EXTENDED_MEMO_SIZE               (BTS_BLOCKCHAIN_MAX_MEMO_SIZE + BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE)

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1  however, to support representing all share values as a double in
 *  languages like java script, we must stay within the epsilon so
 *
 *  10^15 / 2^53 < 1 allows all values to be represented as a double or an int64
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                           (1000*1000*int64_t(1000)*1000*int64_t(1000))

#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                        1
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                        63
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE                   (1024*64)

#define BTS_BLOCKCHAIN_MAX_SUB_SYMBOL_SIZE                  8 // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                      3 // characters
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                      12 // characters

#define BTS_BLOCKCHAIN_MIN_BURN_FEE                         BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_NOTE_FEE                         BTS_BLOCKCHAIN_PRECISION * 5 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_AD_FEE                           BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_RED_PACKET_FEE                   BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_RED_PACKET_UNIT                  BTS_BLOCKCHAIN_PRECISION * 1 // XTS

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               10
#else
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               (60*60) // 1 hour
#endif

#define BTS_BLOCKCHAIN_MIN_FEEDS                            ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1)
#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE             (BTS_BLOCKCHAIN_PRECISION*100)
#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC                 (60*60*24) // 24 hours
#define BTS_BLOCKCHAIN_MAX_YIELD_PERIOD_SEC                 (BTS_BLOCKCHAIN_BLOCKS_PER_YEAR * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) // 1 year

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (2*60*60) // 2 hours
#else
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (30*24*60*60) // 1 month
#endif

#define BTS_BLOCKCHAIN_MAX_SHORT_APR_PCT                    uint64_t( 50 )

#define BTS_BLOCKCHAIN_MCALL_D2C_NUMERATOR                  1
#define BTS_BLOCKCHAIN_MCALL_D2C_DENOMINATOR                2

#define BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE              10000

// TODO: This stuff only matters for propagation throttling; should go somewhere else
#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE                    10000 // XTS
#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND                   1  // (10)
#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE               10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)
<commit_msg>update db version<commit_after>#pragma once

#include <stdint.h>

/* Comment out this line for a non-test network */
// #define BTS_TEST_NETWORK
// #define BTS_TEST_NETWORK_VERSION                            10 // autogenerated

#define BTS_TEST_NETWORK_VERSION                            23 // autogenerated
#define BTS_BLOCKCHAIN_DATABASE_VERSION                     uint64_t( 22 )

/**
 *  The address prepended to string representation of
 *  addresses.
 *
 *  Changing these parameters will result in a hard fork.
 */
#define BTS_ADDRESS_PREFIX                                  "PLS"
#define BTS_BLOCKCHAIN_SYMBOL                               "PLS"
#define BTS_BLOCKCHAIN_NAME                                 "DAC PLAY"
#define BTS_BLOCKCHAIN_DESCRIPTION                          "DAC PLAY Network"

#define BTS_BLOCKCHAIN_PRECISION                            100000

#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC                   int64_t(10)
#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR                      ((60*60)/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)
#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY                       (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))
#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR                      (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))

#define BTS_BLOCKCHAIN_NUM_DELEGATES                        uint32_t(101)
#define BTS_MAX_DELEGATE_PAY_PER_BLOCK                      int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) // 50 XTS
#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY                     ( BTS_BLOCKCHAIN_BLOCKS_PER_HOUR * 3 )

#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE                       (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES/10))
#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC       (60*60*24*2)
#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE                        19 // bytes
#define BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE                   32 // bytes
#define BTS_BLOCKCHAIN_MAX_EXTENDED_MEMO_SIZE               (BTS_BLOCKCHAIN_MAX_MEMO_SIZE + BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE)

/**
 *  The maximum amount that can be issued for user assets.
 *
 *  10^18 / 2^63 < 1  however, to support representing all share values as a double in
 *  languages like java script, we must stay within the epsilon so
 *
 *  10^15 / 2^53 < 1 allows all values to be represented as a double or an int64
 */
#define BTS_BLOCKCHAIN_MAX_SHARES                           (1000*1000*int64_t(1000)*1000*int64_t(1000))

#define BTS_BLOCKCHAIN_MIN_NAME_SIZE                        1
#define BTS_BLOCKCHAIN_MAX_NAME_SIZE                        63
#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE                   (1024*64)

#define BTS_BLOCKCHAIN_MAX_SUB_SYMBOL_SIZE                  8 // characters
#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE                      3 // characters
#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE                      12 // characters

#define BTS_BLOCKCHAIN_MIN_BURN_FEE                         BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_NOTE_FEE                         BTS_BLOCKCHAIN_PRECISION * 5 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_AD_FEE                           BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_RED_PACKET_FEE                   BTS_BLOCKCHAIN_PRECISION * 1 // 1 XTS
#define BTS_BLOCKCHAIN_MIN_RED_PACKET_UNIT                  BTS_BLOCKCHAIN_PRECISION * 1 // XTS

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               10
#else
#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC               (60*60) // 1 hour
#endif

#define BTS_BLOCKCHAIN_MIN_FEEDS                            ((BTS_BLOCKCHAIN_NUM_DELEGATES/2) + 1)
#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE             (BTS_BLOCKCHAIN_PRECISION*100)
#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC                 (60*60*24) // 24 hours
#define BTS_BLOCKCHAIN_MAX_YIELD_PERIOD_SEC                 (BTS_BLOCKCHAIN_BLOCKS_PER_YEAR * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) // 1 year

#ifdef BTS_TEST_NETWORK
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (2*60*60) // 2 hours
#else
#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC                 (30*24*60*60) // 1 month
#endif

#define BTS_BLOCKCHAIN_MAX_SHORT_APR_PCT                    uint64_t( 50 )

#define BTS_BLOCKCHAIN_MCALL_D2C_NUMERATOR                  1
#define BTS_BLOCKCHAIN_MCALL_D2C_DENOMINATOR                2

#define BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE_RATE              10000

// TODO: This stuff only matters for propagation throttling; should go somewhere else
#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE                    10000 // XTS
#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND                   1  // (10)
#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE               10 // (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)
<|endoftext|>


<commit_before>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-8-4 22:09:58
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const char ds[4] = {'D', 'R', 'U', 'L'};

typedef tuple<ll, int, int> state;

// const int C = 1e6+10;
const ll infty = 1000000007;

int N, M, K;
string D;
string S[1010];
ll dist[200010][4];
ll ans[1010][1010];

int main()
{
  cin >> N >> M >> K;
  cin >> D;
  D = D + D + D;
  for (auto i = 0; i < N; i++)
  {
    cin >> S[i];
  }
  for (auto k = 0; k < 4; k++)
  {
    dist[2 * K][k] = infty;
  }
  for (int i = 2 * K - 1; i >= 0; i--)
  {
    for (auto k = 0; k < 4; k++)
    {
      if (D[i] == ds[k])
      {
        dist[i][k] = 1;
      }
      else
      {
        dist[i][k] = dist[i + 1][k] + 1;
      }
    }
  }
  /*
  for (auto i = 0; i < K; i++)
  {
    for (auto k = 0; k < 4; k++)
    {
      cerr << "dist[" << i << "][" << k << "] = " << dist[i][k] << endl;
    }
  }
  */
  int sx, sy, gx, gy;
  fill(&ans[0][0], &ans[0][0] + 1010 * 1010, -1);
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < M; j++)
    {
      if (S[i][j] == 'S')
      {
        sx = i;
        sy = j;
      }
      else if (S[i][j] == 'G')
      {
        gx = i;
        gy = j;
      }
    }
  }
  priority_queue<state, vector<state>, greater<state>> Q;
  Q.push(state(0, sx, sy));
  while (!Q.empty())
  {
    ll d = get<0>(Q.top());
    int x = get<1>(Q.top());
    int y = get<2>(Q.top());
    Q.pop();
    if (ans[x][y] == -1)
    {
      ans[x][y] = d;
      // cerr << "ans[" << x << "][" << y << "] = " << ans[x][y] << endl;
      if (x == gx && y == gy)
      {
        cout << d << endl;
        return 0;
      }
      for (auto k = 0; k < 4; k++)
      {
        int new_x = x + dx[k];
        int new_y = y + dy[k];
        if (0 <= new_x && new_x < N && 0 <= new_y && new_y < M && S[new_x][new_y] != '#' && ans[new_x][new_y] == -1)
        {
          ll new_d = d + dist[d % K][k];
          if (new_d < infty)
          {
            Q.push(state(new_d, new_x, new_y));
          }
        }
      }
    }
  }
  cout << -1 << endl;
}<commit_msg>submit E.cpp to 'E - 迷路' (mujin-pc-2018) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-8-4 22:09:58
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const char ds[4] = {'D', 'R', 'U', 'L'};

typedef tuple<ll, int, int> state;

// const int C = 1e6+10;
const ll infty = 1000000007;

int N, M, K;
string D;
string S[1010];
ll dist[300010][4];
ll ans[1010][1010];

int main()
{
  cin >> N >> M >> K;
  cin >> D;
  D = D + D + D;
  for (auto i = 0; i < N; i++)
  {
    cin >> S[i];
  }
  for (auto k = 0; k < 4; k++)
  {
    dist[3 * K][k] = infty;
  }
  for (int i = 3 * K - 1; i >= 0; i--)
  {
    for (auto k = 0; k < 4; k++)
    {
      if (D[i] == ds[k])
      {
        dist[i][k] = 1;
      }
      else
      {
        dist[i][k] = dist[i + 1][k] + 1;
      }
    }
  }
  /*
  for (auto i = 0; i < K; i++)
  {
    for (auto k = 0; k < 4; k++)
    {
      cerr << "dist[" << i << "][" << k << "] = " << dist[i][k] << endl;
    }
  }
  */
  int sx, sy, gx, gy;
  fill(&ans[0][0], &ans[0][0] + 1010 * 1010, -1);
  for (auto i = 0; i < N; i++)
  {
    for (auto j = 0; j < M; j++)
    {
      if (S[i][j] == 'S')
      {
        sx = i;
        sy = j;
      }
      else if (S[i][j] == 'G')
      {
        gx = i;
        gy = j;
      }
    }
  }
  priority_queue<state, vector<state>, greater<state>> Q;
  Q.push(state(0, sx, sy));
  while (!Q.empty())
  {
    ll d = get<0>(Q.top());
    int x = get<1>(Q.top());
    int y = get<2>(Q.top());
    Q.pop();
    if (ans[x][y] == -1)
    {
      ans[x][y] = d;
      // cerr << "ans[" << x << "][" << y << "] = " << ans[x][y] << endl;
      if (x == gx && y == gy)
      {
        cout << d << endl;
        return 0;
      }
      for (auto k = 0; k < 4; k++)
      {
        int new_x = x + dx[k];
        int new_y = y + dy[k];
        if (0 <= new_x && new_x < N && 0 <= new_y && new_y < M && S[new_x][new_y] != '#' && ans[new_x][new_y] == -1)
        {
          ll new_d = d + dist[d % K][k];
          if (new_d < infty)
          {
            Q.push(state(new_d, new_x, new_y));
          }
        }
      }
    }
  }
  cout << -1 << endl;
}<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* EBookImportFilter: Sets up the filter, and calls DocumentCollector
 * to do the actual filtering
 *
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <com/sun/star/uno/Reference.h>
#include <cppuhelper/supportsservice.hxx>

#include <libe-book/libe-book.h>

#include "EBookImportFilter.hxx"

using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Any;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::XComponentContext;

using libebook::EBOOKDocument;

bool EBookImportFilter::doImportDocument( librevenge::RVNGInputStream &rInput, const rtl::OUString &rFilterName, librevenge::RVNGTextInterface &rGenerator )
{
    if (rFilterName == "FictionBook 2")
        return EBOOKDocument::parse(&rInput, &rGenerator, EBOOKDocument::TYPE_FICTIONBOOK2);
    else if (rFilterName == "PalmDoc")
        return EBOOKDocument::parse(&rInput, &rGenerator, EBOOKDocument::TYPE_PALMDOC);
    else if (rFilterName == "Plucker eBook")
        return EBOOKDocument::parse(&rInput, &rGenerator, EBOOKDocument::TYPE_PLUCKER);
    else if (rFilterName == "eReader eBook")
        return EBOOKDocument::parse(&rInput, &rGenerator, EBOOKDocument::TYPE_PEANUTPRESS);
    else if (rFilterName == "TealDoc")
        return EBOOKDocument::parse(&rInput, &rGenerator, EBOOKDocument::TYPE_TEALDOC);
    else if (rFilterName == "zTXT")
        return EBOOKDocument::parse(&rInput, &rGenerator, EBOOKDocument::TYPE_ZTXT);

    return false;
}

bool EBookImportFilter::doDetectFormat( librevenge::RVNGInputStream &rInput, OUString &rTypeName )
{
    rTypeName = "";

    EBOOKDocument::Type type = EBOOKDocument::TYPE_UNKNOWN;

    if (EBOOKDocument::CONFIDENCE_EXCELLENT == EBOOKDocument::isSupported(&rInput, &type))
    {
        switch (type)
        {
            case EBOOKDocument::TYPE_FICTIONBOOK2 :
                rTypeName = "writer_FictionBook_2";
                break;
            case EBOOKDocument::TYPE_PALMDOC :
                rTypeName = "writer_PalmDoc";
                break;
            case EBOOKDocument::TYPE_PLUCKER :
                rTypeName = "writer_Plucker_eBook";
                break;
            case EBOOKDocument::TYPE_PEANUTPRESS :
                rTypeName = "writer_eReader_eBook";
                break;
            case EBOOKDocument::TYPE_TEALDOC :
                rTypeName = "writer_TealDoc";
                break;
            case EBOOKDocument::TYPE_ZTXT :
                rTypeName = "writer_zTXT";
                break;
            default :
                SAL_WARN_IF(type != EBOOKDocument::TYPE_UNKNOWN, "writerperfect", "EBookImportFilter::doDetectFormat: document type " << type << " detected, but ignored");
        }
    }

    return !rTypeName.isEmpty();
}

OUString EBookImportFilter_getImplementationName ()
throw (RuntimeException)
{
    return OUString (  "org.libreoffice.comp.Writer.EBookImportFilter"  );
}

Sequence< OUString > SAL_CALL EBookImportFilter_getSupportedServiceNames(  )
throw (RuntimeException)
{
    Sequence < OUString > aRet(2);
    OUString *pArray = aRet.getArray();
    pArray[0] =  "com.sun.star.document.ImportFilter";
    pArray[1] =  "com.sun.star.document.ExtendedTypeDetection";
    return aRet;
}
#undef SERVICE_NAME2
#undef SERVICE_NAME1

Reference< XInterface > SAL_CALL EBookImportFilter_createInstance( const Reference< XComponentContext > & rContext)
throw( Exception )
{
    return (cppu::OWeakObject *) new EBookImportFilter( rContext );
}

// XServiceInfo
OUString SAL_CALL EBookImportFilter::getImplementationName(  )
throw (RuntimeException, std::exception)
{
    return EBookImportFilter_getImplementationName();
}
sal_Bool SAL_CALL EBookImportFilter::supportsService( const OUString &rServiceName )
throw (RuntimeException, std::exception)
{
    return cppu::supportsService( this, rServiceName );
}
Sequence< OUString > SAL_CALL EBookImportFilter::getSupportedServiceNames(  )
throw (RuntimeException, std::exception)
{
    return EBookImportFilter_getSupportedServiceNames();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix return value for libe-book import filter<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* EBookImportFilter: Sets up the filter, and calls DocumentCollector
 * to do the actual filtering
 *
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <com/sun/star/uno/Reference.h>
#include <cppuhelper/supportsservice.hxx>

#include <libe-book/libe-book.h>

#include "EBookImportFilter.hxx"

using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Any;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::XComponentContext;

using libebook::EBOOKDocument;

bool EBookImportFilter::doImportDocument( librevenge::RVNGInputStream &rInput, const rtl::OUString &rFilterName, librevenge::RVNGTextInterface &rGenerator )
{
    EBOOKDocument::Type type = EBOOKDocument::TYPE_UNKNOWN;

    if (rFilterName == "FictionBook 2")
        type = EBOOKDocument::TYPE_FICTIONBOOK2;
    else if (rFilterName == "PalmDoc")
        type = EBOOKDocument::TYPE_PALMDOC;
    else if (rFilterName == "Plucker eBook")
        type = EBOOKDocument::TYPE_PLUCKER;
    else if (rFilterName == "eReader eBook")
        type = EBOOKDocument::TYPE_PEANUTPRESS;
    else if (rFilterName == "TealDoc")
        type = EBOOKDocument::TYPE_TEALDOC;
    else if (rFilterName == "zTXT")
        type = EBOOKDocument::TYPE_ZTXT;

    if (EBOOKDocument::TYPE_UNKNOWN != type)
        return EBOOKDocument::RESULT_OK == EBOOKDocument::parse(&rInput, &rGenerator, type);

    return false;
}

bool EBookImportFilter::doDetectFormat( librevenge::RVNGInputStream &rInput, OUString &rTypeName )
{
    rTypeName = "";

    EBOOKDocument::Type type = EBOOKDocument::TYPE_UNKNOWN;

    if (EBOOKDocument::CONFIDENCE_EXCELLENT == EBOOKDocument::isSupported(&rInput, &type))
    {
        switch (type)
        {
            case EBOOKDocument::TYPE_FICTIONBOOK2 :
                rTypeName = "writer_FictionBook_2";
                break;
            case EBOOKDocument::TYPE_PALMDOC :
                rTypeName = "writer_PalmDoc";
                break;
            case EBOOKDocument::TYPE_PLUCKER :
                rTypeName = "writer_Plucker_eBook";
                break;
            case EBOOKDocument::TYPE_PEANUTPRESS :
                rTypeName = "writer_eReader_eBook";
                break;
            case EBOOKDocument::TYPE_TEALDOC :
                rTypeName = "writer_TealDoc";
                break;
            case EBOOKDocument::TYPE_ZTXT :
                rTypeName = "writer_zTXT";
                break;
            default :
                SAL_WARN_IF(type != EBOOKDocument::TYPE_UNKNOWN, "writerperfect", "EBookImportFilter::doDetectFormat: document type " << type << " detected, but ignored");
        }
    }

    return !rTypeName.isEmpty();
}

OUString EBookImportFilter_getImplementationName ()
throw (RuntimeException)
{
    return OUString (  "org.libreoffice.comp.Writer.EBookImportFilter"  );
}

Sequence< OUString > SAL_CALL EBookImportFilter_getSupportedServiceNames(  )
throw (RuntimeException)
{
    Sequence < OUString > aRet(2);
    OUString *pArray = aRet.getArray();
    pArray[0] =  "com.sun.star.document.ImportFilter";
    pArray[1] =  "com.sun.star.document.ExtendedTypeDetection";
    return aRet;
}
#undef SERVICE_NAME2
#undef SERVICE_NAME1

Reference< XInterface > SAL_CALL EBookImportFilter_createInstance( const Reference< XComponentContext > & rContext)
throw( Exception )
{
    return (cppu::OWeakObject *) new EBookImportFilter( rContext );
}

// XServiceInfo
OUString SAL_CALL EBookImportFilter::getImplementationName(  )
throw (RuntimeException, std::exception)
{
    return EBookImportFilter_getImplementationName();
}
sal_Bool SAL_CALL EBookImportFilter::supportsService( const OUString &rServiceName )
throw (RuntimeException, std::exception)
{
    return cppu::supportsService( this, rServiceName );
}
Sequence< OUString > SAL_CALL EBookImportFilter::getSupportedServiceNames(  )
throw (RuntimeException, std::exception)
{
    return EBookImportFilter_getSupportedServiceNames();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

#include <memory>
#include <string>
#include <vector>

#include <glog/logging.h>

#include <gmock/gmock.h>

#include <gtest/gtest.h>

#include <stout/check.hpp>
#include <stout/exit.hpp>
#include <stout/fs.hpp>

#include <stout/os/mkdtemp.hpp>
#include <stout/os/socket.hpp> // For `wsa_*` on Windows.
#include <stout/os/touch.hpp>

#include <stout/tests/environment.hpp>

using stout::internal::tests::Environment;
using stout::internal::tests::TestFilter;

using std::make_shared;
using std::shared_ptr;
using std::string;
using std::vector;

// Attempt to create a symlink. If creating a symlink fails, disable
// all unit tests that rely on the creation of symlinks.
class SymlinkFilter : public TestFilter
{
public:
  SymlinkFilter()
  {
    const Try<string> temp_path = os::mkdtemp();
    CHECK_SOME(temp_path);

    const string file = path::join(temp_path.get(), "file");
    const string link = path::join(temp_path.get(), "link");

    CHECK_SOME(os::touch(file));

    Try<Nothing> symlink_check = fs::symlink(file, link);
    can_create_symlinks = !symlink_check.isError();

    if (!can_create_symlinks) {
      std::cerr
        << "-------------------------------------------------------------\n"
        << "Unable to create symlinks, so no symlink tests will be run\n"
        << "-------------------------------------------------------------"
        << std::endl;
    }
  }

  bool disable(const ::testing::TestInfo* test) const override
  {
    return matches(test, "SYMLINK_") && !can_create_symlinks;
  }

private:
  bool can_create_symlinks;
};

#ifdef __WINDOWS__
// A no-op parameter validator. We use this to prevent the Windows
// implementation of the C runtime from calling `abort` during our test suite.
// See comment in `main.cpp`.
static void noop_invalid_parameter_handler(
    const wchar_t* expression,
    const wchar_t* function,
    const wchar_t* file,
    unsigned int line,
    uintptr_t reserved)
{
  return;
}
#endif // __WINDOWS__

int main(int argc, char** argv)
{
  // Initialize Google Mock/Test.
  testing::InitGoogleMock(&argc, argv);

#ifndef __WINDOWS__
  // Install glog's signal handler.
  // NOTE: this function is declared but not defined on Windows, so if we
  // attempt to compile this on Windows, we get a linker error.
  google::InstallFailureSignalHandler();
#else
  if (!net::wsa_initialize()) {
    EXIT(EXIT_FAILURE) << "WSA failed to initialize";
  }

  // When we're running a debug build, the Windows implementation of the C
  // runtime will validate parameters passed to C-standard functions like
  // `::close`. When we are in debug mode, if a parameter is invalid, the
  // handler will usually call `abort`, rather than populating `errno` and
  // returning an error value. Since we expect some tests to pass invalid
  // paramaters to these functions, we disable this for testing.
  _set_invalid_parameter_handler(noop_invalid_parameter_handler);
#endif // __WINDOWS__

  vector<shared_ptr<TestFilter>> filters = {make_shared<SymlinkFilter>()};
  Environment* environment = new Environment(filters);
  testing::AddGlobalTestEnvironment(environment);

  const int test_results = RUN_ALL_TESTS();

  // Prefer to return the error code from the test run over the error code
  // from the WSA teardown. That is: if the test run failed, return that error
  // code; but, if the tests passed, we still want to return an error if the
  // WSA teardown failed. If both succeeded, return 0.
  const bool teardown_failed =
#ifdef __WINDOWS__
    !net::wsa_cleanup();
#else
    false;
#endif // __WINDOWS__

  return test_results > 0
    ? test_results
    : teardown_failed;
}
<commit_msg>Prevented leaking files in some stout tests.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

#include <memory>
#include <string>
#include <vector>

#include <glog/logging.h>

#include <gmock/gmock.h>

#include <gtest/gtest.h>

#include <stout/check.hpp>
#include <stout/exit.hpp>
#include <stout/fs.hpp>

#include <stout/os/mkdtemp.hpp>
#include <stout/os/rmdir.hpp>
#include <stout/os/socket.hpp> // For `wsa_*` on Windows.
#include <stout/os/touch.hpp>

#include <stout/tests/environment.hpp>

using stout::internal::tests::Environment;
using stout::internal::tests::TestFilter;

using std::make_shared;
using std::shared_ptr;
using std::string;
using std::vector;

// Attempt to create a symlink. If creating a symlink fails, disable
// all unit tests that rely on the creation of symlinks.
class SymlinkFilter : public TestFilter
{
public:
  SymlinkFilter() : temp_path(CHECK_NOTERROR(os::mkdtemp()))
  {
    const string file = path::join(temp_path, "file");
    const string link = path::join(temp_path, "link");

    CHECK_SOME(os::touch(file));

    Try<Nothing> symlink_check = fs::symlink(file, link);
    can_create_symlinks = !symlink_check.isError();

    if (!can_create_symlinks) {
      std::cerr
        << "-------------------------------------------------------------\n"
        << "Unable to create symlinks, so no symlink tests will be run\n"
        << "-------------------------------------------------------------"
        << std::endl;
    }
  }

  ~SymlinkFilter() override
  {
    os::rmdir(temp_path);
  }

  bool disable(const ::testing::TestInfo* test) const override
  {
    return matches(test, "SYMLINK_") && !can_create_symlinks;
  }

private:
  bool can_create_symlinks;
  string temp_path;
};

#ifdef __WINDOWS__
// A no-op parameter validator. We use this to prevent the Windows
// implementation of the C runtime from calling `abort` during our test suite.
// See comment in `main.cpp`.
static void noop_invalid_parameter_handler(
    const wchar_t* expression,
    const wchar_t* function,
    const wchar_t* file,
    unsigned int line,
    uintptr_t reserved)
{
  return;
}
#endif // __WINDOWS__

int main(int argc, char** argv)
{
  // Initialize Google Mock/Test.
  testing::InitGoogleMock(&argc, argv);

#ifndef __WINDOWS__
  // Install glog's signal handler.
  // NOTE: this function is declared but not defined on Windows, so if we
  // attempt to compile this on Windows, we get a linker error.
  google::InstallFailureSignalHandler();
#else
  if (!net::wsa_initialize()) {
    EXIT(EXIT_FAILURE) << "WSA failed to initialize";
  }

  // When we're running a debug build, the Windows implementation of the C
  // runtime will validate parameters passed to C-standard functions like
  // `::close`. When we are in debug mode, if a parameter is invalid, the
  // handler will usually call `abort`, rather than populating `errno` and
  // returning an error value. Since we expect some tests to pass invalid
  // paramaters to these functions, we disable this for testing.
  _set_invalid_parameter_handler(noop_invalid_parameter_handler);
#endif // __WINDOWS__

  vector<shared_ptr<TestFilter>> filters = {make_shared<SymlinkFilter>()};
  Environment* environment = new Environment(filters);
  testing::AddGlobalTestEnvironment(environment);

  const int test_results = RUN_ALL_TESTS();

  // Prefer to return the error code from the test run over the error code
  // from the WSA teardown. That is: if the test run failed, return that error
  // code; but, if the tests passed, we still want to return an error if the
  // WSA teardown failed. If both succeeded, return 0.
  const bool teardown_failed =
#ifdef __WINDOWS__
    !net::wsa_cleanup();
#else
    false;
#endif // __WINDOWS__

  return test_results > 0
    ? test_results
    : teardown_failed;
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "ShareDBManager.h"
#include "Config.h"
#include "ODBCInterface.h"
#include "TimeManager.h"
#include "Log.h"

BOOL    ShareDBManager::Init()
{
    __ENTER_FUNCTION

        //从Config 读取Login DB 相关的数据
        CHAR    szCharDBHost[ HOST_STR_LEN ] ;
        strncpy( szCharDBHost, g_Config.m_ShareMemInfo.m_DBIP, HOST_STR_LEN ) ;                      //连接对端IP
        szCharDBHost[ HOST_STR_LEN - 1 ] = '\0' ;

        UINT    uCharDBPort = g_Config.m_ShareMemInfo.m_DBPort ;                                     //连接对端端口
        CHAR    szCharDBDatabase[DATABASE_STR_LEN] ;
        strncpy( szCharDbDatabase, g_Config.m_ShareMemInfo.m_DBName, DATABASE_STR_LEN ) ;            //数据库名称
        szCharDBDatabase[ DATABASE_STR_LEN - 1 ] = '\0' ;

        CHAR    szCharDBUser[ DB_USE_STR_LEN ] ;                                                     //用户名称
        strncpy( szCharDBUser, g_Config.m_ShareMemInfo.m_DBUser, DB_USE_STR_LEN ) ;
        szCharDBUser[ DB_USE_STR_LEN - 1 ] = '\0' ;

        CHAR    szCharDBPassword[ DB_PASSWORD_STR_LEN ] ;                                            //密码
        strncpy( szCharDBPassword, g_Config.m_ShareMemInfo.m_DBPassword, DB_PASSWORD_STR_LEN ) ;
        szCharDBPassword[ DB_PASSWORD_STR_LEN - 1 ] = '\0' ;

        Assert( mCharDBInterface ) ;

        mCharDBInterface->Connect( szCharDBDatabase, szCharDBUser, szCharDBPassword ) ;

        if( !mCharDBInterface->IsConnected() )
        {
            Log::SaveLog( "ShareMemory", "mCharDBInterface->Connect()... Get Errors: %s ", mCharDBInterface->GetErrorMsg() ) ;
        }

        return mCharDBInterface->IsConnected() ;

    __LEAVE_FUNCTION

        return FALSE ;
}

VOID ShareDBManager::run()
{
    __ENTER_FUNCTION

    __LEAVE_FUNCTION
}
<commit_msg>fix some bug<commit_after>#include "stdafx.h"
#include "ShareDBManager.h"
#include "Config.h"
#include "ODBCInterface.h"
#include "TimeManager.h"
#include "Log.h"

BOOL    ShareDBManager::Init()
{
    __ENTER_FUNCTION

        //从Config 读取Login DB 相关的数据
        CHAR    szCharDBHost[ HOST_STR_LEN ] ;
        strncpy( szCharDBHost, g_Config.m_ShareMemInfo.m_DBIP, HOST_STR_LEN ) ;                      //连接对端IP
        szCharDBHost[ HOST_STR_LEN - 1 ] = '\0' ;

        UINT    uCharDBPort = g_Config.m_ShareMemInfo.m_DBPort ;                                     //连接对端端口
        CHAR    szCharDBDatabase[ DATABASE_STR_LEN ] ;
        strncpy( szCharDBDatabase, g_Config.m_ShareMemInfo.m_DBName, DATABASE_STR_LEN ) ;            //数据库名称
        szCharDBDatabase[ DATABASE_STR_LEN - 1 ] = '\0' ;

        CHAR    szCharDBUser[ DB_USE_STR_LEN ] ;                                                     //用户名称
        strncpy( szCharDBUser, g_Config.m_ShareMemInfo.m_DBUser, DB_USE_STR_LEN ) ;
        szCharDBUser[ DB_USE_STR_LEN - 1 ] = '\0' ;

        CHAR    szCharDBPassword[ DB_PASSWORD_STR_LEN ] ;                                            //密码
        strncpy( szCharDBPassword, g_Config.m_ShareMemInfo.m_DBPassword, DB_PASSWORD_STR_LEN ) ;
        szCharDBPassword[ DB_PASSWORD_STR_LEN - 1 ] = '\0' ;

        Assert( mCharDBInterface ) ;

        mCharDBInterface->Connect( szCharDBDatabase, szCharDBUser, szCharDBPassword ) ;

        if( !mCharDBInterface->IsConnected() )
        {
            Log::SaveLog( "ShareMemory", "mCharDBInterface->Connect()... Get Errors: %s ", mCharDBInterface->GetErrorMsg() ) ;
        }

        return mCharDBInterface->IsConnected() ;

    __LEAVE_FUNCTION

        return FALSE ;
}

VOID ShareDBManager::run()
{
    __ENTER_FUNCTION

    __LEAVE_FUNCTION
}
<|endoftext|>


<commit_before>#include "offeracceptdialogbtc.h"
#include "ui_offeracceptdialogbtc.h"
#include "init.h"
#include "util.h"
#include "offerpaydialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "syscoingui.h"
#include <QMessageBox>
#include "rpcserver.h"
#include "pubkey.h"
#include "wallet/wallet.h"
#include "main.h"
#include "utilmoneystr.h"
#include <QDesktopServices>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#include <QPixmap>
#if defined(HAVE_CONFIG_H)
#include "config/syscoin-config.h" /* for USE_QRCODE */
#endif
#ifdef USE_QRCODE
#include <qrencode.h>
#endif
using namespace std;
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
extern const CRPCTable tableRPC;
OfferAcceptDialogBTC::OfferAcceptDialogBTC(const PlatformStyle *platformStyle, QString alias, QString offer, QString quantity, QString notes, QString title, QString currencyCode, QString qstrPrice, QString sellerAlias, QString address, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OfferAcceptDialogBTC), platformStyle(platformStyle), alias(alias), offer(offer), notes(notes), quantity(quantity), title(title), sellerAlias(sellerAlias), address(address)
{
    ui->setupUi(this);
	QString theme = GUIUtil::getThemeName();
	ui->aboutShadeBTC->setPixmap(QPixmap(":/images/" + theme + "/about_btc"));
	dblPrice = qstrPrice.toDouble()*quantity.toUInt();
	string strfPrice = strprintf("%f", dblPrice);
	QString fprice = QString::fromStdString(strfPrice);
	string strCurrencyCode = currencyCode.toStdString();
	ui->escrowDisclaimer->setText(tr("Please note escrow is not available since you are paying in BTC, only SYS payments can be escrowed. "));
	ui->bitcoinInstructionLabel->setText(tr("After paying for this item, please enter the Bitcoin Transaction ID and click on the confirm button below. You may use the QR Code to the left to scan the payment request into your wallet or click on the Open BTC Wallet if you are on the desktop and have Bitcoin Core installed."));
	ui->acceptMessage->setText(tr("Are you sure you want to purchase %1 of '%2' from merchant: '%3'? To complete your purchase please pay %4 BTC to %5 using your Bitcoin wallet.").arg(quantity).arg(title).arg(sellerAlias).arg(fprice).arg(address));
	string strPrice = strprintf("%f", dblPrice);
	price = QString::fromStdString(strPrice);

	if (!platformStyle->getImagesOnButtons())
	{
		ui->confirmButton->setIcon(QIcon());
		ui->openBtcWalletButton->setIcon(QIcon());
		ui->cancelButton->setIcon(QIcon());

	}
	else
	{
		ui->confirmButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/transaction_confirmed"));
		ui->openBtcWalletButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/send"));
		ui->cancelButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/quit"));
	}
	this->offerPaid = false;
	connect(ui->confirmButton, SIGNAL(clicked()), this, SLOT(tryAcceptOffer()));
	connect(ui->openBtcWalletButton, SIGNAL(clicked()), this, SLOT(openBTCWallet()));

#ifdef USE_QRCODE
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace.";
	SendCoinsRecipient info;
	info.address = this->address;
	info.label = this->sellerAlias;
	info.message = message;
	ParseMoney(price.toStdString(), info.amount);
	QString uri = GUIUtil::formatBitcoinURI(info);

	ui->lblQRCode->setText("");
    if(!uri.isEmpty())
    {
        // limit URI length
        if (uri.length() > MAX_URI_LENGTH)
        {
            ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
        } else {
            QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
            if (!code)
            {
                ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
                return;
            }
            QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
            myImage.fill(0xffffff);
            unsigned char *p = code->data;
            for (int y = 0; y width; y++)
            {
                for (int x = 0; x width; x++)
                {
                    myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
                    p++;
                }
            }
            QRcode_free(code);
            ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(128, 128));
        }
    }
#endif
}
void OfferAcceptDialogBTC::on_cancelButton_clicked()
{
    reject();
}
OfferAcceptDialogBTC::~OfferAcceptDialogBTC()
{
    delete ui;
}

void OfferAcceptDialogBTC::slotConfirmedFinished(QNetworkReply * reply){
	if(reply->error() != QNetworkReply::NoError) {
		ui->confirmButton->setText(m_buttonText);
		ui->confirmButton->setEnabled(true);
        QMessageBox::critical(this, windowTitle(),
            tr("Error making request: ") + reply->errorString(),
                QMessageBox::Ok, QMessageBox::Ok);
		return;
	}
	double valueAmount = 0;
	QString time;

	QByteArray bytes = reply->readAll();
	QString str = QString::fromUtf8(bytes.data(), bytes.size());
	UniValue outerValue;
	bool read = outerValue.read(str.toStdString());
	if (read)
	{
		UniValue outerObj = outerValue.get_obj();
		UniValue statusValue = find_value(outerObj, "status");
		if (statusValue.isStr())
		{
			if(statusValue.get_str() != "success")
			{
				ui->confirmButton->setText(m_buttonText);
				ui->confirmButton->setEnabled(true);
				QMessageBox::critical(this, windowTitle(),
					tr("Transaction status not successful: ") + QString::fromStdString(statusValue.get_str()),
						QMessageBox::Ok, QMessageBox::Ok);
				return;
			}
		}
		UniValue dataObj = find_value(outerObj, "data");
		UniValue timeValue = find_value(dataObj, "time_utc");
		if (timeValue.isStr())
			time = QString::fromStdString(timeValue.get_str());
		UniValue outputsValue = find_value(dataObj, "vouts");
		if (outputsValue.isArray())
		{
			UniValue outputs = outputsValue.get_array();
			for (unsigned int idx = 0; idx < outputs.size(); idx++) {
				const UniValue& output = outputs[idx];
				UniValue addressValue = find_value(output, "address");
				if(addressValue.isStr())
				{
					if(addressValue.get_str() == address.toStdString())
					{
						UniValue paymentValue = find_value(output, "amount");
						if(paymentValue.isStr())
						{
							valueAmount += QString::fromStdString(paymentValue.get_str()).toDouble();

							if(valueAmount >= dblPrice)
							{
								ui->confirmButton->setText(m_buttonText);
								ui->confirmButton->setEnabled(true);
								QMessageBox::information(this, windowTitle(),
									tr("Transaction ID %1 was found in the Bitcoin blockchain! Full payment has been detected at %3.").arg(ui->btctxidEdit->text().trimmed()).arg(height).arg(time),
									QMessageBox::Ok, QMessageBox::Ok);
								acceptOffer();
								return;
							}
						}
					}

				}
			}
		}
	}
	else
	{
		ui->confirmButton->setText(m_buttonText);
		ui->confirmButton->setEnabled(true);
		QMessageBox::critical(this, windowTitle(),
			tr("Cannot parse JSON response: ") + str,
				QMessageBox::Ok, QMessageBox::Ok);
		return;
	}

	reply->deleteLater();
	ui->confirmButton->setText(m_buttonText);
	ui->confirmButton->setEnabled(true);
	QMessageBox::warning(this, windowTitle(),
		tr("Payment not found in the Bitcoin blockchain! Please try again later."),
			QMessageBox::Ok, QMessageBox::Ok);
}
void OfferAcceptDialogBTC::CheckPaymentInBTC()
{
	m_buttonText = ui->confirmButton->text();
	ui->confirmButton->setText(tr("Please Wait..."));
	ui->confirmButton->setEnabled(false);
	QNetworkAccessManager *nam = new QNetworkAccessManager(this);
	connect(nam, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotConfirmedFinished(QNetworkReply *)));
	QUrl url("http://btc.blockr.io/api/v1/tx/info/" + ui->btctxidEdit->text().trimmed());
	QNetworkRequest request(url);
	nam->get(request);
}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void OfferAcceptDialogBTC::tryAcceptOffer()
{
	if (ui->btctxidEdit->text().trimmed().isEmpty()) {
        ui->btctxidEdit->setText("");
        QMessageBox::critical(this, windowTitle(),
        tr("Please enter a valid Bitcoin Transaction ID into the input box and try again"),
            QMessageBox::Ok, QMessageBox::Ok);
        return;
    }
	CheckPaymentInBTC();
}
void OfferAcceptDialogBTC::acceptOffer(){
		UniValue params(UniValue::VARR);
		UniValue valError;
		UniValue valResult;
		UniValue valId;
		UniValue result ;
		string strReply;
		string strError;

		string strMethod = string("offeraccept");
		if(this->quantity.toLong() <= 0)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("Invalid quantity when trying to accept offer!"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		this->offerPaid = false;
		params.push_back(this->alias.toStdString());
		params.push_back(this->offer.toStdString());
		params.push_back(this->quantity.toStdString());
		params.push_back(this->notes.toStdString());
		params.push_back(ui->btctxidEdit->text().trimmed().toStdString());

	    try {
            result = tableRPC.execute(strMethod, params);
			if (result.type() != UniValue::VNULL)
			{
				const UniValue &arr = result.get_array();
				string strResult = arr[0].get_str();
				QString offerAcceptTXID = QString::fromStdString(strResult);
				if(offerAcceptTXID != QString(""))
				{
					OfferPayDialog dlg(platformStyle, this->title, this->quantity, this->price, "BTC", this);
					dlg.exec();
					this->offerPaid = true;
					OfferAcceptDialogBTC::accept();
					return;

				}
			}
		}
		catch (UniValue& objError)
		{
			strError = find_value(objError, "message").get_str();
			QMessageBox::critical(this, windowTitle(),
			tr("Error accepting offer: \"%1\"").arg(QString::fromStdString(strError)),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		catch(std::exception& e)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("General exception when accepting offer"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
}
void OfferAcceptDialogBTC::openBTCWallet()
{
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace.";
	SendCoinsRecipient info;
	info.address = this->address;
	info.label = this->sellerAlias;
	info.message = message;
	ParseMoney(price.toStdString(), info.amount);
	QString uri = GUIUtil::formatBitcoinURI(info);
	QDesktopServices::openUrl(QUrl(uri, QUrl::TolerantMode));
}
bool OfferAcceptDialogBTC::getPaymentStatus()
{
	return this->offerPaid;
}
<commit_msg>typo<commit_after>#include "offeracceptdialogbtc.h"
#include "ui_offeracceptdialogbtc.h"
#include "init.h"
#include "util.h"
#include "offerpaydialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "platformstyle.h"
#include "syscoingui.h"
#include <QMessageBox>
#include "rpcserver.h"
#include "pubkey.h"
#include "wallet/wallet.h"
#include "main.h"
#include "utilmoneystr.h"
#include <QDesktopServices>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
#include <QPixmap>
#if defined(HAVE_CONFIG_H)
#include "config/syscoin-config.h" /* for USE_QRCODE */
#endif
#ifdef USE_QRCODE
#include <qrencode.h>
#endif
using namespace std;
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
extern const CRPCTable tableRPC;
OfferAcceptDialogBTC::OfferAcceptDialogBTC(const PlatformStyle *platformStyle, QString alias, QString offer, QString quantity, QString notes, QString title, QString currencyCode, QString qstrPrice, QString sellerAlias, QString address, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OfferAcceptDialogBTC), platformStyle(platformStyle), alias(alias), offer(offer), notes(notes), quantity(quantity), title(title), sellerAlias(sellerAlias), address(address)
{
    ui->setupUi(this);
	QString theme = GUIUtil::getThemeName();
	ui->aboutShadeBTC->setPixmap(QPixmap(":/images/" + theme + "/about_btc"));
	dblPrice = qstrPrice.toDouble()*quantity.toUInt();
	string strfPrice = strprintf("%f", dblPrice);
	QString fprice = QString::fromStdString(strfPrice);
	string strCurrencyCode = currencyCode.toStdString();
	ui->escrowDisclaimer->setText(tr("Please note escrow is not available since you are paying in BTC, only SYS payments can be escrowed. "));
	ui->bitcoinInstructionLabel->setText(tr("After paying for this item, please enter the Bitcoin Transaction ID and click on the confirm button below. You may use the QR Code to the left to scan the payment request into your wallet or click on the Open BTC Wallet if you are on the desktop and have Bitcoin Core installed."));
	ui->acceptMessage->setText(tr("Are you sure you want to purchase %1 of '%2' from merchant: '%3'? To complete your purchase please pay %4 BTC to %5 using your Bitcoin wallet.").arg(quantity).arg(title).arg(sellerAlias).arg(fprice).arg(address));
	string strPrice = strprintf("%f", dblPrice);
	price = QString::fromStdString(strPrice);

	if (!platformStyle->getImagesOnButtons())
	{
		ui->confirmButton->setIcon(QIcon());
		ui->openBtcWalletButton->setIcon(QIcon());
		ui->cancelButton->setIcon(QIcon());

	}
	else
	{
		ui->confirmButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/transaction_confirmed"));
		ui->openBtcWalletButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/send"));
		ui->cancelButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/quit"));
	}
	this->offerPaid = false;
	connect(ui->confirmButton, SIGNAL(clicked()), this, SLOT(tryAcceptOffer()));
	connect(ui->openBtcWalletButton, SIGNAL(clicked()), this, SLOT(openBTCWallet()));

#ifdef USE_QRCODE
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace.";
	SendCoinsRecipient info;
	info.address = this->address;
	info.label = this->sellerAlias;
	info.message = message;
	ParseMoney(price.toStdString(), info.amount);
	QString uri = GUIUtil::formatBitcoinURI(info);

	ui->lblQRCode->setText("");
    if(!uri.isEmpty())
    {
        // limit URI length
        if (uri.length() > MAX_URI_LENGTH)
        {
            ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
        } else {
            QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
            if (!code)
            {
                ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
                return;
            }
            QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
            myImage.fill(0xffffff);
            unsigned char *p = code->data;
            for (int y = 0; y width; y++)
            {
                for (int x = 0; x width; x++)
                {
                    myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
                    p++;
                }
            }
            QRcode_free(code);
            ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(128, 128));
        }
    }
#endif
}
void OfferAcceptDialogBTC::on_cancelButton_clicked()
{
    reject();
}
OfferAcceptDialogBTC::~OfferAcceptDialogBTC()
{
    delete ui;
}

void OfferAcceptDialogBTC::slotConfirmedFinished(QNetworkReply * reply){
	if(reply->error() != QNetworkReply::NoError) {
		ui->confirmButton->setText(m_buttonText);
		ui->confirmButton->setEnabled(true);
        QMessageBox::critical(this, windowTitle(),
            tr("Error making request: ") + reply->errorString(),
                QMessageBox::Ok, QMessageBox::Ok);
		return;
	}
	double valueAmount = 0;
	QString time;

	QByteArray bytes = reply->readAll();
	QString str = QString::fromUtf8(bytes.data(), bytes.size());
	UniValue outerValue;
	bool read = outerValue.read(str.toStdString());
	if (read)
	{
		UniValue outerObj = outerValue.get_obj();
		UniValue statusValue = find_value(outerObj, "status");
		if (statusValue.isStr())
		{
			if(statusValue.get_str() != "success")
			{
				ui->confirmButton->setText(m_buttonText);
				ui->confirmButton->setEnabled(true);
				QMessageBox::critical(this, windowTitle(),
					tr("Transaction status not successful: ") + QString::fromStdString(statusValue.get_str()),
						QMessageBox::Ok, QMessageBox::Ok);
				return;
			}
		}
		UniValue dataObj = find_value(outerObj, "data");
		UniValue timeValue = find_value(dataObj, "time_utc");
		if (timeValue.isStr())
			time = QString::fromStdString(timeValue.get_str());
		UniValue outputsValue = find_value(dataObj, "vouts");
		if (outputsValue.isArray())
		{
			UniValue outputs = outputsValue.get_array();
			for (unsigned int idx = 0; idx < outputs.size(); idx++) {
				const UniValue& output = outputs[idx];
				UniValue addressValue = find_value(output, "address");
				if(addressValue.isStr())
				{
					if(addressValue.get_str() == address.toStdString())
					{
						UniValue paymentValue = find_value(output, "amount");
						if(paymentValue.isStr())
						{
							valueAmount += QString::fromStdString(paymentValue.get_str()).toDouble();

							if(valueAmount >= dblPrice)
							{
								ui->confirmButton->setText(m_buttonText);
								ui->confirmButton->setEnabled(true);
								QMessageBox::information(this, windowTitle(),
									tr("Transaction ID %1 was found in the Bitcoin blockchain! Full payment has been detected at %2.").arg(ui->btctxidEdit->text().trimmed()).arg(time),
									QMessageBox::Ok, QMessageBox::Ok);
								acceptOffer();
								return;
							}
						}
					}

				}
			}
		}
	}
	else
	{
		ui->confirmButton->setText(m_buttonText);
		ui->confirmButton->setEnabled(true);
		QMessageBox::critical(this, windowTitle(),
			tr("Cannot parse JSON response: ") + str,
				QMessageBox::Ok, QMessageBox::Ok);
		return;
	}

	reply->deleteLater();
	ui->confirmButton->setText(m_buttonText);
	ui->confirmButton->setEnabled(true);
	QMessageBox::warning(this, windowTitle(),
		tr("Payment not found in the Bitcoin blockchain! Please try again later."),
			QMessageBox::Ok, QMessageBox::Ok);
}
void OfferAcceptDialogBTC::CheckPaymentInBTC()
{
	m_buttonText = ui->confirmButton->text();
	ui->confirmButton->setText(tr("Please Wait..."));
	ui->confirmButton->setEnabled(false);
	QNetworkAccessManager *nam = new QNetworkAccessManager(this);
	connect(nam, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotConfirmedFinished(QNetworkReply *)));
	QUrl url("http://btc.blockr.io/api/v1/tx/info/" + ui->btctxidEdit->text().trimmed());
	QNetworkRequest request(url);
	nam->get(request);
}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void OfferAcceptDialogBTC::tryAcceptOffer()
{
	if (ui->btctxidEdit->text().trimmed().isEmpty()) {
        ui->btctxidEdit->setText("");
        QMessageBox::critical(this, windowTitle(),
        tr("Please enter a valid Bitcoin Transaction ID into the input box and try again"),
            QMessageBox::Ok, QMessageBox::Ok);
        return;
    }
	CheckPaymentInBTC();
}
void OfferAcceptDialogBTC::acceptOffer(){
		UniValue params(UniValue::VARR);
		UniValue valError;
		UniValue valResult;
		UniValue valId;
		UniValue result ;
		string strReply;
		string strError;

		string strMethod = string("offeraccept");
		if(this->quantity.toLong() <= 0)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("Invalid quantity when trying to accept offer!"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		this->offerPaid = false;
		params.push_back(this->alias.toStdString());
		params.push_back(this->offer.toStdString());
		params.push_back(this->quantity.toStdString());
		params.push_back(this->notes.toStdString());
		params.push_back(ui->btctxidEdit->text().trimmed().toStdString());

	    try {
            result = tableRPC.execute(strMethod, params);
			if (result.type() != UniValue::VNULL)
			{
				const UniValue &arr = result.get_array();
				string strResult = arr[0].get_str();
				QString offerAcceptTXID = QString::fromStdString(strResult);
				if(offerAcceptTXID != QString(""))
				{
					OfferPayDialog dlg(platformStyle, this->title, this->quantity, this->price, "BTC", this);
					dlg.exec();
					this->offerPaid = true;
					OfferAcceptDialogBTC::accept();
					return;

				}
			}
		}
		catch (UniValue& objError)
		{
			strError = find_value(objError, "message").get_str();
			QMessageBox::critical(this, windowTitle(),
			tr("Error accepting offer: \"%1\"").arg(QString::fromStdString(strError)),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
		catch(std::exception& e)
		{
			QMessageBox::critical(this, windowTitle(),
				tr("General exception when accepting offer"),
				QMessageBox::Ok, QMessageBox::Ok);
			return;
		}
}
void OfferAcceptDialogBTC::openBTCWallet()
{
	QString message = "Payment for offer ID " + this->offer + " on Syscoin Decentralized Marketplace.";
	SendCoinsRecipient info;
	info.address = this->address;
	info.label = this->sellerAlias;
	info.message = message;
	ParseMoney(price.toStdString(), info.amount);
	QString uri = GUIUtil::formatBitcoinURI(info);
	QDesktopServices::openUrl(QUrl(uri, QUrl::TolerantMode));
}
bool OfferAcceptDialogBTC::getPaymentStatus()
{
	return this->offerPaid;
}
<|endoftext|>