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

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();

    // Genesis block
    if (pindexLast == NULL)
        return nProofOfWorkLimit;

    // Only change once per difficulty adjustment interval
    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
    {
        if (params.fPowAllowMinDifficultyBlocks)
        {
            // Special difficulty rule for testnet:
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }
        return pindexLast->nBits;
    }

    // Go back by what we want to be 14 days worth of blocks
    // Litecoin: This fixes an issue where a 51% attack can change difficulty at will.
    // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
    int blockstogoback = params.DifficultyAdjustmentInterval()-1;
    if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())
        blockstogoback = params.DifficultyAdjustmentInterval();

    // Go back by what we want to be 14 days worth of blocks
    const CBlockIndex* pindexFirst = pindexLast;
    for (int i = 0; pindexFirst && i < blockstogoback; i++)
        pindexFirst = pindexFirst->pprev;

    assert(pindexFirst);

    return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}

unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    if (nActualTimespan < params.nPowTargetTimespan/4)
        nActualTimespan = params.nPowTargetTimespan/4;
    if (nActualTimespan > params.nPowTargetTimespan*4)
        nActualTimespan = params.nPowTargetTimespan*4;

    // Retarget
    arith_uint256 bnNew;
    arith_uint256 bnOld;
    bnNew.SetCompact(pindexLast->nBits);
    bnOld = bnNew;
    // Litecoin: intermediate uint256 can overflow by 1 bit
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    bool fShift = bnNew.bits() > bnPowLimit.bits() - 1;
    if (fShift)
        bnNew >>= 1;
    bnNew *= nActualTimespan;
    bnNew /= params.nPowTargetTimespan;
    if (fShift)
        bnNew <<= 1;

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return false;

    // Check proof of work matches claimed amount
    if (UintToArith256(hash) > bnTarget)
        return false;

    return true;
}
<commit_msg>Add reset diff block, add new retarget system for fix stucked blockchain<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"

unsigned int GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();

    // Genesis block
    if (pindexLast == NULL)
        return nProofOfWorkLimit;
	//reset diff to profOfworkLimit after block 3338 solution tested.
	if (pindexLast->nHeight+1 == 3339)
        return nProofOfWorkLimit;

    // Only change once per difficulty adjustment interval
    if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
    {
        if (params.fPowAllowMinDifficultyBlocks)
        {
            // Special difficulty rule for testnet:
            // If the new block's timestamp is more than 2* 10 minutes
            // then allow mining of a min-difficulty block.
            if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
                return nProofOfWorkLimit;
            else
            {
                // Return the last non-special-min-difficulty-rules-block
                const CBlockIndex* pindex = pindexLast;
                while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
                    pindex = pindex->pprev;
                return pindex->nBits;
            }
        }
        return pindexLast->nBits;
    }

    // Go back by what we want to be 14 days worth of blocks
    // Litebitcoin: This fixes an issue where a 51% attack can change difficulty at will.
    // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
    int blockstogoback = params.DifficultyAdjustmentInterval()-1;
    if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())
        blockstogoback = params.DifficultyAdjustmentInterval();

    // Go back by what we want to be 14 days worth of blocks
    const CBlockIndex* pindexFirst = pindexLast;
    for (int i = 0; pindexFirst && i < blockstogoback; i++)
        pindexFirst = pindexFirst->pprev;

    assert(pindexFirst);

    return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}

unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    if (params.fPowNoRetargeting)
        return pindexLast->nBits;

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    if (nActualTimespan < params.nPowTargetTimespan/4)
        nActualTimespan = params.nPowTargetTimespan/4;
    if (nActualTimespan > params.nPowTargetTimespan*4)
        nActualTimespan = params.nPowTargetTimespan*4;

    // Retarget
    arith_uint256 bnNew;
    arith_uint256 bnOld;
    bnNew.SetCompact(pindexLast->nBits);
    bnOld = bnNew;
    // Litebitcoin: intermediate uint256 can overflow by 1 bit
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
    bool fShift = bnNew.bits() > bnPowLimit.bits() - 1;
    if (fShift)
        bnNew >>= 1;
    bnNew *= nActualTimespan;
    bnNew /= params.nPowTargetTimespan;
    if (fShift)
        bnNew <<= 1;

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    return bnNew.GetCompact();
}

unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) {
    /* current difficulty formula, dash - DarkGravity v3, written by Evan Duffield - evan@dash.org */
    const CBlockIndex *BlockLastSolved = pindexLast;
    const CBlockIndex *BlockReading = pindexLast;
    int64_t nActualTimespan = 0;
    int64_t LastBlockTime = 0;
    int64_t PastBlocksMin = 24;
    int64_t PastBlocksMax = 24;
    int64_t CountBlocks = 0;
    arith_uint256 PastDifficultyAverage;
    arith_uint256 PastDifficultyAveragePrev;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) {
        return UintToArith256(params.powLimit).GetCompact();
    }

    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
        CountBlocks++;

        if(CountBlocks <= PastBlocksMin) {
            if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
            else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks) + (arith_uint256().SetCompact(BlockReading->nBits))) / (CountBlocks + 1); }
            PastDifficultyAveragePrev = PastDifficultyAverage;
        }

        if(LastBlockTime > 0){
            int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime());
            nActualTimespan += Diff;
        }
        LastBlockTime = BlockReading->GetBlockTime();

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

    arith_uint256 bnNew(PastDifficultyAverage);

    int64_t _nTargetTimespan = CountBlocks * params.nPowTargetSpacing;

    if (nActualTimespan < _nTargetTimespan/3)
        nActualTimespan = _nTargetTimespan/3;
    if (nActualTimespan > _nTargetTimespan*3)
        nActualTimespan = _nTargetTimespan*3;

    // Retarget
    bnNew *= nActualTimespan;
    bnNew /= _nTargetTimespan;

    if (bnNew > UintToArith256(params.powLimit)){
        bnNew = UintToArith256(params.powLimit);
    }

    return bnNew.GetCompact();
}

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
 int DiffMode = 1;
 if (pindexLast->nHeight+1 < 3340)    { DiffMode = 1; }
 if (pindexLast->nHeight+1 >= 3340)   { DiffMode = 2; }
 if (DiffMode == 1) { return GetNextWorkRequired_V1(pindexLast, pblock, params); }
 if (DiffMode == 2) { return DarkGravityWave(pindexLast, pblock, params); }
 return DarkGravityWave(pindexLast, pblock, params);
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
        return false;

    // Check proof of work matches claimed amount
    if (UintToArith256(hash) > bnTarget)
        return false;

    return true;
}
<|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow 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 "tensorflow/core/grappler/optimizers/pin_to_host_optimizer.h"

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/grappler/graph_view.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/utils/symbolic_shapes.h"
#include "tensorflow/core/grappler/utils/topological_sort.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/str_util.h"

namespace tensorflow {
namespace grappler {
namespace internal {

// TODO(williamchan): Change this constant to be something smarter, maybe
// dynamically determined.
constexpr int64 kTensorMaxSize = 64;

// Find KernelDef for `node`.
Status TryFindKernelDef(const NodeDef& node, const KernelDef** kdef) {
  // Try find KernelDef for node.device, else GPU or CPU.
  for (const DeviceType& device :
       {node.device().c_str(), DEVICE_GPU, DEVICE_CPU}) {
    Status s = FindKernelDef(device, node, kdef, nullptr);
    if (s.ok()) {
      return Status::OK();
    }
  }

  return errors::NotFound("Could not find KernelDef for op: ", node.op());
}

// Check if all node's inputs are pinned to CPU memory.
bool AreAllNodeInputsPinnedToHost(const GraphView& graph, const NodeDef& node) {
  // Loop through all the inputs excluding the controlling nodes.
  for (const GraphView::OutputPort& fanin : graph.GetFanins(node, false)) {
    // Check if (the fanin) op's device is on CPU.
    if (str_util::StrContains(fanin.node->device(), DEVICE_CPU)) {
      continue;
    }

    // Check if (the fanin) op's output port is pinned to HostMemory.
    const OpDef* fanin_odef = nullptr;
    Status s = OpRegistry::Global()->LookUpOpDef(fanin.node->op(), &fanin_odef);
    if (!s.ok()) {
      LOG(INFO) << "Could not find OpDef for : " << fanin.node->op();
      return false;
    }

    const int output_arg_id =
        OpOutputPortIdToArgId(*fanin.node, *fanin_odef, fanin.port_id);
    if (output_arg_id < 0) {
      LOG(WARNING) << "Invalid port: " << fanin.port_id << "!\n"
                   << node.DebugString() << "\n"
                   << fanin.node->DebugString() << "\n"
                   << fanin_odef->DebugString();
      return false;
    }

    const KernelDef* fanin_kdef = nullptr;
    s = TryFindKernelDef(*fanin.node, &fanin_kdef);
    if (!s.ok()) {
      LOG(INFO) << "Could not find KernelDef for : " << fanin.node->op();
      return false;
    }

    bool fanin_pinned = false;
    for (const string& host_memory_arg : fanin_kdef->host_memory_arg()) {
      if (fanin_odef->output_arg(output_arg_id).name() == host_memory_arg) {
        fanin_pinned = true;
        break;
      }
    }

    if (!fanin_pinned) {
      return false;
    }
  }

  return true;
}

bool IsTensorIntegerAndSmall(const OpInfo::TensorProperties& prop) {
  // Check if Tensor is integer and small size.

  // Check type to be int32 or int64.
  if (prop.dtype() != DataType::DT_INT32 &&
      prop.dtype() != DataType::DT_INT64) {
    return false;
  }

  // Check size known and small.
  const int64 size = NumCoefficients(prop.shape());
  if (size < 0 || size > kTensorMaxSize) {
    return false;
  }

  return true;
}

bool AreAllNodeInputsAndOutputsIntsAndSmall(const GraphProperties& properties,
                                            const NodeDef& node) {
  for (const auto& prop : properties.GetInputProperties(node.name())) {
    if (!IsTensorIntegerAndSmall(prop)) {
      return false;
    }
  }

  for (const auto& prop : properties.GetOutputProperties(node.name())) {
    if (!IsTensorIntegerAndSmall(prop)) {
      return false;
    }
  }
  return true;
}

string TryFindHostDevice(const gtl::FlatSet<string>& devices,
                         bool has_device_cpu, const string& device) {
  // Force this node onto the CPU.
  if (device.empty() && has_device_cpu) {
    return "/device:CPU:0";
  } else if (str_util::StrContains(device, DEVICE_GPU)) {
    // Sometimes the cluster can have:
    //   devices = {"/device:CPU:0", "/device:XLA_GPU:0"}
    // and we need to handle them properly.
    for (const auto& device_match :
         {std::pair<string, string>("GPU", "CPU:0"),
          std::pair<string, string>("/device", "/device:CPU:0")}) {
      const string device_host =
          strings::StrCat(device.substr(0, device.rfind(device_match.first)),
                          device_match.second);
      if (devices.find(device_host) != devices.end()) {
        return device_host;
      }
    }
  }

  // We couldn't find an appropriate Host device, return original device.
  return device;
}

bool IsTPUGraphDef(const GraphDef& def) {
  for (const auto& node : def.node()) {
    if (node.op() == "TPUCompile" || node.op() == "TPUExecute" ||
        node.op() == "TPUPartitionedCall") {
      return true;
    }
  }
  return false;
}

// All the nodes that should be blacklisted and not swapped.
bool IsBlacklisted(const NodeDef& node) { return IsCollective(node); }
}  // end namespace internal

Status PinToHostOptimizer::Optimize(Cluster* cluster, const GrapplerItem& item,
                                    GraphDef* optimized_graph) {
  *optimized_graph = item.graph;

  // Skip all TPU graphs.
  if (internal::IsTPUGraphDef(*optimized_graph)) {
    return Status::OK();
  }

  GraphProperties properties(item);
  bool has_properties = false;
  GraphView graph(optimized_graph);

  gtl::FlatSet<string> devices;
  if (cluster) {
    const std::vector<string> device_names = cluster->GetDeviceNames();
    devices.insert(device_names.begin(), device_names.end());
  } else {
    devices = {"/device:CPU:0"};
  }

  const bool has_device_cpu = devices.find("/device:CPU:0") != devices.end();

  // Topologically sort the graph, so that we traverse the nodes in order. This
  // will help us discover producer->consumer chains of Host ops.
  TF_RETURN_IF_ERROR(TopologicalSort(optimized_graph));

  // All the Const nodes, and their original devices in topological order.
  std::vector<std::pair<NodeDef*, string>> const_nodes;

  for (auto& node : *optimized_graph->mutable_node()) {
    // Check if node already on CPU.
    if (str_util::StrContains(node.device(), DEVICE_CPU)) {
      continue;
    }

    // Skip these node types.
    if (internal::IsBlacklisted(node)) {
      continue;
    }

    // Check the node can be run on CPU.
    Status s = FindKernelDef(DEVICE_CPU, node, nullptr, nullptr);
    if (!s.ok()) {
      continue;
    }

    // Check all input's are pinned to CPU.
    if (!internal::AreAllNodeInputsPinnedToHost(graph, node)) {
      continue;
    }

    if (!has_properties) {
      // This is an expensive call, call it lazily.
      TF_RETURN_IF_ERROR(properties.InferStatically(false));
      has_properties = true;
    }

    // Check all inputs and outputs are integers and small.
    if (!internal::AreAllNodeInputsAndOutputsIntsAndSmall(properties, node)) {
      continue;
    }

    if (IsConstant(node)) {
      const_nodes.emplace_back(&node, node.device());
    }
    // Try and swap the device to Host.
    node.set_device(
        internal::TryFindHostDevice(devices, has_device_cpu, node.device()));
  }

  // Traverse all `const_nodes`, and map them back to GPU greedily.
  for (auto& it : const_nodes) {
    NodeDef* node = it.first;
    const string& device = it.second;

    // Check all the consumers of this node, if any of them are on the original
    // device, swap this node back onto the original device.
    for (const GraphView::InputPort& fanout : graph.GetFanouts(*node, false)) {
      if (fanout.node->device() == device) {
        node->set_device(device);
        break;
      }
    }
  }
  return Status::OK();
}

}  // end namespace grappler
}  // end namespace tensorflow
<commit_msg>Disable PinToHostOptimizer for NoOp.<commit_after>/* Copyright 2018 The TensorFlow 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 "tensorflow/core/grappler/optimizers/pin_to_host_optimizer.h"

#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/grappler/graph_view.h"
#include "tensorflow/core/grappler/grappler_item.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/utils/symbolic_shapes.h"
#include "tensorflow/core/grappler/utils/topological_sort.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/strings/str_util.h"

namespace tensorflow {
namespace grappler {
namespace internal {

// TODO(williamchan): Change this constant to be something smarter, maybe
// dynamically determined.
constexpr int64 kTensorMaxSize = 64;

// Find KernelDef for `node`.
Status TryFindKernelDef(const NodeDef& node, const KernelDef** kdef) {
  // Try find KernelDef for node.device, else GPU or CPU.
  for (const DeviceType& device :
       {node.device().c_str(), DEVICE_GPU, DEVICE_CPU}) {
    Status s = FindKernelDef(device, node, kdef, nullptr);
    if (s.ok()) {
      return Status::OK();
    }
  }

  return errors::NotFound("Could not find KernelDef for op: ", node.op());
}

// Check if all node's inputs are pinned to CPU memory.
bool AreAllNodeInputsPinnedToHost(const GraphView& graph, const NodeDef& node) {
  // Loop through all the inputs excluding the controlling nodes.
  for (const GraphView::OutputPort& fanin : graph.GetFanins(node, false)) {
    // Check if (the fanin) op's device is on CPU.
    if (str_util::StrContains(fanin.node->device(), DEVICE_CPU)) {
      continue;
    }

    // Check if (the fanin) op's output port is pinned to HostMemory.
    const OpDef* fanin_odef = nullptr;
    Status s = OpRegistry::Global()->LookUpOpDef(fanin.node->op(), &fanin_odef);
    if (!s.ok()) {
      LOG(INFO) << "Could not find OpDef for : " << fanin.node->op();
      return false;
    }

    const int output_arg_id =
        OpOutputPortIdToArgId(*fanin.node, *fanin_odef, fanin.port_id);
    if (output_arg_id < 0) {
      LOG(WARNING) << "Invalid port: " << fanin.port_id << "!\n"
                   << node.DebugString() << "\n"
                   << fanin.node->DebugString() << "\n"
                   << fanin_odef->DebugString();
      return false;
    }

    const KernelDef* fanin_kdef = nullptr;
    s = TryFindKernelDef(*fanin.node, &fanin_kdef);
    if (!s.ok()) {
      LOG(INFO) << "Could not find KernelDef for : " << fanin.node->op();
      return false;
    }

    bool fanin_pinned = false;
    for (const string& host_memory_arg : fanin_kdef->host_memory_arg()) {
      if (fanin_odef->output_arg(output_arg_id).name() == host_memory_arg) {
        fanin_pinned = true;
        break;
      }
    }

    if (!fanin_pinned) {
      return false;
    }
  }

  return true;
}

bool IsTensorIntegerAndSmall(const OpInfo::TensorProperties& prop) {
  // Check if Tensor is integer and small size.

  // Check type to be int32 or int64.
  if (prop.dtype() != DataType::DT_INT32 &&
      prop.dtype() != DataType::DT_INT64) {
    return false;
  }

  // Check size known and small.
  const int64 size = NumCoefficients(prop.shape());
  if (size < 0 || size > kTensorMaxSize) {
    return false;
  }

  return true;
}

bool AreAllNodeInputsAndOutputsIntsAndSmall(const GraphProperties& properties,
                                            const NodeDef& node) {
  for (const auto& prop : properties.GetInputProperties(node.name())) {
    if (!IsTensorIntegerAndSmall(prop)) {
      return false;
    }
  }

  for (const auto& prop : properties.GetOutputProperties(node.name())) {
    if (!IsTensorIntegerAndSmall(prop)) {
      return false;
    }
  }
  return true;
}

string TryFindHostDevice(const gtl::FlatSet<string>& devices,
                         bool has_device_cpu, const string& device) {
  // Force this node onto the CPU.
  if (device.empty() && has_device_cpu) {
    return "/device:CPU:0";
  } else if (str_util::StrContains(device, DEVICE_GPU)) {
    // Sometimes the cluster can have:
    //   devices = {"/device:CPU:0", "/device:XLA_GPU:0"}
    // and we need to handle them properly.
    for (const auto& device_match :
         {std::pair<string, string>("GPU", "CPU:0"),
          std::pair<string, string>("/device", "/device:CPU:0")}) {
      const string device_host =
          strings::StrCat(device.substr(0, device.rfind(device_match.first)),
                          device_match.second);
      if (devices.find(device_host) != devices.end()) {
        return device_host;
      }
    }
  }

  // We couldn't find an appropriate Host device, return original device.
  return device;
}

bool IsTPUGraphDef(const GraphDef& def) {
  for (const auto& node : def.node()) {
    if (node.op() == "TPUCompile" || node.op() == "TPUExecute" ||
        node.op() == "TPUPartitionedCall") {
      return true;
    }
  }
  return false;
}

// All the nodes that should be blacklisted and not swapped.
bool IsBlacklisted(const NodeDef& node) {
  return
      // Collective ops should not be swapped.
      IsCollective(node) ||
      // NoOp breaks perf regression tests (probably due to group dependencies).
      IsNoOp(node);
}
}  // end namespace internal

Status PinToHostOptimizer::Optimize(Cluster* cluster, const GrapplerItem& item,
                                    GraphDef* optimized_graph) {
  *optimized_graph = item.graph;

  // Skip all TPU graphs.
  if (internal::IsTPUGraphDef(*optimized_graph)) {
    return Status::OK();
  }

  GraphProperties properties(item);
  bool has_properties = false;
  GraphView graph(optimized_graph);

  gtl::FlatSet<string> devices;
  if (cluster) {
    const std::vector<string> device_names = cluster->GetDeviceNames();
    devices.insert(device_names.begin(), device_names.end());
  } else {
    devices = {"/device:CPU:0"};
  }

  const bool has_device_cpu = devices.find("/device:CPU:0") != devices.end();

  // Topologically sort the graph, so that we traverse the nodes in order. This
  // will help us discover producer->consumer chains of Host ops.
  TF_RETURN_IF_ERROR(TopologicalSort(optimized_graph));

  // All the Const nodes, and their original devices in topological order.
  std::vector<std::pair<NodeDef*, string>> const_nodes;

  for (auto& node : *optimized_graph->mutable_node()) {
    // Check if node already on CPU.
    if (str_util::StrContains(node.device(), DEVICE_CPU)) {
      continue;
    }

    // Skip these node types.
    if (internal::IsBlacklisted(node)) {
      continue;
    }

    // Check the node can be run on CPU.
    Status s = FindKernelDef(DEVICE_CPU, node, nullptr, nullptr);
    if (!s.ok()) {
      continue;
    }

    // Check all input's are pinned to CPU.
    if (!internal::AreAllNodeInputsPinnedToHost(graph, node)) {
      continue;
    }

    if (!has_properties) {
      // This is an expensive call, call it lazily.
      TF_RETURN_IF_ERROR(properties.InferStatically(false));
      has_properties = true;
    }

    // Check all inputs and outputs are integers and small.
    if (!internal::AreAllNodeInputsAndOutputsIntsAndSmall(properties, node)) {
      continue;
    }

    if (IsConstant(node)) {
      const_nodes.emplace_back(&node, node.device());
    }
    // Try and swap the device to Host.
    node.set_device(
        internal::TryFindHostDevice(devices, has_device_cpu, node.device()));
  }

  // Traverse all `const_nodes`, and map them back to GPU greedily.
  for (auto& it : const_nodes) {
    NodeDef* node = it.first;
    const string& device = it.second;

    // Check all the consumers of this node, if any of them are on the original
    // device, swap this node back onto the original device.
    for (const GraphView::InputPort& fanout : graph.GetFanouts(*node, false)) {
      if (fanout.node->device() == device) {
        node->set_device(device);
        break;
      }
    }
  }
  return Status::OK();
}

}  // end namespace grappler
}  // end namespace tensorflow
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osgSim/MultiSwitch>

#include <algorithm>

using namespace osgSim;
using namespace osg;

MultiSwitch::MultiSwitch():
    _newChildDefaultValue(true),
    _activeSwitchSet(0)
{
}

MultiSwitch::MultiSwitch(const MultiSwitch& sw,const osg::CopyOp& copyop):
    osg::Group(sw,copyop),
    _newChildDefaultValue(sw._newChildDefaultValue),
    _activeSwitchSet(sw._activeSwitchSet),
    _values(sw._values)
{
}

void MultiSwitch::traverse(osg::NodeVisitor& nv)
{
    if (nv.getTraversalMode()==osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
    {

        if (_activeSwitchSet<_values.size())
        {
            for(unsigned int pos=0;pos<_children.size();++pos)
            {
                if (_values[_activeSwitchSet][pos]) _children[pos]->accept(nv);
            }
        }
    }
    else
    {
        Group::traverse(nv);
    }
}

bool MultiSwitch::addChild( osg::Node *child)
{
    unsigned int childPosition = _children.size();
    if (Group::addChild(child))
    {
        for(SwitchSetList::iterator itr=_values.begin();
            itr!=_values.end();
            ++itr)
        {
            ValueList& values = *itr;
            if (_children.size()>_values.size())
            {
                values.resize(_children.size(),_newChildDefaultValue);
                values[childPosition]=_newChildDefaultValue;
            }
        }
        return true;
    }
    return false;
}

bool MultiSwitch::insertChild( unsigned int index, osg::Node *child)
{
    if (Group::insertChild(index,child))
    {
        for(SwitchSetList::iterator itr=_values.begin();
            itr!=_values.end();
            ++itr)
        {
            ValueList& values = *itr;
            if (index>=_values.size())
            {
                values.push_back(_newChildDefaultValue);
            }
            else
            {
                values.insert(values.begin()+index, _newChildDefaultValue);
            }
        }

        return true;
    }
    return false;
}

bool MultiSwitch::removeChild( osg::Node *child )
{
    // find the child's position.
    unsigned int pos=getChildIndex(child);
    if (pos==_children.size()) return false;

    for(SwitchSetList::iterator itr=_values.begin();
        itr!=_values.end();
        ++itr)
    {
        ValueList& values = *itr;
        values.erase(values.begin()+pos);
    }

    return Group::removeChild(child);
}

void MultiSwitch::setValue(unsigned int switchSet, unsigned int pos,bool value)
{
    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    if (pos>=values.size()) values.resize(pos+1,_newChildDefaultValue);
    values[pos]=value;
}

void MultiSwitch::setChildValue(const osg::Node* child,unsigned int switchSet, bool value)
{
    expandToEncompassSwitchSet(switchSet);

    // find the child's position.
    unsigned int pos=getChildIndex(child);
    if (pos==_children.size()) return;

    ValueList& values = _values[switchSet];
    values[pos]=value;
}

bool MultiSwitch::getValue(unsigned int switchSet, unsigned int pos) const
{
    if (switchSet>=_values.size()) return false;

    const ValueList& values = _values[switchSet];
    if (pos>=values.size()) return false;

    return values[pos];
}

bool MultiSwitch::getChildValue(const osg::Node* child, unsigned int switchSet) const
{
    if (switchSet>=_values.size()) return false;

    // find the child's position.
    unsigned int pos=getChildIndex(child);
    if (pos==_children.size()) return false;

    const ValueList& values = _values[switchSet];
    return values[pos];
}

void MultiSwitch::expandToEncompassSwitchSet(unsigned int switchSet)
{
    if (switchSet>=_values.size())
    {
        // need to expand arrays.
        unsigned int originalSize = _values.size();
        _values.resize(switchSet+1);
        for(unsigned int i=originalSize;i<=switchSet;++i)
        {
            ValueList& values = _values[i];
            values.resize(_children.size(),_newChildDefaultValue);
        }
    }
}

bool MultiSwitch::setAllChildrenOff(unsigned int switchSet)
{
    _newChildDefaultValue = false;

    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    for(ValueList::iterator itr=values.begin();
        itr!=values.end();
        ++itr)
    {
        *itr = false;
    }
    return true;
}

bool MultiSwitch::setAllChildrenOn(unsigned int switchSet)
{
    _newChildDefaultValue = true;

    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    for(ValueList::iterator itr=values.begin();
        itr!=values.end();
        ++itr)
    {
        *itr = true;
    }
    return true;
}

bool MultiSwitch::setSingleChildOn(unsigned int switchSet, unsigned int pos)
{
    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    for(ValueList::iterator itr=values.begin();
        itr!=values.end();
        ++itr)
    {
        *itr = false;
    }
    setValue(switchSet, pos,true);
    return true;
}

void MultiSwitch::setSwitchSetList(const SwitchSetList& switchSetList)
{
    expandToEncompassSwitchSet(switchSetList.size());

    _values = switchSetList;
}

void MultiSwitch::setValueList(unsigned int switchSet, const ValueList& values)
{
    expandToEncompassSwitchSet(switchSet);

    _values[switchSet] = values;
}
<commit_msg>From Brede Johansen,<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/
#include <osgSim/MultiSwitch>

#include <algorithm>

using namespace osgSim;
using namespace osg;

MultiSwitch::MultiSwitch():
    _newChildDefaultValue(true),
    _activeSwitchSet(0)
{
}

MultiSwitch::MultiSwitch(const MultiSwitch& sw,const osg::CopyOp& copyop):
    osg::Group(sw,copyop),
    _newChildDefaultValue(sw._newChildDefaultValue),
    _activeSwitchSet(sw._activeSwitchSet),
    _values(sw._values)
{
}

void MultiSwitch::traverse(osg::NodeVisitor& nv)
{
    if (nv.getTraversalMode()==osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN)
    {

        if (_activeSwitchSet<_values.size())
        {
            for(unsigned int pos=0;pos<_children.size();++pos)
            {
                if (_values[_activeSwitchSet][pos]) _children[pos]->accept(nv);
            }
        }
    }
    else
    {
        Group::traverse(nv);
    }
}

bool MultiSwitch::addChild( osg::Node *child)
{
    unsigned int childPosition = _children.size();
    if (Group::addChild(child))
    {
        for(SwitchSetList::iterator itr=_values.begin();
            itr!=_values.end();
            ++itr)
        {
            ValueList& values = *itr;
            if (_children.size()>values.size())
            {
                values.resize(_children.size(),_newChildDefaultValue);
                values[childPosition]=_newChildDefaultValue;
            }
        }
        return true;
    }
    return false;
}

bool MultiSwitch::insertChild( unsigned int index, osg::Node *child)
{
    if (Group::insertChild(index,child))
    {
        for(SwitchSetList::iterator itr=_values.begin();
            itr!=_values.end();
            ++itr)
        {
            ValueList& values = *itr;
            if (index>=values.size())
            {
                values.push_back(_newChildDefaultValue);
            }
            else
            {
                values.insert(values.begin()+index, _newChildDefaultValue);
            }
        }

        return true;
    }
    return false;
}

bool MultiSwitch::removeChild( osg::Node *child )
{
    // find the child's position.
    unsigned int pos=getChildIndex(child);
    if (pos==_children.size()) return false;

    for(SwitchSetList::iterator itr=_values.begin();
        itr!=_values.end();
        ++itr)
    {
        ValueList& values = *itr;
        values.erase(values.begin()+pos);
    }

    return Group::removeChild(child);
}

void MultiSwitch::setValue(unsigned int switchSet, unsigned int pos,bool value)
{
    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    if (pos>=values.size()) values.resize(pos+1,_newChildDefaultValue);
    values[pos]=value;
}

void MultiSwitch::setChildValue(const osg::Node* child,unsigned int switchSet, bool value)
{
    expandToEncompassSwitchSet(switchSet);

    // find the child's position.
    unsigned int pos=getChildIndex(child);
    if (pos==_children.size()) return;

    ValueList& values = _values[switchSet];
    values[pos]=value;
}

bool MultiSwitch::getValue(unsigned int switchSet, unsigned int pos) const
{
    if (switchSet>=_values.size()) return false;

    const ValueList& values = _values[switchSet];
    if (pos>=values.size()) return false;

    return values[pos];
}

bool MultiSwitch::getChildValue(const osg::Node* child, unsigned int switchSet) const
{
    if (switchSet>=_values.size()) return false;

    // find the child's position.
    unsigned int pos=getChildIndex(child);
    if (pos==_children.size()) return false;

    const ValueList& values = _values[switchSet];
    return values[pos];
}

void MultiSwitch::expandToEncompassSwitchSet(unsigned int switchSet)
{
    if (switchSet>=_values.size())
    {
        // need to expand arrays.
        unsigned int originalSize = _values.size();
        _values.resize(switchSet+1);
        for(unsigned int i=originalSize;i<=switchSet;++i)
        {
            ValueList& values = _values[i];
            values.resize(_children.size(),_newChildDefaultValue);
        }
    }
}

bool MultiSwitch::setAllChildrenOff(unsigned int switchSet)
{
    _newChildDefaultValue = false;

    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    for(ValueList::iterator itr=values.begin();
        itr!=values.end();
        ++itr)
    {
        *itr = false;
    }
    return true;
}

bool MultiSwitch::setAllChildrenOn(unsigned int switchSet)
{
    _newChildDefaultValue = true;

    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    for(ValueList::iterator itr=values.begin();
        itr!=values.end();
        ++itr)
    {
        *itr = true;
    }
    return true;
}

bool MultiSwitch::setSingleChildOn(unsigned int switchSet, unsigned int pos)
{
    expandToEncompassSwitchSet(switchSet);

    ValueList& values = _values[switchSet];
    for(ValueList::iterator itr=values.begin();
        itr!=values.end();
        ++itr)
    {
        *itr = false;
    }
    setValue(switchSet, pos,true);
    return true;
}

void MultiSwitch::setSwitchSetList(const SwitchSetList& switchSetList)
{
    expandToEncompassSwitchSet(switchSetList.size());

    _values = switchSetList;
}

void MultiSwitch::setValueList(unsigned int switchSet, const ValueList& values)
{
    expandToEncompassSwitchSet(switchSet);

    _values[switchSet] = values;
}
<|endoftext|>


<commit_before>/*
A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].

Write a function:

int solution(int A[], int N);

that, given an array A consisting of N integers, returns the maximum sum of any slice of A.

For example, given array A such that:

A[0] = 3  A[1] = 2  A[2] = -6
A[3] = 4  A[4] = 0
the function should return 5 because:

(3, 4) is a slice of A that has sum 4,
(2, 2) is a slice of A that has sum −6,
(0, 1) is a slice of A that has sum 5,
no other slice of A has sum greater than (0, 1).
Assume that:

N is an integer within the range [1..1,000,000];
each element of array A is an integer within the range [−1,000,000..1,000,000];
the result will be an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.

Copyright 2009–2015 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
*/
<commit_msg>Update solution.cpp<commit_after>// you can use includes, for example:
// #include <algorithm>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

void process(vector<int> &A, int first, int last, int &max, int &max_i, bool reverse) {
    int sum(0);
    for(unsigned int j=first; j<=last; ++j) {
        int i = j;
        if( reverse )
            i = last-first-j;
        sum += A[i];
        if( sum>max ) {
            max = sum;
            max_i = i;
        }
    }
}

int solution(vector<int> &A) {
    // write your code in C++11
    // 0-->q in [0,N-1]
    int max_1(A[0]);
    int max_q(0);
    process( A, 0, A.size()-1, max_1, max_q, false );
    // cout << max_q << " " << max_1 << endl;

    // p<--N-1 in [0,N-1]
    int max_2(A.back());
    int max_p(A.size()-1);
    process( A, 0, A.size()-1, max_2, max_p, true );
    // cout << max_p << " " << max_2 << endl;

    int max;
    if( max_1 > max_2 ) {
        // p<--q in [0,max_q]
        max = A[max_q];
        int max_p(max_q);
        process( A, 0, max_q, max, max_p, true );
        // cout << max_p << " " << max << endl;
    }
    else {
        // p-->q in [max_p,N-1]
        max = A[max_p];
        int max_q(max_p);
        process( A, max_p, A.size()-1, max, max_q, false );
        // cout << max_q << " " << max << endl;
    }

    return max;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
 *
 * 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 names of Stanford University or Willow Garage, Inc. 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 <ros/ros.h>
#include <cv_tracker/image_obj_ranged.h>
#include <std_msgs/Header.h>
#include <fusion_func.h>
#include <runtime_manager/ConfigCarFusion.h>

static void publishTopic();
static ros::Publisher fused_objects;
static std_msgs::Header sensor_header;

static void DetectedObjectsCallback(const cv_tracker::image_obj& image_object)
{
	setDetectedObjects(image_object);

	fuse();
	publishTopic();
}

/*static void ScanImageCallback(const scan2image::ScanImage& scan_image)
{
	setScanImage(scan_image);
	sensor_header = scan_image.header;

	calcDistance();
	publishTopic();
}*/

static void PointsImageCallback(const points2image::PointsImage& points_image)
{
	setPointsImage(points_image);
	sensor_header = points_image.header;

	fuse();
	publishTopic();
}

static void publishTopic()
{
	/*
	 * Publish topic(obj position ranged).
	 */
	cv_tracker::image_obj_ranged fused_objects_msg;
	fused_objects_msg.header = sensor_header;
	fused_objects_msg.type = getObjectsType();
	fused_objects_msg.obj = getObjectsRectRanged();
	fused_objects.publish(fused_objects_msg);
}

static void config_cb(const runtime_manager::ConfigCarFusion::ConstPtr& param)
{
	setParams(param->min_low_height,
			param->max_low_height,
			param->max_height,
			param->min_points,
			param->dispersion);
}

int main(int argc, char **argv)
{
	init();
	ros::init(argc, argv, "range_fusion");

	ros::NodeHandle n;
	ros::NodeHandle private_nh("~");

	std::string image_topic;
	std::string points_topic;
	if (private_nh.getParam("image_node", image_topic))
	{
		ROS_INFO("Setting image node to %s", image_topic.c_str());
	}
	else
	{
		ROS_INFO("No image node received, defaulting to image_obj, you can use _image_node:=YOUR_TOPIC");
		image_topic = "/image_obj";
	}
	if (private_nh.getParam("points_node", points_topic))
	{
		ROS_INFO("Setting points node to %s", points_topic.c_str());
	}
	else
	{
		ROS_INFO("No points node received, defaulting to vscan_image, you can use _points_node:=YOUR_TOPIC");
		points_topic = "/vscan_image";
	}

	ros::Subscriber image_obj_sub = n.subscribe(image_topic, 1, DetectedObjectsCallback);
	//ros::Subscriber scan_image_sub = n.subscribe("scan_image", 1, ScanImageCallback);
	ros::Subscriber points_image_sub =n.subscribe(points_topic, 1, PointsImageCallback);
#if _DEBUG
	ros::Subscriber image_sub = n.subscribe(IMAGE_TOPIC, 1, IMAGE_CALLBACK);
#endif
	fused_objects = n.advertise<cv_tracker::image_obj_ranged>("image_obj_ranged", 1);

	ros::Subscriber config_subscriber;
	std::string config_topic("/config");
	config_topic += ros::this_node::getNamespace() + "/fusion";
	config_subscriber = n.subscribe(config_topic, 1, config_cb);

	ros::spin();
	destroy();

	return 0;
}
<commit_msg>Fixed topic names to relative ones<commit_after>/*
 * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
 *
 * 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 names of Stanford University or Willow Garage, Inc. 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 <ros/ros.h>
#include <cv_tracker/image_obj_ranged.h>
#include <std_msgs/Header.h>
#include <fusion_func.h>
#include <runtime_manager/ConfigCarFusion.h>

static void publishTopic();
static ros::Publisher fused_objects;
static std_msgs::Header sensor_header;

static void DetectedObjectsCallback(const cv_tracker::image_obj& image_object)
{
	setDetectedObjects(image_object);

	fuse();
	publishTopic();
}

/*static void ScanImageCallback(const scan2image::ScanImage& scan_image)
{
	setScanImage(scan_image);
	sensor_header = scan_image.header;

	calcDistance();
	publishTopic();
}*/

static void PointsImageCallback(const points2image::PointsImage& points_image)
{
	setPointsImage(points_image);
	sensor_header = points_image.header;

	fuse();
	publishTopic();
}

static void publishTopic()
{
	/*
	 * Publish topic(obj position ranged).
	 */
	cv_tracker::image_obj_ranged fused_objects_msg;
	fused_objects_msg.header = sensor_header;
	fused_objects_msg.type = getObjectsType();
	fused_objects_msg.obj = getObjectsRectRanged();
	fused_objects.publish(fused_objects_msg);
}

static void config_cb(const runtime_manager::ConfigCarFusion::ConstPtr& param)
{
	setParams(param->min_low_height,
			param->max_low_height,
			param->max_height,
			param->min_points,
			param->dispersion);
}

int main(int argc, char **argv)
{
	init();
	ros::init(argc, argv, "range_fusion");

	ros::NodeHandle n;
	ros::NodeHandle private_nh("~");

	std::string image_topic;
	std::string points_topic;
	if (private_nh.getParam("image_node", image_topic))
	{
		ROS_INFO("Setting image node to %s", image_topic.c_str());
	}
	else
	{
		ROS_INFO("No image node received, defaulting to image_obj, you can use _image_node:=YOUR_TOPIC");
		image_topic = "image_obj";
	}
	if (private_nh.getParam("points_node", points_topic))
	{
		ROS_INFO("Setting points node to %s", points_topic.c_str());
	}
	else
	{
		ROS_INFO("No points node received, defaulting to vscan_image, you can use _points_node:=YOUR_TOPIC");
		points_topic = "/vscan_image";
	}

	ros::Subscriber image_obj_sub = n.subscribe(image_topic, 1, DetectedObjectsCallback);
	//ros::Subscriber scan_image_sub = n.subscribe("scan_image", 1, ScanImageCallback);
	ros::Subscriber points_image_sub =n.subscribe(points_topic, 1, PointsImageCallback);
#if _DEBUG
	ros::Subscriber image_sub = n.subscribe(IMAGE_TOPIC, 1, IMAGE_CALLBACK);
#endif
	fused_objects = n.advertise<cv_tracker::image_obj_ranged>("image_obj_ranged", 1);

	ros::Subscriber config_subscriber;
	std::string config_topic("/config");
	config_topic += ros::this_node::getNamespace() + "/fusion";
	config_subscriber = n.subscribe(config_topic, 1, config_cb);

	ros::spin();
	destroy();

	return 0;
}
<|endoftext|>


<commit_before>#include "world.hpp"

void world_t::update_chunks(){

}
<commit_msg>Delete world.cpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: defaultoptions.cxx,v $
 * $Revision: 1.14 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include <svtools/defaultoptions.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configitem.hxx>
#include <unotools/configmgr.hxx>
#include <tools/debug.hxx>
#include <tools/resmgr.hxx>
#include <tools/urlobj.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <osl/mutex.hxx>

#include <vos/process.hxx>
#include <unotools/localfilehelper.hxx>
#include <rtl/instance.hxx>

#include <itemholder1.hxx>

using namespace osl;
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

// define ----------------------------------------------------------------

#define ASCII_STR(s)                OUString( RTL_CONSTASCII_USTRINGPARAM(s) )

#define DEFAULTPATH__ADDIN          0
#define DEFAULTPATH__AUTOCORRECT    1
#define DEFAULTPATH__AUTOTEXT       2
#define DEFAULTPATH__BACKUP         3
#define DEFAULTPATH__BASIC          4
#define DEFAULTPATH__BITMAP         5
#define DEFAULTPATH__CONFIG         6
#define DEFAULTPATH__DICTIONARY     7
#define DEFAULTPATH__FAVORITES      8
#define DEFAULTPATH__FILTER         9
#define DEFAULTPATH__GALLERY        10
#define DEFAULTPATH__GRAPHIC        11
#define DEFAULTPATH__HELP           12
#define DEFAULTPATH__LINGUISTIC     13
#define DEFAULTPATH__MODULE         14
#define DEFAULTPATH__PALETTE        15
#define DEFAULTPATH__PLUGIN         16
#define DEFAULTPATH__TEMP           17
#define DEFAULTPATH__TEMPLATE       18
#define DEFAULTPATH__USERCONFIG     19
#define DEFAULTPATH__USERDICTIONARY 20
#define DEFAULTPATH__WORK           21

// class SvtDefaultOptions_Impl ------------------------------------------

class SvtDefaultOptions_Impl : public utl::ConfigItem
{
public:
    String          m_aAddinPath;
    String          m_aAutoCorrectPath;
    String          m_aAutoTextPath;
    String          m_aBackupPath;
    String          m_aBasicPath;
    String          m_aBitmapPath;
    String          m_aConfigPath;
    String          m_aDictionaryPath;
    String          m_aFavoritesPath;
    String          m_aFilterPath;
    String          m_aGalleryPath;
    String          m_aGraphicPath;
    String          m_aHelpPath;
    String          m_aLinguisticPath;
    String          m_aModulePath;
    String          m_aPalettePath;
    String          m_aPluginPath;
    String          m_aTempPath;
    String          m_aTemplatePath;
    String          m_aUserConfigPath;
    String          m_aUserDictionaryPath;
    String          m_aWorkPath;

                    SvtDefaultOptions_Impl();

    String          GetDefaultPath( USHORT nId ) const;
};

// global ----------------------------------------------------------------

static SvtDefaultOptions_Impl*  pOptions = NULL;
static sal_Int32                nRefCount = 0;

typedef String SvtDefaultOptions_Impl:: *PathStrPtr;

struct PathToDefaultMapping_Impl
{
    SvtPathOptions::Pathes  _ePath;
    PathStrPtr              _pDefaultPath;
};

static PathToDefaultMapping_Impl __READONLY_DATA PathMap_Impl[] =
{
    { SvtPathOptions::PATH_ADDIN,           &SvtDefaultOptions_Impl::m_aAddinPath },
    { SvtPathOptions::PATH_AUTOCORRECT, &SvtDefaultOptions_Impl::m_aAutoCorrectPath },
    { SvtPathOptions::PATH_AUTOTEXT,        &SvtDefaultOptions_Impl::m_aAutoTextPath },
    { SvtPathOptions::PATH_BACKUP,      &SvtDefaultOptions_Impl::m_aBackupPath },
    { SvtPathOptions::PATH_BASIC,           &SvtDefaultOptions_Impl::m_aBasicPath },
    { SvtPathOptions::PATH_BITMAP,      &SvtDefaultOptions_Impl::m_aBitmapPath },
    { SvtPathOptions::PATH_CONFIG,      &SvtDefaultOptions_Impl::m_aConfigPath },
    { SvtPathOptions::PATH_DICTIONARY,  &SvtDefaultOptions_Impl::m_aDictionaryPath },
    { SvtPathOptions::PATH_FAVORITES,       &SvtDefaultOptions_Impl::m_aFavoritesPath },
    { SvtPathOptions::PATH_FILTER,      &SvtDefaultOptions_Impl::m_aFilterPath },
    { SvtPathOptions::PATH_GALLERY,     &SvtDefaultOptions_Impl::m_aGalleryPath },
    { SvtPathOptions::PATH_GRAPHIC,     &SvtDefaultOptions_Impl::m_aGraphicPath },
    { SvtPathOptions::PATH_HELP,            &SvtDefaultOptions_Impl::m_aHelpPath },
    { SvtPathOptions::PATH_LINGUISTIC,  &SvtDefaultOptions_Impl::m_aLinguisticPath },
    { SvtPathOptions::PATH_MODULE,      &SvtDefaultOptions_Impl::m_aModulePath },
    { SvtPathOptions::PATH_PALETTE,     &SvtDefaultOptions_Impl::m_aPalettePath },
    { SvtPathOptions::PATH_PLUGIN,      &SvtDefaultOptions_Impl::m_aPluginPath },
    { SvtPathOptions::PATH_TEMP,          &SvtDefaultOptions_Impl::m_aTempPath },
    { SvtPathOptions::PATH_TEMPLATE,        &SvtDefaultOptions_Impl::m_aTemplatePath },
    { SvtPathOptions::PATH_USERCONFIG,  &SvtDefaultOptions_Impl::m_aUserConfigPath },
    { SvtPathOptions::PATH_WORK,            &SvtDefaultOptions_Impl::m_aWorkPath }
};

// functions -------------------------------------------------------------

Sequence< OUString > GetDefaultPropertyNames()
{
    static const char* aPropNames[] =
    {
        "Addin",            // PATH_ADDIN
        "AutoCorrect",      // PATH_AUTOCORRECT
        "AutoText",         // PATH_AUTOTEXT
        "Backup",           // PATH_BACKUP
        "Basic",            // PATH_BASIC
        "Bitmap",           // PATH_BITMAP
        "Config",           // PATH_CONFIG
        "Dictionary",       // PATH_DICTIONARY
        "Favorite",         // PATH_FAVORITES
        "Filter",           // PATH_FILTER
        "Gallery",          // PATH_GALLERY
        "Graphic",          // PATH_GRAPHIC
        "Help",             // PATH_HELP
        "Linguistic",       // PATH_LINGUISTIC
        "Module",           // PATH_MODULE
        "Palette",          // PATH_PALETTE
        "Plugin",           // PATH_PLUGIN
        "Temp",             // PATH_TEMP
        "Template",         // PATH_TEMPLATE
        "UserConfig",       // PATH_USERCONFIG
        "Work"              // PATH_WORK
    };

    const int nCount = sizeof( aPropNames ) / sizeof( const char* );
    Sequence< OUString > aNames( nCount );
    OUString* pNames = aNames.getArray();
    for ( int i = 0; i < nCount; i++ )
        pNames[i] = OUString::createFromAscii( aPropNames[i] );

    return aNames;
}

// class SvtDefaultOptions_Impl ------------------------------------------

String SvtDefaultOptions_Impl::GetDefaultPath( USHORT nId ) const
{
    String aRet;
    USHORT nIdx = 0;

    while ( PathMap_Impl[nIdx]._ePath <= SvtPathOptions::PATH_WORK )
    {
        if ( nId == PathMap_Impl[nIdx]._ePath && PathMap_Impl[nIdx]._pDefaultPath )
        {
            aRet = this->*(PathMap_Impl[nIdx]._pDefaultPath);
            if ( nId == SvtPathOptions::PATH_ADDIN ||
                 nId == SvtPathOptions::PATH_FILTER ||
                 nId == SvtPathOptions::PATH_HELP ||
                 nId == SvtPathOptions::PATH_MODULE ||
                 nId == SvtPathOptions::PATH_PLUGIN )
            {
                String aTmp;
                ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aRet, aTmp );
                aRet = aTmp;
            }

            break;
        }
        ++nIdx;
    }

    return aRet;
}

// -----------------------------------------------------------------------

SvtDefaultOptions_Impl::SvtDefaultOptions_Impl() : ConfigItem( ASCII_STR("Office.Common/Path/Default") )
{
    /*ConfigManager* pCfgMgr =*/ ConfigManager::GetConfigManager();
    Sequence< OUString > aNames = GetDefaultPropertyNames();
    Sequence< Any > aValues = GetProperties( aNames );
    EnableNotification( aNames );
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT( aValues.getLength() == aNames.getLength(), "GetProperties failed" );
    if ( aValues.getLength() == aNames.getLength() )
    {
        SvtPathOptions aPathOpt;
        OUString aTempStr, aFullPath;

        for ( int nProp = 0; nProp < aNames.getLength(); nProp++ )
        {
            if ( pValues[nProp].hasValue() )
            {
                switch ( pValues[nProp].getValueTypeClass() )
                {
                    case ::com::sun::star::uno::TypeClass_STRING :
                    {
                        // multi pathes
                        if ( pValues[nProp] >>= aTempStr )
                            aFullPath = aPathOpt.SubstituteVariable( aTempStr );
                        else
                        {
                            DBG_ERRORFILE( "any operator >>= failed" );
                        }
                        break;
                    }

                    case ::com::sun::star::uno::TypeClass_SEQUENCE :
                    {
                        // single pathes
                        aFullPath = OUString();
                        Sequence < OUString > aList;
                        if ( pValues[nProp] >>= aList )
                        {
                            sal_Int32 nCount = aList.getLength();
                            for ( sal_Int32 nPosition = 0; nPosition < nCount; ++nPosition )
                            {
                                aTempStr = aPathOpt.SubstituteVariable( aList[ nPosition ] );
                                aFullPath += aTempStr;
                                if ( nPosition < nCount-1 )
                                    aFullPath += OUString( RTL_CONSTASCII_USTRINGPARAM(";") );
                            }
                        }
                        else
                        {
                            DBG_ERRORFILE( "any operator >>= failed" );
                        }
                        break;
                    }

                    default:
                    {
                        DBG_ERRORFILE( "Wrong any type" );
                    }
                }

                switch ( nProp )
                {
                    case DEFAULTPATH__ADDIN:            m_aAddinPath = String( aFullPath );         break;
                    case DEFAULTPATH__AUTOCORRECT:      m_aAutoCorrectPath = String( aFullPath );   break;
                    case DEFAULTPATH__AUTOTEXT:         m_aAutoTextPath = String( aFullPath );      break;
                    case DEFAULTPATH__BACKUP:           m_aBackupPath = String( aFullPath );        break;
                    case DEFAULTPATH__BASIC:            m_aBasicPath = String( aFullPath );         break;
                    case DEFAULTPATH__BITMAP:           m_aBitmapPath = String( aFullPath );        break;
                    case DEFAULTPATH__CONFIG:           m_aConfigPath = String( aFullPath );        break;
                    case DEFAULTPATH__DICTIONARY:       m_aDictionaryPath = String( aFullPath );    break;
                    case DEFAULTPATH__FAVORITES:        m_aFavoritesPath = String( aFullPath );     break;
                    case DEFAULTPATH__FILTER:           m_aFilterPath = String( aFullPath );        break;
                    case DEFAULTPATH__GALLERY:          m_aGalleryPath = String( aFullPath );       break;
                    case DEFAULTPATH__GRAPHIC:          m_aGraphicPath = String( aFullPath );       break;
                    case DEFAULTPATH__HELP:             m_aHelpPath = String( aFullPath );          break;
                    case DEFAULTPATH__LINGUISTIC:       m_aLinguisticPath = String( aFullPath );    break;
                    case DEFAULTPATH__MODULE:           m_aModulePath = String( aFullPath );        break;
                    case DEFAULTPATH__PALETTE:          m_aPalettePath = String( aFullPath );       break;
                    case DEFAULTPATH__PLUGIN:           m_aPluginPath = String( aFullPath );        break;
                    case DEFAULTPATH__TEMP:             m_aTempPath = String( aFullPath );          break;
                    case DEFAULTPATH__TEMPLATE:         m_aTemplatePath = String( aFullPath );      break;
                    case DEFAULTPATH__USERCONFIG:       m_aUserConfigPath = String( aFullPath );    break;
                    case DEFAULTPATH__USERDICTIONARY:   m_aUserDictionaryPath = String( aFullPath );break;
                    case DEFAULTPATH__WORK:             m_aWorkPath = String( aFullPath );          break;

                    default:
                        DBG_ERRORFILE( "invalid index to load a default path" );
                }
            }
        }
    }
}

// class SvtDefaultOptions -----------------------------------------------
namespace { struct lclMutex : public rtl::Static< ::osl::Mutex, lclMutex > {}; }

SvtDefaultOptions::SvtDefaultOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( lclMutex::get() );
    if ( !pOptions )
    {
        pOptions = new SvtDefaultOptions_Impl;
        ItemHolder1::holdConfigItem(E_DEFAULTOPTIONS);
    }
    ++nRefCount;
    pImp = pOptions;
}

// -----------------------------------------------------------------------

SvtDefaultOptions::~SvtDefaultOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( lclMutex::get() );
    if ( !--nRefCount )
    {
        if ( pOptions->IsModified() )
            pOptions->Commit();
        DELETEZ( pOptions );
    }
}

// -----------------------------------------------------------------------

String SvtDefaultOptions::GetDefaultPath( USHORT nId ) const
{
    return pImp->GetDefaultPath( nId );
}

<commit_msg>INTEGRATION: CWS fwk88 (1.14.32); FILE MERGED 2008/05/22 07:53:46 pb 1.14.32.1: fix: #i88176# swap work- and userdictionarypath<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: defaultoptions.cxx,v $
 * $Revision: 1.15 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#include <svtools/defaultoptions.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configitem.hxx>
#include <unotools/configmgr.hxx>
#include <tools/debug.hxx>
#include <tools/resmgr.hxx>
#include <tools/urlobj.hxx>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <osl/mutex.hxx>

#include <vos/process.hxx>
#include <unotools/localfilehelper.hxx>
#include <rtl/instance.hxx>

#include <itemholder1.hxx>

using namespace osl;
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

// define ----------------------------------------------------------------

#define ASCII_STR(s)                OUString( RTL_CONSTASCII_USTRINGPARAM(s) )

#define DEFAULTPATH__ADDIN          0
#define DEFAULTPATH__AUTOCORRECT    1
#define DEFAULTPATH__AUTOTEXT       2
#define DEFAULTPATH__BACKUP         3
#define DEFAULTPATH__BASIC          4
#define DEFAULTPATH__BITMAP         5
#define DEFAULTPATH__CONFIG         6
#define DEFAULTPATH__DICTIONARY     7
#define DEFAULTPATH__FAVORITES      8
#define DEFAULTPATH__FILTER         9
#define DEFAULTPATH__GALLERY        10
#define DEFAULTPATH__GRAPHIC        11
#define DEFAULTPATH__HELP           12
#define DEFAULTPATH__LINGUISTIC     13
#define DEFAULTPATH__MODULE         14
#define DEFAULTPATH__PALETTE        15
#define DEFAULTPATH__PLUGIN         16
#define DEFAULTPATH__TEMP           17
#define DEFAULTPATH__TEMPLATE       18
#define DEFAULTPATH__USERCONFIG     19
#define DEFAULTPATH__WORK           20
#define DEFAULTPATH__USERDICTIONARY 21

// class SvtDefaultOptions_Impl ------------------------------------------

class SvtDefaultOptions_Impl : public utl::ConfigItem
{
public:
    String          m_aAddinPath;
    String          m_aAutoCorrectPath;
    String          m_aAutoTextPath;
    String          m_aBackupPath;
    String          m_aBasicPath;
    String          m_aBitmapPath;
    String          m_aConfigPath;
    String          m_aDictionaryPath;
    String          m_aFavoritesPath;
    String          m_aFilterPath;
    String          m_aGalleryPath;
    String          m_aGraphicPath;
    String          m_aHelpPath;
    String          m_aLinguisticPath;
    String          m_aModulePath;
    String          m_aPalettePath;
    String          m_aPluginPath;
    String          m_aTempPath;
    String          m_aTemplatePath;
    String          m_aUserConfigPath;
    String          m_aWorkPath;
    String          m_aUserDictionaryPath;

                    SvtDefaultOptions_Impl();

    String          GetDefaultPath( USHORT nId ) const;
};

// global ----------------------------------------------------------------

static SvtDefaultOptions_Impl*  pOptions = NULL;
static sal_Int32                nRefCount = 0;

typedef String SvtDefaultOptions_Impl:: *PathStrPtr;

struct PathToDefaultMapping_Impl
{
    SvtPathOptions::Pathes  _ePath;
    PathStrPtr              _pDefaultPath;
};

static PathToDefaultMapping_Impl __READONLY_DATA PathMap_Impl[] =
{
    { SvtPathOptions::PATH_ADDIN,           &SvtDefaultOptions_Impl::m_aAddinPath },
    { SvtPathOptions::PATH_AUTOCORRECT,     &SvtDefaultOptions_Impl::m_aAutoCorrectPath },
    { SvtPathOptions::PATH_AUTOTEXT,        &SvtDefaultOptions_Impl::m_aAutoTextPath },
    { SvtPathOptions::PATH_BACKUP,          &SvtDefaultOptions_Impl::m_aBackupPath },
    { SvtPathOptions::PATH_BASIC,           &SvtDefaultOptions_Impl::m_aBasicPath },
    { SvtPathOptions::PATH_BITMAP,          &SvtDefaultOptions_Impl::m_aBitmapPath },
    { SvtPathOptions::PATH_CONFIG,          &SvtDefaultOptions_Impl::m_aConfigPath },
    { SvtPathOptions::PATH_DICTIONARY,      &SvtDefaultOptions_Impl::m_aDictionaryPath },
    { SvtPathOptions::PATH_FAVORITES,       &SvtDefaultOptions_Impl::m_aFavoritesPath },
    { SvtPathOptions::PATH_FILTER,          &SvtDefaultOptions_Impl::m_aFilterPath },
    { SvtPathOptions::PATH_GALLERY,         &SvtDefaultOptions_Impl::m_aGalleryPath },
    { SvtPathOptions::PATH_GRAPHIC,         &SvtDefaultOptions_Impl::m_aGraphicPath },
    { SvtPathOptions::PATH_HELP,            &SvtDefaultOptions_Impl::m_aHelpPath },
    { SvtPathOptions::PATH_LINGUISTIC,      &SvtDefaultOptions_Impl::m_aLinguisticPath },
    { SvtPathOptions::PATH_MODULE,          &SvtDefaultOptions_Impl::m_aModulePath },
    { SvtPathOptions::PATH_PALETTE,         &SvtDefaultOptions_Impl::m_aPalettePath },
    { SvtPathOptions::PATH_PLUGIN,          &SvtDefaultOptions_Impl::m_aPluginPath },
    { SvtPathOptions::PATH_TEMP,            &SvtDefaultOptions_Impl::m_aTempPath },
    { SvtPathOptions::PATH_TEMPLATE,        &SvtDefaultOptions_Impl::m_aTemplatePath },
    { SvtPathOptions::PATH_USERCONFIG,      &SvtDefaultOptions_Impl::m_aUserConfigPath },
    { SvtPathOptions::PATH_WORK,            &SvtDefaultOptions_Impl::m_aWorkPath }
};

// functions -------------------------------------------------------------

Sequence< OUString > GetDefaultPropertyNames()
{
    static const char* aPropNames[] =
    {
        "Addin",            // PATH_ADDIN
        "AutoCorrect",      // PATH_AUTOCORRECT
        "AutoText",         // PATH_AUTOTEXT
        "Backup",           // PATH_BACKUP
        "Basic",            // PATH_BASIC
        "Bitmap",           // PATH_BITMAP
        "Config",           // PATH_CONFIG
        "Dictionary",       // PATH_DICTIONARY
        "Favorite",         // PATH_FAVORITES
        "Filter",           // PATH_FILTER
        "Gallery",          // PATH_GALLERY
        "Graphic",          // PATH_GRAPHIC
        "Help",             // PATH_HELP
        "Linguistic",       // PATH_LINGUISTIC
        "Module",           // PATH_MODULE
        "Palette",          // PATH_PALETTE
        "Plugin",           // PATH_PLUGIN
        "Temp",             // PATH_TEMP
        "Template",         // PATH_TEMPLATE
        "UserConfig",       // PATH_USERCONFIG
        "Work"              // PATH_WORK
    };

    const int nCount = sizeof( aPropNames ) / sizeof( const char* );
    Sequence< OUString > aNames( nCount );
    OUString* pNames = aNames.getArray();
    for ( int i = 0; i < nCount; i++ )
        pNames[i] = OUString::createFromAscii( aPropNames[i] );

    return aNames;
}

// class SvtDefaultOptions_Impl ------------------------------------------

String SvtDefaultOptions_Impl::GetDefaultPath( USHORT nId ) const
{
    String aRet;
    USHORT nIdx = 0;

    while ( PathMap_Impl[nIdx]._ePath <= SvtPathOptions::PATH_WORK )
    {
        if ( nId == PathMap_Impl[nIdx]._ePath && PathMap_Impl[nIdx]._pDefaultPath )
        {
            aRet = this->*(PathMap_Impl[nIdx]._pDefaultPath);
            if ( nId == SvtPathOptions::PATH_ADDIN ||
                 nId == SvtPathOptions::PATH_FILTER ||
                 nId == SvtPathOptions::PATH_HELP ||
                 nId == SvtPathOptions::PATH_MODULE ||
                 nId == SvtPathOptions::PATH_PLUGIN )
            {
                String aTmp;
                ::utl::LocalFileHelper::ConvertPhysicalNameToURL( aRet, aTmp );
                aRet = aTmp;
            }

            break;
        }
        ++nIdx;
    }

    return aRet;
}

// -----------------------------------------------------------------------

SvtDefaultOptions_Impl::SvtDefaultOptions_Impl() : ConfigItem( ASCII_STR("Office.Common/Path/Default") )
{
    /*ConfigManager* pCfgMgr =*/ ConfigManager::GetConfigManager();
    Sequence< OUString > aNames = GetDefaultPropertyNames();
    Sequence< Any > aValues = GetProperties( aNames );
    EnableNotification( aNames );
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT( aValues.getLength() == aNames.getLength(), "GetProperties failed" );
    if ( aValues.getLength() == aNames.getLength() )
    {
        SvtPathOptions aPathOpt;
        OUString aTempStr, aFullPath;

        for ( int nProp = 0; nProp < aNames.getLength(); nProp++ )
        {
            if ( pValues[nProp].hasValue() )
            {
                switch ( pValues[nProp].getValueTypeClass() )
                {
                    case ::com::sun::star::uno::TypeClass_STRING :
                    {
                        // multi pathes
                        if ( pValues[nProp] >>= aTempStr )
                            aFullPath = aPathOpt.SubstituteVariable( aTempStr );
                        else
                        {
                            DBG_ERRORFILE( "any operator >>= failed" );
                        }
                        break;
                    }

                    case ::com::sun::star::uno::TypeClass_SEQUENCE :
                    {
                        // single pathes
                        aFullPath = OUString();
                        Sequence < OUString > aList;
                        if ( pValues[nProp] >>= aList )
                        {
                            sal_Int32 nCount = aList.getLength();
                            for ( sal_Int32 nPosition = 0; nPosition < nCount; ++nPosition )
                            {
                                aTempStr = aPathOpt.SubstituteVariable( aList[ nPosition ] );
                                aFullPath += aTempStr;
                                if ( nPosition < nCount-1 )
                                    aFullPath += OUString( RTL_CONSTASCII_USTRINGPARAM(";") );
                            }
                        }
                        else
                        {
                            DBG_ERRORFILE( "any operator >>= failed" );
                        }
                        break;
                    }

                    default:
                    {
                        DBG_ERRORFILE( "Wrong any type" );
                    }
                }

                switch ( nProp )
                {
                    case DEFAULTPATH__ADDIN:            m_aAddinPath = String( aFullPath );         break;
                    case DEFAULTPATH__AUTOCORRECT:      m_aAutoCorrectPath = String( aFullPath );   break;
                    case DEFAULTPATH__AUTOTEXT:         m_aAutoTextPath = String( aFullPath );      break;
                    case DEFAULTPATH__BACKUP:           m_aBackupPath = String( aFullPath );        break;
                    case DEFAULTPATH__BASIC:            m_aBasicPath = String( aFullPath );         break;
                    case DEFAULTPATH__BITMAP:           m_aBitmapPath = String( aFullPath );        break;
                    case DEFAULTPATH__CONFIG:           m_aConfigPath = String( aFullPath );        break;
                    case DEFAULTPATH__DICTIONARY:       m_aDictionaryPath = String( aFullPath );    break;
                    case DEFAULTPATH__FAVORITES:        m_aFavoritesPath = String( aFullPath );     break;
                    case DEFAULTPATH__FILTER:           m_aFilterPath = String( aFullPath );        break;
                    case DEFAULTPATH__GALLERY:          m_aGalleryPath = String( aFullPath );       break;
                    case DEFAULTPATH__GRAPHIC:          m_aGraphicPath = String( aFullPath );       break;
                    case DEFAULTPATH__HELP:             m_aHelpPath = String( aFullPath );          break;
                    case DEFAULTPATH__LINGUISTIC:       m_aLinguisticPath = String( aFullPath );    break;
                    case DEFAULTPATH__MODULE:           m_aModulePath = String( aFullPath );        break;
                    case DEFAULTPATH__PALETTE:          m_aPalettePath = String( aFullPath );       break;
                    case DEFAULTPATH__PLUGIN:           m_aPluginPath = String( aFullPath );        break;
                    case DEFAULTPATH__TEMP:             m_aTempPath = String( aFullPath );          break;
                    case DEFAULTPATH__TEMPLATE:         m_aTemplatePath = String( aFullPath );      break;
                    case DEFAULTPATH__USERCONFIG:       m_aUserConfigPath = String( aFullPath );    break;
                    case DEFAULTPATH__WORK:             m_aWorkPath = String( aFullPath );          break;
                    case DEFAULTPATH__USERDICTIONARY:   m_aUserDictionaryPath = String( aFullPath );break;

                    default:
                        DBG_ERRORFILE( "invalid index to load a default path" );
                }
            }
        }
    }
}

// class SvtDefaultOptions -----------------------------------------------
namespace { struct lclMutex : public rtl::Static< ::osl::Mutex, lclMutex > {}; }

SvtDefaultOptions::SvtDefaultOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( lclMutex::get() );
    if ( !pOptions )
    {
        pOptions = new SvtDefaultOptions_Impl;
        ItemHolder1::holdConfigItem(E_DEFAULTOPTIONS);
    }
    ++nRefCount;
    pImp = pOptions;
}

// -----------------------------------------------------------------------

SvtDefaultOptions::~SvtDefaultOptions()
{
    // Global access, must be guarded (multithreading)
    ::osl::MutexGuard aGuard( lclMutex::get() );
    if ( !--nRefCount )
    {
        if ( pOptions->IsModified() )
            pOptions->Commit();
        DELETEZ( pOptions );
    }
}

// -----------------------------------------------------------------------

String SvtDefaultOptions::GetDefaultPath( USHORT nId ) const
{
    return pImp->GetDefaultPath( nId );
}

<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include "fake-inc.h"
#include <string.h>
#include <vector>
#include <algorithm>
#ifdef WIN32
#else
#ifdef USE_GOOGLE_POFILER
#include "gperftools/profiler.h"
#endif
#endif

// for test
int test_cfunc1(int a, int b)
{
	return a - b;
}

// for test
class test_class1
{
public:
	test_class1()
	{
		b = 10;
	}
	int test_memfunc1(int a)
	{
		return a - b;
	}
private:
	int b;
};
class test_class2
{
public:
	test_class2()
	{
		b = 10;
	}
	int test_memfunc1(int a)
	{
		return a + b;
	}
	int test_memfunc2(int a)
	{
		return a * b;
	}
	test_class2 * self()
	{
		return this;
	}
private:
	int b;
};

// for test
test_class1 * new_test_class1()
{
	return new test_class1();
}
void delete_test_class1(test_class1 * p)
{
	delete p;
}
test_class2 * new_test_class2()
{
	return new test_class2();
}
void delete_test_class2(test_class2 * p)
{
	delete p;
}

void error_log(fake * fk, int eno, const char * file, int lineno, const char * func, const char * str)
{
	printf("fake error[%d] in file(%s:%d) func(%s) : ", eno, file, lineno, func);
	printf("%s\n", str);
	printf("call stack :\n%s\n", fkgetcurcallstack(fk));
	printf("cur routine :\n%s\n", fkgetcurroutine(fk));
}

static const char * g_replacebuff = "start compile";

//
bool readfile(const char * filename, int addsize, char * & buf, int & filesize);
bool writefile(const char * filename, const char * buf, int filesize);
int parsearg(fake * fk, int & argc, const char ** & argv);

// ѡ
bool g_isopenprofile = false;
bool g_isopenjit = false;
bool g_isopengoogleprofile = false;
int g_testnum = 1;
bool g_issave = false;
bool g_isload = false;
bool g_isprintoutput = false;
bool g_iscompile = false;
bool g_iscompiled = false;
bool g_isstep = false;
const char * g_selfname = 0;

int main(int argc, const char *argv[])
{
	fake * fk = newfake();

	//
	int parseret = parsearg(fk, argc, argv);
	if (parseret != 0)
	{
		return parseret;
	}

	if (g_iscompiled)
	{
		fksetargv(fk, argc - 1, argv + 1);
	}
	else
	{
		fksetargv(fk, argc - 2, argv + 2);
	}
	fkopenalllib(fk);
	fkseterrorfunc(fk, error_log);

	// for test
	fkreg(fk, "test_cfunc1", test_cfunc1);
	fkreg(fk, "new_test_class1", new_test_class1);
	fkreg(fk, "new_test_class2", new_test_class2);
	fkreg(fk, "delete_test_class1", delete_test_class1);
	fkreg(fk, "delete_test_class2", delete_test_class2);
	fkreg(fk, "test_memfunc1", &test_class1::test_memfunc1);
	fkreg(fk, "test_memfunc1", &test_class2::test_memfunc1);
	fkreg(fk, "test_memfunc2", &test_class2::test_memfunc2);
	fkreg(fk, "self", &test_class2::self);

	// ļ
	if (g_iscompiled)
	{
		// Լ
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, 0, selftmpbuf, selfsize))
		{
			return -1;
		}

		int startpos = 0;
		int size = 0;
		memcpy(&startpos, g_replacebuff, sizeof(startpos));
		memcpy(&size, g_replacebuff + 4, sizeof(size));

		if (fkloadfunc(fk, selftmpbuf + startpos, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(selftmpbuf);
	}
	// ļ
	else if (!g_isload)
	{
		fkparse(fk, argv[1]);
		if (fkerror(fk))
		{
			return -1;
		}
	}
	// ļ
	else
	{
		// ļ
		char * tmpbuf = 0;
		int size = 0;
		if (!readfile(argv[1], 0, tmpbuf, size))
		{
			return -1;
		}

		if (fkloadfunc(fk, tmpbuf, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(tmpbuf);
		printf("load from %s ok, size %d\n", argv[1], size);
	}

	// ļ
	if (g_issave)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("save func fail\n");
			return -1;
		}

		const char * filename = "fake.bin";
		if (!writefile(filename, tmpbuf, size))
		{
			return -1;
		}
		free(tmpbuf);

		printf("save to %s ok, size %d\n", filename, size);

		return 0;
	}

	// 뵽һ
	if (g_iscompile)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("compile func fail\n");
			return -1;
		}

		// Լ
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, size, selftmpbuf, selfsize))
		{
			return -1;
		}

		// 滻ڴеַ
		bool isfind = false;
		for (int i = 0; i < selfsize; i++)
		{
			if (memcmp(selftmpbuf + i, g_replacebuff, strlen(g_replacebuff)) == 0)
			{
				memcpy(selftmpbuf + i, &selfsize, sizeof(selfsize));
				memcpy(selftmpbuf + i + 4, &size, sizeof(size));
				isfind = true;
				break;
			}
		}
		if (!isfind)
		{
			printf("replace %s pos fail\n", argv[0]);
			return -1;
		}

		// ƺ
		memcpy(selftmpbuf + selfsize, tmpbuf, size);
		free(tmpbuf);

		//
		const char * filename = "out.exe";
		if (!writefile(filename, selftmpbuf, selfsize + size))
		{
			return -1;
		}
		free(selftmpbuf);

		printf("compile to %s ok, size %d\n", filename, selfsize + size);

		return 0;
	}

#ifndef WIN32
#ifdef USE_GOOGLE_POFILER
	if (g_isopengoogleprofile)
	{
		ProfilerStart("fake.prof");
	}
#endif
#endif

	uint32_t begintime = time(0);
	int fkret = 0;

	// run
	for (int i = 0; i < g_testnum; i++)
	{
		if (!g_isopenjit)
		{
			if (g_isstep)
			{
				fkret = fkdebugrun<int>(fk, "main");
			}
			else
			{
				fkret = fkrun<int>(fk, "main");
			}
		}
		else
		{
			fkret = fkrunjit<int>(fk, "main");
		}
	}

	uint32_t endtime = time(0);

#ifndef WIN32
#ifdef USE_GOOGLE_POFILER
	if (g_isopengoogleprofile)
	{
		ProfilerStop();
	}
#endif
#endif

	if (fkerror(fk))
	{
		return -1;
	}

	if (g_isopenprofile)
	{
		printf("\n%s", fkdumpprofile(fk));
	}

	if (g_isprintoutput)
	{
		printf("main return : %d, use time %d\n", fkret, endtime - begintime);
	}

	delfake(fk);

	return 0;
}

bool readfile(const char * filename, int addsize, char * & buf, int & filesize)
{
	//
	FILE * fp = fopen(filename, "rb");
	if (!fp)
	{
		printf("open %s for read fail\n", filename);
		return false;
	}

	fseek(fp, 0, SEEK_END);
	int size = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	char * tmpbuf = (char *)malloc(size + addsize);
	if (fread(tmpbuf, size, 1, fp) != 1)
	{
		printf("read %s fail\n", filename);
		free(tmpbuf);
		return false;
	}
	fclose(fp);

	buf = tmpbuf;
	filesize = size;

	return true;
}

bool writefile(const char * filename, const char * buf, int filesize)
{
	FILE * fp = fopen(filename, "wb");
	if (!fp)
	{
		printf("open %s for write fail\n", filename);
		return false;
	}

	if (fwrite(buf, filesize, 1, fp) != 1)
	{
		printf("write %s fail\n", filename);
		return -1;
	}

	fclose(fp);

	return true;
}

int parsearg(fake * fk, int & argc, const char ** & argv)
{
	g_selfname = argv[0];

	// start compilememcmp޽ֻ
	if (g_replacebuff[0] != 's' ||
		g_replacebuff[1] != 't' ||
		g_replacebuff[2] != 'a' ||
		g_replacebuff[3] != 'r' ||
		g_replacebuff[4] != 't' ||
		g_replacebuff[5] != ' ' ||
		g_replacebuff[6] != 'c' ||
		g_replacebuff[7] != 'o' ||
		g_replacebuff[8] != 'm' ||
		g_replacebuff[9] != 'p' ||
		g_replacebuff[10] != 'i' ||
		g_replacebuff[11] != 'l' ||
		g_replacebuff[12] != 'e')
	{
		g_iscompiled = true;
	}
	else if (argc < 2)
	{
		printf("try -h for help\n");
		return -1;
	}

	if (argc >= 2 && argv[1][0] == '-')
	{
		if (strstr(argv[1], "h"))
		{
			printf("\
fakescript\n\narg : [-hjpgtsl] file [arg]\n\
-h help\n\
-j open jit\n\
-p open profile\n\
-g open google profile\n\
-t open test mode\n\
-s save func to fake.bin\n\
-l load func from file\n\
-o print return value and time\n\
-c compile script to out.exe\n\
-d debug step mod\n\
-y open optimize\n\
sample:./fake a.fk\n\n");
			return -1;
		}

		if (strstr(argv[1], "j"))
		{
			fkopenjit(fk);
			g_isopenjit = true;
		}

		if (strstr(argv[1], "p"))
		{
			fkopenprofile(fk);
			g_isopenprofile = true;
		}

		if (strstr(argv[1], "y"))
		{
			fkopenoptimize(fk);
		}

#ifndef WIN32
		if (strstr(argv[1], "g"))
		{
			g_isopengoogleprofile = true;
		}
#endif

		if (strstr(argv[1], "t"))
		{
			g_testnum = 9000000;
		}

		if (strstr(argv[1], "s"))
		{
			g_issave = true;
		}

		if (strstr(argv[1], "l"))
		{
			g_isload = true;
		}

		if (strstr(argv[1], "o"))
		{
			g_isprintoutput = true;
		}

		if (strstr(argv[1], "c"))
		{
			printf("%s\n", g_replacebuff);
			g_iscompile = true;
		}

		if (strstr(argv[1], "d"))
		{
			g_isstep = true;
		}

		argc--;
		argv++;
	}

	return 0;
}

<commit_msg>delete<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include "fake-inc.h"
#include <string.h>
#include <vector>
#include <algorithm>
#ifdef WIN32
#else
#ifdef USE_GOOGLE_POFILER
#include "gperftools/profiler.h"
#endif
#endif

// for test
int test_cfunc1(int a, int b)
{
	return a - b;
}

// for test
class test_class1
{
public:
	test_class1()
	{
		b = 10;
	}
	int test_memfunc1(int a)
	{
		return a - b;
	}
private:
	int b;
};
class test_class2
{
public:
	test_class2()
	{
		b = 10;
	}
	int test_memfunc1(int a)
	{
		return a + b;
	}
	int test_memfunc2(int a)
	{
		return a * b;
	}
	test_class2 * self()
	{
		return this;
	}
private:
	int b;
};

// for test
test_class1 * new_test_class1()
{
	return new test_class1();
}
void delete_test_class1(test_class1 * p)
{
	delete p;
}
test_class2 * new_test_class2()
{
	return new test_class2();
}
void delete_test_class2(test_class2 * p)
{
	delete p;
}

void error_log(fake * fk, int eno, const char * file, int lineno, const char * func, const char * str)
{
	printf("fake error[%d] in file(%s:%d) func(%s) : ", eno, file, lineno, func);
	printf("%s\n", str);
	printf("call stack :\n%s\n", fkgetcurcallstack(fk));
	printf("cur routine :\n%s\n", fkgetcurroutine(fk));
}

static const char * g_replacebuff = "start compile";

//
bool readfile(const char * filename, int addsize, char * & buf, int & filesize);
bool writefile(const char * filename, const char * buf, int filesize);
int parsearg(fake * fk, int & argc, const char ** & argv);

// ѡ
bool g_isopenprofile = false;
bool g_isopenjit = false;
bool g_isopengoogleprofile = false;
int g_testnum = 1;
bool g_issave = false;
bool g_isload = false;
bool g_isprintoutput = false;
bool g_iscompile = false;
bool g_iscompiled = false;
bool g_isstep = false;
const char * g_selfname = 0;

int main(int argc, const char *argv[])
{
	fake * fk = newfake();

	//
	int parseret = parsearg(fk, argc, argv);
	if (parseret != 0)
	{
		return parseret;
	}

	if (g_iscompiled)
	{
		fksetargv(fk, argc - 1, argv + 1);
	}
	else
	{
		fksetargv(fk, argc - 2, argv + 2);
	}
	fkopenalllib(fk);
	fkseterrorfunc(fk, error_log);

	// for test
	fkreg(fk, "test_cfunc1", test_cfunc1);
	fkreg(fk, "new_test_class1", new_test_class1);
	fkreg(fk, "new_test_class2", new_test_class2);
	fkreg(fk, "delete_test_class1", delete_test_class1);
	fkreg(fk, "delete_test_class2", delete_test_class2);
	fkreg(fk, "test_memfunc1", &test_class1::test_memfunc1);
	fkreg(fk, "test_memfunc1", &test_class2::test_memfunc1);
	fkreg(fk, "test_memfunc2", &test_class2::test_memfunc2);
	fkreg(fk, "self", &test_class2::self);

	// ļ
	if (g_iscompiled)
	{
		// Լ
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, 0, selftmpbuf, selfsize))
		{
			return -1;
		}

		int startpos = 0;
		int size = 0;
		memcpy(&startpos, g_replacebuff, sizeof(startpos));
		memcpy(&size, g_replacebuff + 4, sizeof(size));

		if (fkloadfunc(fk, selftmpbuf + startpos, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(selftmpbuf);
	}
	// ļ
	else if (!g_isload)
	{
		fkparse(fk, argv[1]);
		if (fkerror(fk))
		{
			return -1;
		}
	}
	// ļ
	else
	{
		// ļ
		char * tmpbuf = 0;
		int size = 0;
		if (!readfile(argv[1], 0, tmpbuf, size))
		{
			return -1;
		}

		if (fkloadfunc(fk, tmpbuf, size) == -1)
		{
			printf("load func fail\n");
			return -1;
		}

		free(tmpbuf);
		printf("load from %s ok, size %d\n", argv[1], size);
	}

	// ļ
	if (g_issave)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("save func fail\n");
			return -1;
		}

		const char * filename = "fake.bin";
		if (!writefile(filename, tmpbuf, size))
		{
			return -1;
		}
		free(tmpbuf);

		printf("save to %s ok, size %d\n", filename, size);

		return 0;
	}

	// 뵽һ
	if (g_iscompile)
	{
		int tmpsize = 1024 * 1024;
		char * tmpbuf = (char *)malloc(tmpsize);
		int size = fksavefunc(fk, tmpbuf, tmpsize);
		if (size == -1)
		{
			printf("compile func fail\n");
			return -1;
		}

		// Լ
		char * selftmpbuf = 0;
		int selfsize = 0;
		if (!readfile(g_selfname, size, selftmpbuf, selfsize))
		{
			return -1;
		}

		// 滻ڴеַ
		bool isfind = false;
		for (int i = 0; i < selfsize; i++)
		{
			if (memcmp(selftmpbuf + i, g_replacebuff, strlen(g_replacebuff)) == 0)
			{
				memcpy(selftmpbuf + i, &selfsize, sizeof(selfsize));
				memcpy(selftmpbuf + i + 4, &size, sizeof(size));
				isfind = true;
				break;
			}
		}
		if (!isfind)
		{
			printf("replace %s pos fail\n", argv[0]);
			return -1;
		}

		// ƺ
		memcpy(selftmpbuf + selfsize, tmpbuf, size);
		free(tmpbuf);

		//
		const char * filename = "out.exe";
		if (!writefile(filename, selftmpbuf, selfsize + size))
		{
			return -1;
		}
		free(selftmpbuf);

		printf("compile to %s ok, size %d\n", filename, selfsize + size);

		return 0;
	}

#ifndef WIN32
#ifdef USE_GOOGLE_POFILER
	if (g_isopengoogleprofile)
	{
		ProfilerStart("fake.prof");
	}
#endif
#endif

	uint32_t begintime = time(0);
	int fkret = 0;

	// run
	for (int i = 0; i < g_testnum; i++)
	{
		if (!g_isopenjit)
		{
			if (g_isstep)
			{
				fkret = fkdebugrun<int>(fk, "main");
			}
			else
			{
				fkret = fkrun<int>(fk, "main");
			}
		}
		else
		{
			fkret = fkrunjit<int>(fk, "main");
		}
	}

	uint32_t endtime = time(0);

#ifndef WIN32
#ifdef USE_GOOGLE_POFILER
	if (g_isopengoogleprofile)
	{
		ProfilerStop();
	}
#endif
#endif

	if (fkerror(fk))
	{
		return -1;
	}

	if (g_isopenprofile)
	{
		printf("\n%s", fkdumpprofile(fk));
	}

	if (g_isprintoutput)
	{
		printf("main return : %d, use time %d\n", fkret, endtime - begintime);
	}

	delfake(fk);

	return 0;
}

bool readfile(const char * filename, int addsize, char * & buf, int & filesize)
{
	//
	FILE * fp = fopen(filename, "rb");
	if (!fp)
	{
		printf("open %s for read fail\n", filename);
		return false;
	}

	fseek(fp, 0, SEEK_END);
	int size = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	char * tmpbuf = (char *)malloc(size + addsize);
	if (fread(tmpbuf, size, 1, fp) != 1)
	{
		printf("read %s fail\n", filename);
		free(tmpbuf);
		return false;
	}
	fclose(fp);

	buf = tmpbuf;
	filesize = size;

	return true;
}

bool writefile(const char * filename, const char * buf, int filesize)
{
	FILE * fp = fopen(filename, "wb");
	if (!fp)
	{
		printf("open %s for write fail\n", filename);
		return false;
	}

	if (fwrite(buf, filesize, 1, fp) != 1)
	{
		printf("write %s fail\n", filename);
		return -1;
	}

	fclose(fp);

	return true;
}

int parsearg(fake * fk, int & argc, const char ** & argv)
{
	g_selfname = argv[0];

	// start compilememcmp޽ֻ
	if (g_replacebuff[0] != 's' ||
		g_replacebuff[1] != 't' ||
		g_replacebuff[2] != 'a' ||
		g_replacebuff[3] != 'r' ||
		g_replacebuff[4] != 't' ||
		g_replacebuff[5] != ' ' ||
		g_replacebuff[6] != 'c' ||
		g_replacebuff[7] != 'o' ||
		g_replacebuff[8] != 'm' ||
		g_replacebuff[9] != 'p' ||
		g_replacebuff[10] != 'i' ||
		g_replacebuff[11] != 'l' ||
		g_replacebuff[12] != 'e')
	{
		g_iscompiled = true;
	}
	else if (argc < 2)
	{
		printf("try -h for help\n");
		return -1;
	}

	if (argc >= 2 && argv[1][0] == '-')
	{
		if (strstr(argv[1], "h"))
		{
			printf("\
fakescript\n\narg : [-hjpgtsl] file [arg]\n\
-h help\n\
-j open jit\n\
-p open profile\n\
-g open google profile\n\
-t open test mode\n\
-s save func to fake.bin\n\
-l load func from file\n\
-o print return value and time\n\
-c compile script to out.exe\n\
-d debug step mod\n\
sample:./fake a.fk\n\n");
			return -1;
		}

		if (strstr(argv[1], "j"))
		{
			fkopenjit(fk);
			g_isopenjit = true;
		}

		if (strstr(argv[1], "p"))
		{
			fkopenprofile(fk);
			g_isopenprofile = true;
		}

#ifndef WIN32
		if (strstr(argv[1], "g"))
		{
			g_isopengoogleprofile = true;
		}
#endif

		if (strstr(argv[1], "t"))
		{
			g_testnum = 9000000;
		}

		if (strstr(argv[1], "s"))
		{
			g_issave = true;
		}

		if (strstr(argv[1], "l"))
		{
			g_isload = true;
		}

		if (strstr(argv[1], "o"))
		{
			g_isprintoutput = true;
		}

		if (strstr(argv[1], "c"))
		{
			printf("%s\n", g_replacebuff);
			g_iscompile = true;
		}

		if (strstr(argv[1], "d"))
		{
			g_isstep = true;
		}

		argc--;
		argv++;
	}

	return 0;
}

<|endoftext|>