<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/log/log.h>
LOG_SETUP("generation_handler_stress_test");
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/generationhandler.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/size_literals.h>
#include <thread>

using vespalib::Executor;
using vespalib::GenerationHandler;
using vespalib::makeLambdaTask;
using vespalib::ThreadStackExecutor;

namespace {

bool smoke_test = false;
const vespalib::string smoke_test_option = "--smoke-test";

}

struct WorkContext
{
    std::atomic<uint64_t> _generation;

    WorkContext() noexcept
        : _generation(0)
    {
    }
};

struct IndirectContext {
    std::atomic<uint64_t *> _value_ptr;
    char _pad[256];
    static constexpr size_t values_size = 65536;
    uint64_t _values[values_size];

    IndirectContext();
    uint64_t* calc_value_ptr(uint64_t idx) { return &_values[(idx & (values_size - 1))]; }
};

IndirectContext::IndirectContext()
    : _value_ptr(nullptr),
      _pad(),
      _values()
{
    _value_ptr = &_values[0];
}

class Fixture : public ::testing::Test {
protected:
    GenerationHandler _generationHandler;
    uint32_t _readThreads;
    ThreadStackExecutor _writer; // 1 write thread
    std::unique_ptr<ThreadStackExecutor> _readers; // multiple reader threads
    std::atomic<long> _readSeed;
    std::atomic<long> _doneWriteWork;
    std::atomic<long> _doneReadWork;
    std::atomic<bool> _stopRead;
    bool _reportWork;

    Fixture();
    ~Fixture();

    void set_read_threads(uint32_t read_threads);

    uint32_t getReadThreads() const { return _readThreads; }
    void stressTest(uint32_t writeCnt);
    void stress_test_indirect(uint64_t write_cnt);
public:
    void readWork(const WorkContext &context);
    void writeWork(uint32_t cnt, WorkContext &context);
    void read_indirect_work(const IndirectContext& context);
    void write_indirect_work(uint64_t cnt, IndirectContext& context);
private:
    Fixture(const Fixture &index) = delete;
    Fixture(Fixture &&index) = delete;
    Fixture &operator=(const Fixture &index) = delete;
    Fixture &operator=(Fixture &&index) = delete;
};

Fixture::Fixture()
    : ::testing::Test(),
      _generationHandler(),
      _readThreads(1),
      _writer(1, 128_Ki),
      _readers(),
      _doneWriteWork(0),
      _doneReadWork(0),
      _stopRead(false),
      _reportWork(false)
{
    set_read_threads(1);
}

Fixture::~Fixture()
{
    if (_readers) {
        _readers->sync();
        _readers->shutdown();
    }
    _writer.sync();
    _writer.shutdown();
    if (_reportWork) {
        LOG(info,
            "readWork=%ld, writeWork=%ld",
            _doneReadWork.load(), _doneWriteWork.load());
    }
}

void
Fixture::set_read_threads(uint32_t read_threads)
{
    if (_readers) {
        _readers->sync();
        _readers->shutdown();
    }
    _readThreads = read_threads;
    _readers = std::make_unique<ThreadStackExecutor>(read_threads, 128_Ki);
}

void
Fixture::readWork(const WorkContext &context)
{
    uint32_t i;
    uint32_t cnt = std::numeric_limits<uint32_t>::max();

    for (i = 0; i < cnt && !_stopRead.load(); ++i) {
        auto guard = _generationHandler.takeGuard();
        auto generation = context._generation.load(std::memory_order_relaxed);
        EXPECT_GE(generation, guard.getGeneration());
    }
    _doneReadWork += i;
    LOG(info, "done %u read work", i);
}

void
Fixture::writeWork(uint32_t cnt, WorkContext &context)
{
    for (uint32_t i = 0; i < cnt; ++i) {
        context._generation.store(_generationHandler.getNextGeneration(), std::memory_order_relaxed);
        _generationHandler.incGeneration();
    }
    _doneWriteWork += cnt;
    _stopRead = true;
    LOG(info, "done %u write work", cnt);
}

namespace
{

class ReadWorkTask : public vespalib::Executor::Task
{
    Fixture &_f;
    std::shared_ptr<WorkContext> _context;
public:
    ReadWorkTask(Fixture &f, std::shared_ptr<WorkContext> context)
        : _f(f),
          _context(context)
    {
    }
    virtual void run() override { _f.readWork(*_context); }
};

class WriteWorkTask : public vespalib::Executor::Task
{
    Fixture &_f;
    uint32_t _cnt;
    std::shared_ptr<WorkContext> _context;
public:
    WriteWorkTask(Fixture &f, uint32_t cnt,
                  std::shared_ptr<WorkContext> context)
        : _f(f),
          _cnt(cnt),
          _context(context)
    {
    }
    virtual void run() override { _f.writeWork(_cnt, *_context); }
};

}

void
Fixture::stressTest(uint32_t writeCnt)
{
    _reportWork = true;
    uint32_t readThreads = getReadThreads();
    LOG(info,
        "starting stress test, 1 write thread, %u read threads, %u writes",
        readThreads, writeCnt);
    auto context = std::make_shared<WorkContext>();
    _writer.execute(std::make_unique<WriteWorkTask>(*this, writeCnt, context));
    for (uint32_t i = 0; i < readThreads; ++i) {
        _readers->execute(std::make_unique<ReadWorkTask>(*this, context));
    }
    _writer.sync();
    _readers->sync();
}

void
Fixture::read_indirect_work(const IndirectContext& context)
{
    uint64_t i;
    uint64_t cnt = std::numeric_limits<uint32_t>::max();
    uint64_t old_value = 0;
    for (i = 0; i < cnt && !_stopRead.load(); ++i) {
        auto guard = _generationHandler.takeGuard();
        // Data referenced by pointer is protected by guard
        auto v_ptr = context._value_ptr.load(std::memory_order_acquire);
        EXPECT_GE(*v_ptr, old_value);
        old_value = *v_ptr;
    }
    _doneReadWork += i;
    LOG(info, "done %" PRIu64 " read work", i);
}

void
Fixture::write_indirect_work(uint64_t cnt, IndirectContext& context)
{
    uint32_t sleep_cnt = 0;
    ASSERT_EQ(0, _generationHandler.getCurrentGeneration());
    auto oldest_gen = _generationHandler.getFirstUsedGeneration();
    for (uint64_t i = 0; i < cnt; ++i) {
        auto gen = _generationHandler.getCurrentGeneration();
        // Hold data for gen, write new data for next_gen
        auto next_gen = gen + 1;
        auto *v_ptr = context.calc_value_ptr(next_gen);
        ASSERT_EQ(0u, *v_ptr) << (_stopRead = true, "");
        *v_ptr = next_gen;
        context._value_ptr.store(v_ptr, std::memory_order_release);
        _generationHandler.incGeneration();
        auto first_used_gen = _generationHandler.getFirstUsedGeneration();
        while (oldest_gen < first_used_gen) {
            // Clear data that readers should no longer have access to.
            *context.calc_value_ptr(oldest_gen) = 0;
            ++oldest_gen;
        }
        while ((next_gen - first_used_gen) >= context.values_size - 2) {
            // Sleep if writer gets too much ahead of readers.
            std::this_thread::sleep_for(1ms);
            ++sleep_cnt;
            _generationHandler.updateFirstUsedGeneration();
            first_used_gen = _generationHandler.getFirstUsedGeneration();
        }
    }
    _doneWriteWork += cnt;
    _stopRead = true;
    LOG(info, "done %" PRIu64 " write work, %u sleeps", cnt, sleep_cnt);
}

void
Fixture::stress_test_indirect(uint64_t write_cnt)
{
    _reportWork = true;
    uint32_t read_threads = getReadThreads();
    LOG(info, "starting stress test indirect, 1 write thread, %u read threads, %" PRIu64 " writes", read_threads, write_cnt);
    auto context = std::make_shared<IndirectContext>();
    _writer.execute(makeLambdaTask([this, context, write_cnt]() { write_indirect_work(write_cnt, *context); }));
#if 1
    for (uint32_t i = 0; i < read_threads; ++i) {
        _readers->execute(makeLambdaTask([this, context]() { read_indirect_work(*context); }));
    }
#endif
    _writer.sync();
    _readers->sync();
}

using GenerationHandlerStressTest = Fixture;

TEST_F(GenerationHandlerStressTest, stress_test_2_readers)
{
    set_read_threads(2);
    stressTest(smoke_test ? 10000 : 1000000);
}

TEST_F(GenerationHandlerStressTest, stress_test_4_readers)
{
    set_read_threads(4);
    stressTest(smoke_test ? 10000 : 1000000);
}

TEST_F(GenerationHandlerStressTest, stress_test_indirect_2_readers)
{
    set_read_threads(2);
    stress_test_indirect(smoke_test ? 10000 : 1000000);
}

TEST_F(GenerationHandlerStressTest, stress_test_indirect_4_readers)
{
    set_read_threads(4);
    stress_test_indirect(smoke_test ? 10000 : 1000000);
}

int main(int argc, char **argv) {
    if (argc > 1 && argv[1] == smoke_test_option) {
        smoke_test = true;
        ++argv;
        --argc;
    }
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<commit_msg>Remove unneeded preprocessor directives. Make stopping of readers more robust.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/log/log.h>
LOG_SETUP("generation_handler_stress_test");
#include <vespa/vespalib/gtest/gtest.h>
#include <vespa/vespalib/util/generationhandler.h>
#include <vespa/vespalib/util/lambdatask.h>
#include <vespa/vespalib/util/threadstackexecutor.h>
#include <vespa/vespalib/util/size_literals.h>
#include <thread>

using vespalib::Executor;
using vespalib::GenerationHandler;
using vespalib::makeLambdaTask;
using vespalib::ThreadStackExecutor;

namespace {

bool smoke_test = false;
const vespalib::string smoke_test_option = "--smoke-test";

}

class ReadStopper {
    std::atomic<bool> &_stop_read;
public:
    ReadStopper(std::atomic<bool>& stop_read)
        : _stop_read(stop_read)
    {
    }
    ~ReadStopper() {
        _stop_read = true;
    }
};

struct WorkContext
{
    std::atomic<uint64_t> _generation;

    WorkContext() noexcept
        : _generation(0)
    {
    }
};

struct IndirectContext {
    std::atomic<uint64_t *> _value_ptr;
    char _pad[256];
    static constexpr size_t values_size = 65536;
    uint64_t _values[values_size];

    IndirectContext();
    uint64_t* calc_value_ptr(uint64_t idx) { return &_values[(idx & (values_size - 1))]; }
};

IndirectContext::IndirectContext()
    : _value_ptr(nullptr),
      _pad(),
      _values()
{
    _value_ptr = &_values[0];
}

class Fixture : public ::testing::Test {
protected:
    GenerationHandler _generationHandler;
    uint32_t _readThreads;
    ThreadStackExecutor _writer; // 1 write thread
    std::unique_ptr<ThreadStackExecutor> _readers; // multiple reader threads
    std::atomic<long> _readSeed;
    std::atomic<long> _doneWriteWork;
    std::atomic<long> _doneReadWork;
    std::atomic<bool> _stopRead;
    bool _reportWork;

    Fixture();
    ~Fixture();

    void set_read_threads(uint32_t read_threads);

    uint32_t getReadThreads() const { return _readThreads; }
    void stressTest(uint32_t writeCnt);
    void stress_test_indirect(uint64_t write_cnt);
public:
    void readWork(const WorkContext &context);
    void writeWork(uint32_t cnt, WorkContext &context);
    void read_indirect_work(const IndirectContext& context);
    void write_indirect_work(uint64_t cnt, IndirectContext& context);
private:
    Fixture(const Fixture &index) = delete;
    Fixture(Fixture &&index) = delete;
    Fixture &operator=(const Fixture &index) = delete;
    Fixture &operator=(Fixture &&index) = delete;
};

Fixture::Fixture()
    : ::testing::Test(),
      _generationHandler(),
      _readThreads(1),
      _writer(1, 128_Ki),
      _readers(),
      _doneWriteWork(0),
      _doneReadWork(0),
      _stopRead(false),
      _reportWork(false)
{
    set_read_threads(1);
}

Fixture::~Fixture()
{
    if (_readers) {
        _readers->sync();
        _readers->shutdown();
    }
    _writer.sync();
    _writer.shutdown();
    if (_reportWork) {
        LOG(info,
            "readWork=%ld, writeWork=%ld",
            _doneReadWork.load(), _doneWriteWork.load());
    }
}

void
Fixture::set_read_threads(uint32_t read_threads)
{
    if (_readers) {
        _readers->sync();
        _readers->shutdown();
    }
    _readThreads = read_threads;
    _readers = std::make_unique<ThreadStackExecutor>(read_threads, 128_Ki);
}

void
Fixture::readWork(const WorkContext &context)
{
    uint32_t i;
    uint32_t cnt = std::numeric_limits<uint32_t>::max();

    for (i = 0; i < cnt && !_stopRead.load(); ++i) {
        auto guard = _generationHandler.takeGuard();
        auto generation = context._generation.load(std::memory_order_relaxed);
        EXPECT_GE(generation, guard.getGeneration());
    }
    _doneReadWork += i;
    LOG(info, "done %u read work", i);
}

void
Fixture::writeWork(uint32_t cnt, WorkContext &context)
{
    ReadStopper read_stopper(_stopRead);
    for (uint32_t i = 0; i < cnt; ++i) {
        context._generation.store(_generationHandler.getNextGeneration(), std::memory_order_relaxed);
        _generationHandler.incGeneration();
    }
    _doneWriteWork += cnt;
    LOG(info, "done %u write work", cnt);
}

namespace
{

class ReadWorkTask : public vespalib::Executor::Task
{
    Fixture &_f;
    std::shared_ptr<WorkContext> _context;
public:
    ReadWorkTask(Fixture &f, std::shared_ptr<WorkContext> context)
        : _f(f),
          _context(context)
    {
    }
    virtual void run() override { _f.readWork(*_context); }
};

class WriteWorkTask : public vespalib::Executor::Task
{
    Fixture &_f;
    uint32_t _cnt;
    std::shared_ptr<WorkContext> _context;
public:
    WriteWorkTask(Fixture &f, uint32_t cnt,
                  std::shared_ptr<WorkContext> context)
        : _f(f),
          _cnt(cnt),
          _context(context)
    {
    }
    virtual void run() override { _f.writeWork(_cnt, *_context); }
};

}

void
Fixture::stressTest(uint32_t writeCnt)
{
    _reportWork = true;
    uint32_t readThreads = getReadThreads();
    LOG(info,
        "starting stress test, 1 write thread, %u read threads, %u writes",
        readThreads, writeCnt);
    auto context = std::make_shared<WorkContext>();
    _writer.execute(std::make_unique<WriteWorkTask>(*this, writeCnt, context));
    for (uint32_t i = 0; i < readThreads; ++i) {
        _readers->execute(std::make_unique<ReadWorkTask>(*this, context));
    }
    _writer.sync();
    _readers->sync();
}

void
Fixture::read_indirect_work(const IndirectContext& context)
{
    uint64_t i;
    uint64_t cnt = std::numeric_limits<uint32_t>::max();
    uint64_t old_value = 0;
    for (i = 0; i < cnt && !_stopRead.load(); ++i) {
        auto guard = _generationHandler.takeGuard();
        // Data referenced by pointer is protected by guard
        auto v_ptr = context._value_ptr.load(std::memory_order_acquire);
        EXPECT_GE(*v_ptr, old_value);
        old_value = *v_ptr;
    }
    _doneReadWork += i;
    LOG(info, "done %" PRIu64 " read work", i);
}

void
Fixture::write_indirect_work(uint64_t cnt, IndirectContext& context)
{
    ReadStopper read_stopper(_stopRead);
    uint32_t sleep_cnt = 0;
    ASSERT_EQ(0, _generationHandler.getCurrentGeneration());
    auto oldest_gen = _generationHandler.getFirstUsedGeneration();
    for (uint64_t i = 0; i < cnt; ++i) {
        auto gen = _generationHandler.getCurrentGeneration();
        // Hold data for gen, write new data for next_gen
        auto next_gen = gen + 1;
        auto *v_ptr = context.calc_value_ptr(next_gen);
        ASSERT_EQ(0u, *v_ptr);
        *v_ptr = next_gen;
        context._value_ptr.store(v_ptr, std::memory_order_release);
        _generationHandler.incGeneration();
        auto first_used_gen = _generationHandler.getFirstUsedGeneration();
        while (oldest_gen < first_used_gen) {
            // Clear data that readers should no longer have access to.
            *context.calc_value_ptr(oldest_gen) = 0;
            ++oldest_gen;
        }
        while ((next_gen - first_used_gen) >= context.values_size - 2) {
            // Sleep if writer gets too much ahead of readers.
            std::this_thread::sleep_for(1ms);
            ++sleep_cnt;
            _generationHandler.updateFirstUsedGeneration();
            first_used_gen = _generationHandler.getFirstUsedGeneration();
        }
    }
    _doneWriteWork += cnt;
    LOG(info, "done %" PRIu64 " write work, %u sleeps", cnt, sleep_cnt);
}

void
Fixture::stress_test_indirect(uint64_t write_cnt)
{
    _reportWork = true;
    uint32_t read_threads = getReadThreads();
    LOG(info, "starting stress test indirect, 1 write thread, %u read threads, %" PRIu64 " writes", read_threads, write_cnt);
    auto context = std::make_shared<IndirectContext>();
    _writer.execute(makeLambdaTask([this, context, write_cnt]() { write_indirect_work(write_cnt, *context); }));
    for (uint32_t i = 0; i < read_threads; ++i) {
        _readers->execute(makeLambdaTask([this, context]() { read_indirect_work(*context); }));
    }
    _writer.sync();
    _readers->sync();
}

using GenerationHandlerStressTest = Fixture;

TEST_F(GenerationHandlerStressTest, stress_test_2_readers)
{
    set_read_threads(2);
    stressTest(smoke_test ? 10000 : 1000000);
}

TEST_F(GenerationHandlerStressTest, stress_test_4_readers)
{
    set_read_threads(4);
    stressTest(smoke_test ? 10000 : 1000000);
}

TEST_F(GenerationHandlerStressTest, stress_test_indirect_2_readers)
{
    set_read_threads(2);
    stress_test_indirect(smoke_test ? 10000 : 1000000);
}

TEST_F(GenerationHandlerStressTest, stress_test_indirect_4_readers)
{
    set_read_threads(4);
    stress_test_indirect(smoke_test ? 10000 : 1000000);
}

int main(int argc, char **argv) {
    if (argc > 1 && argv[1] == smoke_test_option) {
        smoke_test = true;
        ++argv;
        --argc;
    }
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "Runtime/World/CScriptSwitch.hpp"

#include "Runtime/CStateManager.hpp"

#include "TCastTo.hpp" // Generated file, do not modify include path

namespace urde {
CScriptSwitch::CScriptSwitch(TUniqueId uid, std::string_view name, const CEntityInfo& info, bool active, bool opened,
                             bool closeOnOpened)
: CEntity(uid, info, active, name), x34_opened(opened), x35_closeOnOpened(closeOnOpened) {}

void CScriptSwitch::Accept(IVisitor& visitor) { visitor.Visit(this); }

void CScriptSwitch::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) {
  if (GetActive()) {
    if (msg == EScriptObjectMessage::Open)
      x34_opened = true;
    else if (msg == EScriptObjectMessage::Close)
      x34_opened = false;
    else if (msg == EScriptObjectMessage::SetToZero) {
      if (x34_opened) {
        SendScriptMsgs(EScriptObjectState::Open, mgr, EScriptObjectMessage::None);
        if (x35_closeOnOpened)
          x34_opened = false;
      } else
        SendScriptMsgs(EScriptObjectState::Closed, mgr, EScriptObjectMessage::None);
    }
  }

  CEntity::AcceptScriptMsg(msg, objId, mgr);
}
} // namespace urde
<commit_msg>CScriptSwitch: Brace conditionals where applicable<commit_after>#include "Runtime/World/CScriptSwitch.hpp"

#include "Runtime/CStateManager.hpp"

#include "TCastTo.hpp" // Generated file, do not modify include path

namespace urde {
CScriptSwitch::CScriptSwitch(TUniqueId uid, std::string_view name, const CEntityInfo& info, bool active, bool opened,
                             bool closeOnOpened)
: CEntity(uid, info, active, name), x34_opened(opened), x35_closeOnOpened(closeOnOpened) {}

void CScriptSwitch::Accept(IVisitor& visitor) { visitor.Visit(this); }

void CScriptSwitch::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId objId, CStateManager& mgr) {
  if (GetActive()) {
    if (msg == EScriptObjectMessage::Open) {
      x34_opened = true;
    } else if (msg == EScriptObjectMessage::Close) {
      x34_opened = false;
    } else if (msg == EScriptObjectMessage::SetToZero) {
      if (x34_opened) {
        SendScriptMsgs(EScriptObjectState::Open, mgr, EScriptObjectMessage::None);
        if (x35_closeOnOpened)
          x34_opened = false;
      } else {
        SendScriptMsgs(EScriptObjectState::Closed, mgr, EScriptObjectMessage::None);
      }
    }
  }

  CEntity::AcceptScriptMsg(msg, objId, mgr);
}
} // namespace urde
<|endoftext|>


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

  This source file is part of the TEM tomography project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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 "CentralWidget.h"
#include "ui_CentralWidget.h"

#include <pqView.h>
#include <vtkAxis.h>
#include <vtkChartXY.h>
#include <vtkContextMouseEvent.h>
#include <vtkContextScene.h>
#include <vtkContextView.h>
#include <vtkEventQtSlotConnect.h>
#include <vtkFloatArray.h>
#include <vtkImageData.h>
#include <vtkIntArray.h>
#include <vtkMathUtilities.h>
#include <vtkObjectFactory.h>
#include <vtkPlotBar.h>
#include <vtkPointData.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>
#include <vtkTransform2D.h>
#include <vtkTrivialProducer.h>

#include <QtDebug>
#include <QThread>

#include "ActiveObjects.h"
#include "ComputeHistogram.h"
#include "ModuleContour.h"
#include "ModuleManager.h"
#include "Utilities.h"

namespace TEM
{

//-----------------------------------------------------------------------------
// This is just here for now - quick and dirty historgram calculations...
void PopulateHistogram(vtkImageData *input, vtkTable *output)
{
  // The output table will have the twice the number of columns, they will be
  // the x and y for input column. This is the bin centers, and the population.
  double minmax[2] = { 0.0, 0.0 };
  const int numberOfBins = 200;

  // The bin values are the centers, extending +/- half an inc either side
  switch (input->GetScalarType())
    {
    vtkTemplateMacro(
          TEM::GetScalarRange(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)),
                         input->GetPointData()->GetScalars()->GetNumberOfTuples(),
                         minmax));
    default:
      break;
    }
  if (minmax[0] == minmax[1])
    {
    minmax[1] = minmax[0] + 1.0;
    }

  double inc = (minmax[1] - minmax[0]) / numberOfBins;
  double halfInc = inc / 2.0;
  vtkSmartPointer<vtkFloatArray> extents =
      vtkFloatArray::SafeDownCast(
        output->GetColumnByName(vtkStdString("image_extents").c_str()));
  if (!extents)
    {
    extents = vtkSmartPointer<vtkFloatArray>::New();
    extents->SetName(vtkStdString("image_extents").c_str());
    }
  extents->SetNumberOfTuples(numberOfBins);
  double min = minmax[0] + halfInc;
  for (int j = 0; j < numberOfBins; ++j)
    {
    extents->SetValue(j, min + j * inc);
    }
  vtkSmartPointer<vtkIntArray> populations =
      vtkIntArray::SafeDownCast(
        output->GetColumnByName(vtkStdString("image_pops").c_str()));
  if (!populations)
    {
    populations = vtkSmartPointer<vtkIntArray>::New();
    populations->SetName(vtkStdString("image_pops").c_str());
    }
  populations->SetNumberOfTuples(numberOfBins);
  int *pops = static_cast<int *>(populations->GetVoidPointer(0));
  for (int k = 0; k < numberOfBins; ++k)
    {
    pops[k] = 0;
    }

  switch (input->GetScalarType())
    {
    vtkTemplateMacro(
          TEM::CalculateHistogram(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)),
                             input->GetPointData()->GetScalars()->GetNumberOfTuples(),
                             minmax[0], pops, inc, numberOfBins));
    default:
      cout << "UpdateFromFile: Unknown data type" << endl;
    }

#ifndef NDEBUG
  vtkIdType total = 0;
  for (int i = 0; i < numberOfBins; ++i)
    total += pops[i];
  assert(total == input->GetPointData()->GetScalars()->GetNumberOfTuples());
#endif

  output->AddColumn(extents.GetPointer());
  output->AddColumn(populations.GetPointer());
}

// Quick background thread for the histogram calculation.
class HistogramWorker : public QThread
{
  Q_OBJECT

  void run();

public:
  HistogramWorker(QObject *p = 0) : QThread(p) {}

  vtkSmartPointer<vtkImageData> input;
  vtkSmartPointer<vtkTable> output;
};

void HistogramWorker::run()
{
  if (input && output)
    {
    PopulateHistogram(input.Get(), output.Get());
    }
}

class CentralWidget::CWInternals
{
public:
  Ui::CentralWidget Ui;
};

class vtkChartHistogram : public vtkChartXY
{
public:
  static vtkChartHistogram * New();

  bool MouseDoubleClickEvent(const vtkContextMouseEvent &mouse);

  vtkNew<vtkTransform2D> Transform;
  double PositionX;
};

vtkStandardNewMacro(vtkChartHistogram)

bool vtkChartHistogram::MouseDoubleClickEvent(const vtkContextMouseEvent &m)
{
  // Determine the location of the click, and emit something we can listen to!
  vtkPlotBar *histo = 0;
  if (this->GetNumberOfPlots() == 1)
    {
    histo = vtkPlotBar::SafeDownCast(this->GetPlot(0));
    }
  if (!histo)
    {
    return false;
    }
  if (this->Transform->GetMTime() < histo->GetMTime())
    {
    this->CalculateUnscaledPlotTransform(histo->GetXAxis(), histo->GetYAxis(),
                                         this->Transform.Get());
    }
  vtkVector2f pos;
  this->Transform->InverseTransformPoints(m.GetScenePos().GetData(), pos.GetData(),
                                          1);
  this->PositionX = pos.GetX();
  this->InvokeEvent(vtkCommand::CursorChangedEvent);
  return true;
}

//-----------------------------------------------------------------------------
CentralWidget::CentralWidget(QWidget* parentObject, Qt::WindowFlags wflags)
  : Superclass(parentObject, wflags),
    Internals(new CentralWidget::CWInternals()),
    Worker(NULL)
{
  this->Internals->Ui.setupUi(this);

  QList<int> sizes;
  sizes << 200 << 200;
  this->Internals->Ui.splitter->setSizes(sizes);
  this->Internals->Ui.splitter->setStretchFactor(0, 0);
  this->Internals->Ui.splitter->setStretchFactor(1, 1);

  // Set up our little chart.
  this->Histogram
      ->SetInteractor(this->Internals->Ui.histogramWidget->GetInteractor());
  this->Internals->Ui.histogramWidget
      ->SetRenderWindow(this->Histogram->GetRenderWindow());
  vtkChartHistogram* chart = this->Chart.Get();
  this->Histogram->GetScene()->AddItem(chart);
  chart->SetBarWidthFraction(0.95);
  chart->SetRenderEmpty(true);
  chart->SetAutoAxes(false);
  chart->GetAxis(vtkAxis::LEFT)->SetTitle("");
  chart->GetAxis(vtkAxis::BOTTOM)->SetTitle("");
  chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED);
  chart->GetAxis(vtkAxis::LEFT)->SetRange(0.0001, 10);
  chart->GetAxis(vtkAxis::LEFT)->SetMinimumLimit(1);
  chart->GetAxis(vtkAxis::LEFT)->SetLogScale(true);

  this->EventLink->Connect(chart, vtkCommand::CursorChangedEvent, this,
                           SLOT(histogramClicked(vtkObject*)));
}

//-----------------------------------------------------------------------------
CentralWidget::~CentralWidget()
{
}

//-----------------------------------------------------------------------------
void CentralWidget::setDataSource(vtkSMSourceProxy* source)
{
  this->DataSource = source;

  // Whenever the data source changes clear the plot, and then populate when
  // ready (or use the cached histogram values.
  this->Chart->ClearPlots();

  // Get the actual data source, build a histogram out of it.
  vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject());
  vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));

  // Check our cache, and use that if appopriate (or update it).
  if (this->HistogramCache.contains(data))
    {
    vtkTable *cachedTable = this->HistogramCache[data];
    if (cachedTable->GetMTime() > data->GetMTime())
      {
      this->setHistogramTable(cachedTable);
      return;
      }
    else
      {
      // Should this ever happen? Do we want to support this?
      qDebug() << "Image data changed after histogram calculation.";
      return;
      }
    }

  // Calculate a histogram.
  vtkNew<vtkTable> table;
  this->HistogramCache[data] = table.Get();

  if (!this->Worker)
    {
    this->Worker = new HistogramWorker(this);
    connect(this->Worker, SIGNAL(finished()), SLOT(histogramReady()));
    }
  else if (this->Worker->isRunning())
    {
    // FIXME: Queue, abort, something.
    qDebug() << "Worker already running, skipping this one.";
    return;
    }
  this->Worker->input = data;
  this->Worker->output = table.Get();
  this->Worker->start();
}

void CentralWidget::histogramReady()
{
  if (!this->Worker || !this->Worker->input || !this->Worker->output)
    return;

  this->setHistogramTable(this->Worker->output.Get());

  this->Worker->input = NULL;
  this->Worker->output = NULL;
}

void CentralWidget::histogramClicked(vtkObject *caller)
{
  //qDebug() << "Histogram clicked at" << this->Chart->PositionX
  //         << "making this a great spot to ask for an isosurface at value"
  //         << this->Chart->PositionX;
  Q_ASSERT(this->DataSource);

  vtkSMViewProxy* view = ActiveObjects::instance().activeView();
  if (!view)
    {
    return;
    }

  // Use active ModuleContour is possible. Otherwise, find the first existing
  // ModuleContour instance or just create a new one, if none exists.
  ModuleContour* contour = qobject_cast<ModuleContour*>(
    ActiveObjects::instance().activeModule());
  if (!contour)
    {
    QList<ModuleContour*> contours =
      ModuleManager::instance().findModules<ModuleContour*>(this->DataSource, view);
    if (contours.size() == 0)
      {
      contour = qobject_cast<ModuleContour*>(ModuleManager::instance().createAndAddModule(
          "Contour", this->DataSource, view));
      }
    else
      {
      contour = contours[0];
      }
    ActiveObjects::instance().setActiveModule(contour);
    }
  Q_ASSERT(contour);
  contour->setIsoValue(this->Chart->PositionX);
  TEM::convert<pqView*>(view)->render();
}

void CentralWidget::setHistogramTable(vtkTable *table)
{
  this->Chart->ClearPlots();
  vtkPlot *plot = this->Chart->AddPlot(vtkChart::BAR);
  plot->SetInputData(table, "image_extents", "image_pops");
  vtkDataArray *arr =
      vtkDataArray::SafeDownCast(table->GetColumnByName("image_pops"));
  if (arr)
    {
    double max = log10(arr->GetRange()[1]);
    vtkAxis *axis = this->Chart->GetAxis(vtkAxis::LEFT);
    axis->SetUnscaledMinimum(1.0);
    axis->SetMaximumLimit(max + 2.0);
    axis->SetMaximum(static_cast<int>(max) + 1.0);
    }
}

} // end of namespace TEM

#include "CentralWidget.moc"
<commit_msg>Set a marker, make the bars blue with black outline<commit_after>/******************************************************************************

  This source file is part of the TEM tomography project.

  Copyright Kitware, Inc.

  This source code is released under the New BSD License, (the "License").

  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 "CentralWidget.h"
#include "ui_CentralWidget.h"

#include <pqView.h>
#include <vtkAxis.h>
#include <vtkChartXY.h>
#include <vtkContextMouseEvent.h>
#include <vtkContextScene.h>
#include <vtkContextView.h>
#include <vtkEventQtSlotConnect.h>
#include <vtkFloatArray.h>
#include <vtkImageData.h>
#include <vtkIntArray.h>
#include <vtkMathUtilities.h>
#include <vtkObjectFactory.h>
#include <vtkPlotBar.h>
#include <vtkPointData.h>
#include <vtkSMSourceProxy.h>
#include <vtkSMViewProxy.h>
#include <vtkTable.h>
#include <vtkTransform2D.h>
#include <vtkTrivialProducer.h>
#include <vtkContext2D.h>
#include <vtkPen.h>

#include <QtDebug>
#include <QThread>

#include "ActiveObjects.h"
#include "ComputeHistogram.h"
#include "ModuleContour.h"
#include "ModuleManager.h"
#include "Utilities.h"

namespace TEM
{

//-----------------------------------------------------------------------------
// This is just here for now - quick and dirty historgram calculations...
void PopulateHistogram(vtkImageData *input, vtkTable *output)
{
  // The output table will have the twice the number of columns, they will be
  // the x and y for input column. This is the bin centers, and the population.
  double minmax[2] = { 0.0, 0.0 };
  const int numberOfBins = 200;

  // The bin values are the centers, extending +/- half an inc either side
  switch (input->GetScalarType())
    {
    vtkTemplateMacro(
          TEM::GetScalarRange(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)),
                         input->GetPointData()->GetScalars()->GetNumberOfTuples(),
                         minmax));
    default:
      break;
    }
  if (minmax[0] == minmax[1])
    {
    minmax[1] = minmax[0] + 1.0;
    }

  double inc = (minmax[1] - minmax[0]) / numberOfBins;
  double halfInc = inc / 2.0;
  vtkSmartPointer<vtkFloatArray> extents =
      vtkFloatArray::SafeDownCast(
        output->GetColumnByName(vtkStdString("image_extents").c_str()));
  if (!extents)
    {
    extents = vtkSmartPointer<vtkFloatArray>::New();
    extents->SetName(vtkStdString("image_extents").c_str());
    }
  extents->SetNumberOfTuples(numberOfBins);
  double min = minmax[0] + halfInc;
  for (int j = 0; j < numberOfBins; ++j)
    {
    extents->SetValue(j, min + j * inc);
    }
  vtkSmartPointer<vtkIntArray> populations =
      vtkIntArray::SafeDownCast(
        output->GetColumnByName(vtkStdString("image_pops").c_str()));
  if (!populations)
    {
    populations = vtkSmartPointer<vtkIntArray>::New();
    populations->SetName(vtkStdString("image_pops").c_str());
    }
  populations->SetNumberOfTuples(numberOfBins);
  int *pops = static_cast<int *>(populations->GetVoidPointer(0));
  for (int k = 0; k < numberOfBins; ++k)
    {
    pops[k] = 0;
    }

  switch (input->GetScalarType())
    {
    vtkTemplateMacro(
          TEM::CalculateHistogram(reinterpret_cast<VTK_TT *>(input->GetPointData()->GetScalars()->GetVoidPointer(0)),
                             input->GetPointData()->GetScalars()->GetNumberOfTuples(),
                             minmax[0], pops, inc, numberOfBins));
    default:
      cout << "UpdateFromFile: Unknown data type" << endl;
    }

#ifndef NDEBUG
  vtkIdType total = 0;
  for (int i = 0; i < numberOfBins; ++i)
    total += pops[i];
  assert(total == input->GetPointData()->GetScalars()->GetNumberOfTuples());
#endif

  output->AddColumn(extents.GetPointer());
  output->AddColumn(populations.GetPointer());
}

// Quick background thread for the histogram calculation.
class HistogramWorker : public QThread
{
  Q_OBJECT

  void run();

public:
  HistogramWorker(QObject *p = 0) : QThread(p) {}

  vtkSmartPointer<vtkImageData> input;
  vtkSmartPointer<vtkTable> output;
};

void HistogramWorker::run()
{
  if (input && output)
    {
    PopulateHistogram(input.Get(), output.Get());
    }
}

class CentralWidget::CWInternals
{
public:
  Ui::CentralWidget Ui;
};

class vtkHistogramMarker : public vtkPlot
{
public:
  static vtkHistogramMarker * New() { return new vtkHistogramMarker; }

  double PositionX;

  bool Paint(vtkContext2D *painter)
  {
    vtkNew<vtkPen> pen;
    pen->SetColor(255, 0, 0, 255);
    pen->SetWidth(2.0);
    painter->ApplyPen(pen.Get());
    painter->DrawLine(PositionX, 0, PositionX, 1e9);
    return true;
  }
};

class vtkChartHistogram : public vtkChartXY
{
public:
  static vtkChartHistogram * New();

  bool MouseDoubleClickEvent(const vtkContextMouseEvent &mouse);

  vtkNew<vtkTransform2D> Transform;
  double PositionX;
  vtkNew<vtkHistogramMarker> Marker;
};

vtkStandardNewMacro(vtkChartHistogram)

bool vtkChartHistogram::MouseDoubleClickEvent(const vtkContextMouseEvent &m)
{
  // Determine the location of the click, and emit something we can listen to!
  vtkPlotBar *histo = 0;
  if (this->GetNumberOfPlots() > 0)
    {
    histo = vtkPlotBar::SafeDownCast(this->GetPlot(0));
    }
  if (!histo)
    {
    return false;
    }
  if (this->Transform->GetMTime() < histo->GetMTime())
    {
    this->CalculateUnscaledPlotTransform(histo->GetXAxis(), histo->GetYAxis(),
                                         this->Transform.Get());
    }
  vtkVector2f pos;
  this->Transform->InverseTransformPoints(m.GetScenePos().GetData(), pos.GetData(),
                                          1);
  this->PositionX = pos.GetX();
  this->Marker->PositionX = this->PositionX;
  this->Marker->Modified();
  this->Scene->SetDirty(true);
  if (this->GetNumberOfPlots() == 1)
    {
    this->AddPlot(this->Marker.Get());
    }
  this->InvokeEvent(vtkCommand::CursorChangedEvent);
  return true;
}

//-----------------------------------------------------------------------------
CentralWidget::CentralWidget(QWidget* parentObject, Qt::WindowFlags wflags)
  : Superclass(parentObject, wflags),
    Internals(new CentralWidget::CWInternals()),
    Worker(NULL)
{
  this->Internals->Ui.setupUi(this);

  QList<int> sizes;
  sizes << 200 << 200;
  this->Internals->Ui.splitter->setSizes(sizes);
  this->Internals->Ui.splitter->setStretchFactor(0, 0);
  this->Internals->Ui.splitter->setStretchFactor(1, 1);

  // Set up our little chart.
  this->Histogram
      ->SetInteractor(this->Internals->Ui.histogramWidget->GetInteractor());
  this->Internals->Ui.histogramWidget
      ->SetRenderWindow(this->Histogram->GetRenderWindow());
  vtkChartHistogram* chart = this->Chart.Get();
  this->Histogram->GetScene()->AddItem(chart);
  chart->SetBarWidthFraction(0.95);
  chart->SetRenderEmpty(true);
  chart->SetAutoAxes(false);
  chart->GetAxis(vtkAxis::LEFT)->SetTitle("");
  chart->GetAxis(vtkAxis::BOTTOM)->SetTitle("");
  chart->GetAxis(vtkAxis::LEFT)->SetBehavior(vtkAxis::FIXED);
  chart->GetAxis(vtkAxis::LEFT)->SetRange(0.0001, 10);
  chart->GetAxis(vtkAxis::LEFT)->SetMinimumLimit(1);
  chart->GetAxis(vtkAxis::LEFT)->SetLogScale(true);

  this->EventLink->Connect(chart, vtkCommand::CursorChangedEvent, this,
                           SLOT(histogramClicked(vtkObject*)));
}

//-----------------------------------------------------------------------------
CentralWidget::~CentralWidget()
{
}

//-----------------------------------------------------------------------------
void CentralWidget::setDataSource(vtkSMSourceProxy* source)
{
  this->DataSource = source;

  // Whenever the data source changes clear the plot, and then populate when
  // ready (or use the cached histogram values.
  this->Chart->ClearPlots();

  // Get the actual data source, build a histogram out of it.
  vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(source->GetClientSideObject());
  vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));

  // Check our cache, and use that if appopriate (or update it).
  if (this->HistogramCache.contains(data))
    {
    vtkTable *cachedTable = this->HistogramCache[data];
    if (cachedTable->GetMTime() > data->GetMTime())
      {
      this->setHistogramTable(cachedTable);
      return;
      }
    else
      {
      // Should this ever happen? Do we want to support this?
      qDebug() << "Image data changed after histogram calculation.";
      return;
      }
    }

  // Calculate a histogram.
  vtkNew<vtkTable> table;
  this->HistogramCache[data] = table.Get();

  if (!this->Worker)
    {
    this->Worker = new HistogramWorker(this);
    connect(this->Worker, SIGNAL(finished()), SLOT(histogramReady()));
    }
  else if (this->Worker->isRunning())
    {
    // FIXME: Queue, abort, something.
    qDebug() << "Worker already running, skipping this one.";
    return;
    }
  this->Worker->input = data;
  this->Worker->output = table.Get();
  this->Worker->start();
}

void CentralWidget::histogramReady()
{
  if (!this->Worker || !this->Worker->input || !this->Worker->output)
    return;

  this->setHistogramTable(this->Worker->output.Get());

  this->Worker->input = NULL;
  this->Worker->output = NULL;
}

void CentralWidget::histogramClicked(vtkObject *caller)
{
  //qDebug() << "Histogram clicked at" << this->Chart->PositionX
  //         << "making this a great spot to ask for an isosurface at value"
  //         << this->Chart->PositionX;
  Q_ASSERT(this->DataSource);

  vtkSMViewProxy* view = ActiveObjects::instance().activeView();
  if (!view)
    {
    return;
    }

  // Use active ModuleContour is possible. Otherwise, find the first existing
  // ModuleContour instance or just create a new one, if none exists.
  ModuleContour* contour = qobject_cast<ModuleContour*>(
    ActiveObjects::instance().activeModule());
  if (!contour)
    {
    QList<ModuleContour*> contours =
      ModuleManager::instance().findModules<ModuleContour*>(this->DataSource, view);
    if (contours.size() == 0)
      {
      contour = qobject_cast<ModuleContour*>(ModuleManager::instance().createAndAddModule(
          "Contour", this->DataSource, view));
      }
    else
      {
      contour = contours[0];
      }
    ActiveObjects::instance().setActiveModule(contour);
    }
  Q_ASSERT(contour);
  contour->setIsoValue(this->Chart->PositionX);
  TEM::convert<pqView*>(view)->render();
}

void CentralWidget::setHistogramTable(vtkTable *table)
{
  this->Chart->ClearPlots();
  vtkPlot *plot = this->Chart->AddPlot(vtkChart::BAR);
  plot->SetInputData(table, "image_extents", "image_pops");
  plot->SetColor(0, 0, 255, 255);
  vtkDataArray *arr =
      vtkDataArray::SafeDownCast(table->GetColumnByName("image_pops"));
  if (arr)
    {
    double max = log10(arr->GetRange()[1]);
    vtkAxis *axis = this->Chart->GetAxis(vtkAxis::LEFT);
    axis->SetUnscaledMinimum(1.0);
    axis->SetMaximumLimit(max + 2.0);
    axis->SetMaximum(static_cast<int>(max) + 1.0);
    }
}

} // end of namespace TEM

#include "CentralWidget.moc"
<|endoftext|>


<commit_before>#include "BinaryTree.hpp"
#include <catch.hpp>

SCENARIO("default constructor")
{
	Tree<int> node;
	REQUIRE(node.root_() == nullptr);
}

SCENARIO("insert")
{
	Tree<int> tree;
	tree.insert(7);
	REQUIRE(tree.x_() == 7);
	REQUIRE(tree.left_() == nullptr);
	REQUIRE(tree.right_() == nullptr);
}

SCENARIO("search")
{
	Tree<int> tree;
	bool a;
	tree.insert(7);
	a = tree.check_search(7);
	REQUIRE(a == true);
}

SCENARIO("size")
{
	Tree<int> tree;
	int size = 0;
	tree.insert(7);
	size = tree.size(tree.root_());
	REQUIRE(size == 1);
}

SCENARIO("prev_")
{
	Tree<int> tree;
	Node<int> * node;
	tree.insert(3);
	tree.insert(4);
	tree.insert(2);
	node = tree.prev_(4);
	REQUIRE(node->x == 3);
}

SCENARIO("deleteX")
{
	Tree<int> tree;
	int size1, size2;
	tree.insert(3);
	tree.insert(4);
	tree.insert(2);
	tree.insert(0);
	size1 = tree.size(tree.root_());
	tree.deleteX(0);
	size2 = tree.size(tree.root_());
	REQUIRE(size1 == 1 + size2);
}

SCENARIO("out_to_file", "fIn")
{
	Tree<int> tree1, tree2;
	int size1, size2;
	tree1.insert(3);
	tree1.insert(4);
	tree1.out_to_file("TreeOut.txt");
	size1 = tree1.size(tree1.root_());
	tree2.fIn("TreeOut.txt");
	size2 = tree2.size(tree2.root_());
	REQUIRE(size1 == 2);
	REQUIRE(size2 == 2);
	REQUIRE(tree2.x_() == 3);
	REQUIRE(tree2.left_() == nullptr);
	REQUIRE(tree2.right_() != nullptr);
}
<commit_msg>Update init.cpp<commit_after>#include "BinaryTree.hpp"
#include <catch.hpp>

SCENARIO("default constructor")
{
	Tree<int> node;
	REQUIRE(node.root_() == nullptr);
}

SCENARIO("insert")
{
	Tree<int> tree;
	tree.insert(7);
	REQUIRE(tree.x_() == 7);
	REQUIRE(tree.left_() == nullptr);
	REQUIRE(tree.right_() == nullptr);
}

SCENARIO("search")
{
	Tree<int> tree;
	bool a;
	tree.insert(7);
	a = tree.check_search(7);
	REQUIRE(a == true);
}

SCENARIO("size")
{
	Tree<int> tree;
	int size = 0;
	tree.insert(7);
	size = tree.size(tree.root_());
	REQUIRE(size == 1);
}

SCENARIO("prev_")
{
	Tree<int> tree;
	Node<int> * node;
	tree.insert(3);
	tree.insert(4);
	tree.insert(2);
	node = tree.prev_(4);
	REQUIRE(node->x == 3);
}

SCENARIO("deleteX")
{
	Tree<int> tree;
	int size1, size2;
	tree.insert(3);
	tree.insert(4);
	tree.insert(2);
	tree.insert(0);
	size1 = tree.size(tree.root_());
	tree.deleteX(0);
	size2 = tree.size(tree.root_());
	REQUIRE(size1 == 1 + size2);
}

SCENARIO("out_to_file", "fIn")
{
	Tree<int> tree1, tree2;
	int size1, size2;
	tree1.insert(3);
	tree1.insert(4);
	tree1.out_to_file("TreeOut.txt");
	size1 = tree1.size(tree1.root_());
	tree2.fIn("TreeOut.txt");
	size2 = tree2.size(tree2.root_());
	REQUIRE(size1 == 2);
	REQUIRE(size2 == 2);
	REQUIRE(tree2.x_() == 3);
}
<|endoftext|>


<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>

namespace blackhole {
namespace testing {

using ::testing::Invoke;
using ::testing::_;

namespace mock {
namespace {

class handler_t : public ::blackhole::handler_t {
public:
    MOCK_METHOD1(execute, void(const record_t&));
};

}  // namespace
}  // namespace mock

TEST(RootLogger, Log) {
    // Can be initialized with none handlers, does nothing.
    root_logger_t logger({});
    logger.log(0, "GET /porn.png HTTP/1.1");
}

TEST(RootLogger, ConstLog) {
    const root_logger_t logger({});
    logger.log(0, "GET /porn.png HTTP/1.1");
}

TEST(RootLogger, DispatchRecordToHandlers) {
    std::vector<std::unique_ptr<handler_t>> handlers;
    std::vector<mock::handler_t*> handlers_view;

    for (int i = 0; i < 4; ++i) {
        std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
        handlers_view.push_back(handler.get());
        handlers.push_back(std::move(handler));
    }

    const root_logger_t logger(std::move(handlers));

    for (auto handler : handlers_view) {
        EXPECT_CALL(*handler, execute(_))
            .Times(1)
            .WillOnce(Invoke([](const record_t& record) {
                EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
                EXPECT_EQ("GET /porn.png HTTP/1.1", record.formatted().to_string());
                EXPECT_EQ(0, record.severity());
                EXPECT_EQ(0, record.attributes().size());
            }));
    }

    logger.log(0, "GET /porn.png HTTP/1.1");
}

}  // namespace testing
}  // namespace blackhole
<commit_msg>chore(tests): add test to check logger overload<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>

namespace blackhole {
namespace testing {

using ::testing::Invoke;
using ::testing::_;

namespace mock {
namespace {

class handler_t : public ::blackhole::handler_t {
public:
    MOCK_METHOD1(execute, void(const record_t&));
};

}  // namespace
}  // namespace mock

TEST(RootLogger, Log) {
    // Can be initialized with none handlers, does nothing.
    root_logger_t logger({});
    logger.log(0, "GET /porn.png HTTP/1.1");
}

TEST(RootLogger, ConstLog) {
    const root_logger_t logger({});
    logger.log(0, "GET /porn.png HTTP/1.1");
}

TEST(RootLogger, DispatchRecordToHandlers) {
    std::vector<std::unique_ptr<handler_t>> handlers;
    std::vector<mock::handler_t*> handlers_view;

    for (int i = 0; i < 4; ++i) {
        std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
        handlers_view.push_back(handler.get());
        handlers.push_back(std::move(handler));
    }

    const root_logger_t logger(std::move(handlers));

    for (auto handler : handlers_view) {
        EXPECT_CALL(*handler, execute(_))
            .Times(1)
            .WillOnce(Invoke([](const record_t& record) {
                EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
                EXPECT_EQ("GET /porn.png HTTP/1.1", record.formatted().to_string());
                EXPECT_EQ(0, record.severity());
                EXPECT_EQ(0, record.attributes().size());
            }));
    }

    logger.log(0, "GET /porn.png HTTP/1.1");
}

TEST(RootLogger, DispatchRecordWithAttributesToHandlers) {
    std::vector<std::unique_ptr<handler_t>> handlers;
    std::vector<mock::handler_t*> handlers_view;

    for (int i = 0; i < 4; ++i) {
        std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
        handlers_view.push_back(handler.get());
        handlers.push_back(std::move(handler));
    }

    const root_logger_t logger(std::move(handlers));

    const view_of<attributes_t>::type attributes{{"key#1", {42}}};
    attribute_pack pack{attributes};

    for (auto handler : handlers_view) {
        EXPECT_CALL(*handler, execute(_))
            .Times(1)
            .WillOnce(Invoke([&](const record_t& record) {
                EXPECT_EQ("GET /porn.png HTTP/1.1", record.message().to_string());
                EXPECT_EQ("GET /porn.png HTTP/1.1", record.formatted().to_string());
                EXPECT_EQ(0, record.severity());
                ASSERT_EQ(1, record.attributes().size());
                EXPECT_EQ(attributes, record.attributes().at(0).get());
            }));
    }

    logger.log(0, "GET /porn.png HTTP/1.1", pack);
}

}  // namespace testing
}  // namespace blackhole
<|endoftext|>


<commit_before>
#pragma once

#include <vector>
#include <unordered_map>
#include <iostream>
#include <limits>
#include <functional>

template <class E>
class PriorityQueue
{
    private:
        struct Node
        {
            E elem;
            double key;
        };

        const double MAX = std::numeric_limits<double>::infinity();

        std::vector<Node> _elems;
        std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > _indexLookUp;
        int _size;

        void buildMinHeap(void)
        {
            int startIndex = _size/2;

            for(int i = startIndex; i >= 0; i--)
            {
                minHeapify(i);
            }
        }
        void swap(int ind1,int ind2)
        {
            Node tmp = _elems[ind1];

            _elems[ind1] = _elems[ind2];
            _elems[ind2] = tmp;

            _indexLookUp[_elems[ind1].elem] = ind1;
            _indexLookUp[_elems[ind2].elem] = ind2;
        }
        void minHeapify(int index)
        {
            int indexOfMin = 0;
            int left = leftChild(index);
            int right = rightChild(index);

            if(left >= 0 && _elems[index].key > _elems[left].key)
            {
                indexOfMin = left;
            }
            else
            {
                indexOfMin = index;
            }

            if(right >= 0 && _elems[indexOfMin].key > _elems[right].key)
            {
                indexOfMin = right;
            }

            if(indexOfMin != index)
            {
                swap(indexOfMin,index);

                minHeapify(indexOfMin);
            }
        }
        int leftChild(int index)
        {
            int res = 2*index + 1;

            return (res < _size) ? res : -1;
        }
        int rightChild(int index)
        {
            int res = 2*index + 2;

            return (res < _size) ? res : -1;
        }
        int parent(int index)
        {
            return (index <= 0) ? -1 : ((index - 1)/2);
        }

    public:
        PriorityQueue(std::function<size_t(E)> hashFunctor, std::function<bool(E,E)> equalityFunctor)
        {

            std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > m(0,hashFunctor,equalityFunctor);

            _indexLookUp = m;

            _size = 0;
        }

        E peek(void)
        {
            return _elems[0].elem;
        }
        E poll(void)
        {
            E result = _elems[0].elem;

            _elems[0] = _elems.back();
            auto it = _indexLookUp.find(_elems.back().elem);
            _indexLookUp.erase(it);
            _elems.pop_back();

            _indexLookUp[_elems[0].elem] = 0;

            _size -= 1;

            minHeapify(0);

            return result;
        }
        void decreaseKey(E elem, double newKey)
        {
            int index = _indexLookUp[elem];

            if(_elems[index].key > newKey)
            {
                _elems[index].key = newKey;

                int current = index;
                while(current > 0)
                {
                    if(_elems[current].key < _elems[parent(current)].key)
                    {
                        swap(current,parent(current));

                        current = parent(current);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        void insert(E e, double k)
        {
            Node n;
            n.elem = e;
            n.key = MAX;

            _elems.push_back(n);

            _indexLookUp[e] = _size;

            _size += 1;

            decreaseKey(e,k);
        }
        void update(E e, double k)
        {
            if(_indexLookUp.find(e) != _indexLookUp.end())
            {
                decreaseKey(e,k);
            }
            else
            {
                insert(e,k);
            }
        }
        void merge(PriorityQueue<E> other)
        {
            for(unsigned long i = 0; i < other._elems.size(); i++)
            {
                _elems.push_back(other._elems[i]);
                _indexLookUp[_elems.back().elem] = _size + i;
                _size += 1;
            }

            buildMinHeap();
        }

        void print(void)
        {
            if(_elems.size() == 0)
            {
                std::cout << "empty queue" << std::endl;
            }

            for(auto node : _elems)
            {
                std::cout << "key: " << node.key << ", ";
            }

            std::cout << std::endl;
        }

};

<commit_msg>added isEmpty() method to queue<commit_after>
#pragma once

#include <vector>
#include <unordered_map>
#include <iostream>
#include <limits>
#include <functional>

template <class E>
class PriorityQueue
{
    private:
        struct Node
        {
            E elem;
            double key;
        };

        const double MAX = std::numeric_limits<double>::infinity();

        std::vector<Node> _elems;
        std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > _indexLookUp;
        int _size;

        void buildMinHeap(void)
        {
            int startIndex = _size/2;

            for(int i = startIndex; i >= 0; i--)
            {
                minHeapify(i);
            }
        }
        void swap(int ind1,int ind2)
        {
            Node tmp = _elems[ind1];

            _elems[ind1] = _elems[ind2];
            _elems[ind2] = tmp;

            _indexLookUp[_elems[ind1].elem] = ind1;
            _indexLookUp[_elems[ind2].elem] = ind2;
        }
        void minHeapify(int index)
        {
            int indexOfMin = 0;
            int left = leftChild(index);
            int right = rightChild(index);

            if(left >= 0 && _elems[index].key > _elems[left].key)
            {
                indexOfMin = left;
            }
            else
            {
                indexOfMin = index;
            }

            if(right >= 0 && _elems[indexOfMin].key > _elems[right].key)
            {
                indexOfMin = right;
            }

            if(indexOfMin != index)
            {
                swap(indexOfMin,index);

                minHeapify(indexOfMin);
            }
        }
        int leftChild(int index)
        {
            int res = 2*index + 1;

            return (res < _size) ? res : -1;
        }
        int rightChild(int index)
        {
            int res = 2*index + 2;

            return (res < _size) ? res : -1;
        }
        int parent(int index)
        {
            return (index <= 0) ? -1 : ((index - 1)/2);
        }

    public:
        PriorityQueue(std::function<size_t(E)> hashFunctor, std::function<bool(E,E)> equalityFunctor)
        {

            std::unordered_map<E,int,std::function<size_t(E)>,std::function<bool(E,E)> > m(0,hashFunctor,equalityFunctor);

            _indexLookUp = m;

            _size = 0;
        }

        bool isEmpty()
        {
            return (_size == 0);
        }

        E peek(void)
        {
            return _elems[0].elem;
        }
        E poll(void)
        {
            E result = _elems[0].elem;

            _elems[0] = _elems.back();
            auto it = _indexLookUp.find(_elems.back().elem);
            _indexLookUp.erase(it);
            _elems.pop_back();

            _indexLookUp[_elems[0].elem] = 0;

            _size -= 1;

            minHeapify(0);

            return result;
        }
        void decreaseKey(E elem, double newKey)
        {
            int index = _indexLookUp[elem];

            if(_elems[index].key > newKey)
            {
                _elems[index].key = newKey;

                int current = index;
                while(current > 0)
                {
                    if(_elems[current].key < _elems[parent(current)].key)
                    {
                        swap(current,parent(current));

                        current = parent(current);
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        void insert(E e, double k)
        {
            Node n;
            n.elem = e;
            n.key = MAX;

            _elems.push_back(n);

            _indexLookUp[e] = _size;

            _size += 1;

            decreaseKey(e,k);
        }
        void update(E e, double k)
        {
            if(_indexLookUp.find(e) != _indexLookUp.end())
            {
                decreaseKey(e,k);
            }
            else
            {
                insert(e,k);
            }
        }
        void merge(PriorityQueue<E> other)
        {
            for(unsigned long i = 0; i < other._elems.size(); i++)
            {
                _elems.push_back(other._elems[i]);
                _indexLookUp[_elems.back().elem] = _size + i;
                _size += 1;
            }

            buildMinHeap();
        }

        void print(void)
        {
            if(_elems.size() == 0)
            {
                std::cout << "empty queue" << std::endl;
            }

            for(auto node : _elems)
            {
                std::cout << "key: " << node.key << ", ";
            }

            std::cout << std::endl;
        }

};

<|endoftext|>


<commit_before>#pragma once
#include "../lubee/random.hpp"
#include "../lubee/check_serialization.hpp"
#include <gtest/gtest.h>
#include <cereal/archives/json.hpp>
#include <cereal/archives/binary.hpp>

namespace spi {
	namespace test {
		class Random : public ::testing::Test {
			private:
				lubee::RandomMT	_mt;
			public:
				Random(): _mt(lubee::RandomMT::Make<4>()) {}
				auto& mt() {
					return _mt;
				}
		};
		#define USING(t) using t = typename TestFixture::t

		template <class T>
		class TestObj {
			public:
				using value_t = T;
			private:
				value_t _value;
				static int s_counter;
			public:
				TestObj(TestObj&&) = default;
				TestObj(const TestObj&) = delete;
				TestObj() {
					++s_counter;
				}
				TestObj(const value_t& v):
					_value(v)
				{
					++s_counter;
				}
				~TestObj() {
					--s_counter;
				}
				TestObj& operator = (const T& t) {
					_value = t;
					return *this;
				}
				bool operator == (const TestObj& m) const {
					return _value == m._value;
				}
				static void InitializeCounter() {
					s_counter = 0;
				}
				static bool CheckCounter(const int c) {
					return c == s_counter;
				}
		};
		template <class T>
		int TestObj<T>::s_counter;
		template <class T>
		inline bool operator == (const T& t, const TestObj<T>& o) {
			return o == t;
		}
		// コンストラクタ・デストラクタが呼ばれる回数をチェックする機構の初期化
		template <class T, ENABLE_IF(!std::is_trivial<T>{})>
		void InitializeCounter() {
			T::InitializeCounter();
		}
		template <class T, ENABLE_IF(std::is_trivial<T>{})>
		void InitializeCounter() {}

		// コンストラクタ・デストラクタが呼ばれる回数をチェック
		template <class T, class V, ENABLE_IF(!std::is_trivial<T>{})>
		void CheckCounter(const V& v) {
			ASSERT_TRUE(T::CheckCounter(v));
		}
		template <class T, class V, ENABLE_IF(std::is_trivial<T>{})>
		void CheckCounter(const V&) {}
	}
}
<commit_msg>TestObj: getValue(), noexceptを付加<commit_after>#pragma once
#include "../lubee/random.hpp"
#include "../lubee/check_serialization.hpp"
#include <gtest/gtest.h>
#include <cereal/archives/json.hpp>
#include <cereal/archives/binary.hpp>

namespace spi {
	namespace test {
		class Random : public ::testing::Test {
			private:
				lubee::RandomMT	_mt;
			public:
				Random(): _mt(lubee::RandomMT::Make<4>()) {}
				auto& mt() noexcept {
					return _mt;
				}
		};
		#define USING(t) using t = typename TestFixture::t

		template <class T>
		class TestObj {
			public:
				using value_t = T;
			private:
				value_t _value;
				static int s_counter;
			public:
				TestObj(TestObj&&) = default;
				TestObj(const TestObj&) = delete;
				TestObj() noexcept {
					++s_counter;
				}
				TestObj(const value_t& v) noexcept:
					_value(v)
				{
					++s_counter;
				}
				~TestObj() noexcept {
					--s_counter;
				}
				TestObj& operator = (const T& t) {
					_value = t;
					return *this;
				}
				value_t getValue() const noexcept {
					return _value;
				}
				bool operator == (const TestObj& m) const noexcept {
					return _value == m._value;
				}
				static void InitializeCounter() noexcept {
					s_counter = 0;
				}
				static bool CheckCounter(const int c) noexcept {
					return c == s_counter;
				}
		};
		template <class T>
		int TestObj<T>::s_counter;
		template <class T>
		inline bool operator == (const T& t, const TestObj<T>& o) noexcept {
			return o == t;
		}
		// コンストラクタ・デストラクタが呼ばれる回数をチェックする機構の初期化
		template <class T, ENABLE_IF(!std::is_trivial<T>{})>
		void InitializeCounter() {
			T::InitializeCounter();
		}
		template <class T, ENABLE_IF(std::is_trivial<T>{})>
		void InitializeCounter() noexcept {}

		// コンストラクタ・デストラクタが呼ばれる回数をチェック
		template <class T, class V, ENABLE_IF(!std::is_trivial<T>{})>
		void CheckCounter(const V& v) {
			ASSERT_TRUE(T::CheckCounter(v));
		}
		template <class T, class V, ENABLE_IF(std::is_trivial<T>{})>
		void CheckCounter(const V&) noexcept {}
	}
}
<|endoftext|>


<commit_before>#include <PresentaBALLSettings.h>
#include <PresentaBALLView.h>

#include <BALL/SYSTEM/path.h>
#include <BALL/SYSTEM/directory.h>

#include <QLineEdit>
#include <QFileDialog>

namespace BALL
{
	namespace VIEW
	{
		PresentaBALLSettings::PresentaBALLSettings(QWidget* parent, const char* name, Qt::WindowFlags fl)
			: ConfigDialog(parent, fl),
			  Ui_PresentaBALLSettingsData()
		{
			setupUi(this);
			setObjectName(name);
			setWidgetStackName((String)tr("PresentaBALL"));
			setINIFileSectionName("PresentaBALL");
			registerWidgets_();

			connect(browse_button, SIGNAL(clicked()), this, SLOT(selectIndexHTMLLocation()));
		}

		PresentaBALLSettings::~PresentaBALLSettings()
		{ }

		void PresentaBALLSettings::setIndexHTMLLocation(const QString& path)
		{
			index_html_edit->setText(path);
		}

		QString PresentaBALLSettings::getIndexHTMLLocation()
		{
			return index_html_edit->text();
		}

		void PresentaBALLSettings::selectIndexHTMLLocation()
		{
			QString new_location = QFileDialog::getOpenFileName(this, "Select a start page for PresentaBALL");

			if (new_location != "")
			{
				setIndexHTMLLocation(new_location);
			}
		}

		void PresentaBALLSettings::restoreDefaultValues(bool all)
		{
			PreferencesEntry::restoreDefaultValues(all);

			//set the webpage language according to the language set in preferences
			String home_dir = Directory::getUserHomeDir();
			INIFile f(home_dir + FileSystem::PATH_SEPARATOR + ".BALLView");
			f.read();

			Path p;
			String s;
			if (f.hasEntry("GENERAL", "language") && f.getValue("GENERAL", "language") == "de_DE")
			{
				s = p.find("HTMLBasedInterface/html_de");
			}
			else
			{
				s = p.find("HTMLBasedInterface/html_eng");
			}

			if (!s.isEmpty())
			{
				setIndexHTMLLocation((s + "/index.html").c_str());
			}
			else
			{
				Log.error() << "No html directory set!" << std::endl;
			}
		}

	}
}
<commit_msg>[PresentaBALL] Fix: Set default values in settings dialog<commit_after>#include <PresentaBALLSettings.h>
#include <PresentaBALLView.h>

#include <BALL/SYSTEM/path.h>
#include <BALL/SYSTEM/directory.h>

#include <QLineEdit>
#include <QFileDialog>

namespace BALL
{
	namespace VIEW
	{
		PresentaBALLSettings::PresentaBALLSettings(QWidget* parent, const char* name, Qt::WindowFlags fl)
			: ConfigDialog(parent, fl),
			  Ui_PresentaBALLSettingsData()
		{
			setupUi(this);
			setObjectName(name);
			setWidgetStackName((String)tr("PresentaBALL"));
			setINIFileSectionName("PresentaBALL");
			registerWidgets_();

			restoreDefaultValues();
			connect(browse_button, SIGNAL(clicked()), this, SLOT(selectIndexHTMLLocation()));
		}

		PresentaBALLSettings::~PresentaBALLSettings()
		{ }

		void PresentaBALLSettings::setIndexHTMLLocation(const QString& path)
		{
			index_html_edit->setText(path);
		}

		QString PresentaBALLSettings::getIndexHTMLLocation()
		{
			return index_html_edit->text();
		}

		void PresentaBALLSettings::selectIndexHTMLLocation()
		{
			QString new_location = QFileDialog::getOpenFileName(this, "Select a start page for PresentaBALL");

			if (new_location != "")
			{
				setIndexHTMLLocation(new_location);
			}
		}

		void PresentaBALLSettings::restoreDefaultValues(bool all)
		{
			PreferencesEntry::restoreDefaultValues(all);

			//set the webpage language according to the language set in preferences
			String home_dir = Directory::getUserHomeDir();
			INIFile f(home_dir + FileSystem::PATH_SEPARATOR + ".BALLView");
			f.read();

			Path p;
			String s;
			if (f.hasEntry("GENERAL", "language") && f.getValue("GENERAL", "language") == "de_DE")
			{
				s = p.find("HTMLBasedInterface/html_de");
			}
			else
			{
				s = p.find("HTMLBasedInterface/html_eng");
			}

			if (!s.isEmpty())
			{
				setIndexHTMLLocation((s + "/index.html").c_str());
			}
			else
			{
				Log.error() << "No html directory set!" << std::endl;
			}
		}

	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fwkhelper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 22:57:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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 GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

#include "workwin.hxx"
#include <sfx2/frame.hxx>

void SAL_CALL RefreshToolbars( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );
    if ( xFrame.is() )
    {
        SfxFrame* pFrame=0;
        for ( pFrame = SfxFrame::GetFirst(); pFrame; pFrame = SfxFrame::GetNext( *pFrame ) )
        {
            if ( pFrame->GetFrameInterface() == xFrame )
                break;
        }

        if ( pFrame )
        {
            SfxWorkWindow* pWrkWin = pFrame->GetWorkWindow_Impl();
            if ( pWrkWin )
                pWrkWin->UpdateObjectBars_Impl();
        }
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.216); FILE MERGED 2008/04/01 15:38:44 thb 1.4.216.3: #i85898# Stripping all external header guards 2008/04/01 12:40:40 thb 1.4.216.2: #i85898# Stripping all external header guards 2008/03/31 13:38:01 rt 1.4.216.1: #i87441# Change license header to LPGL v3.<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: fwkhelper.cxx,v $
 * $Revision: 1.5 $
 *
 * 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_sfx2.hxx"
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/frame/XFrame.hpp>
#include "sal/config.h"

#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>

#include "workwin.hxx"
#include <sfx2/frame.hxx>

void SAL_CALL RefreshToolbars( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );
    if ( xFrame.is() )
    {
        SfxFrame* pFrame=0;
        for ( pFrame = SfxFrame::GetFirst(); pFrame; pFrame = SfxFrame::GetNext( *pFrame ) )
        {
            if ( pFrame->GetFrameInterface() == xFrame )
                break;
        }

        if ( pFrame )
        {
            SfxWorkWindow* pWrkWin = pFrame->GetWorkWindow_Impl();
            if ( pWrkWin )
                pWrkWin->UpdateObjectBars_Impl();
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>tdf#90994 Sidebar tab bar buttons should should have accessible names<commit_after><|endoftext|>


<commit_before>#include <string.h>
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>
#include <ctime>
#include <assert.h>
#define pi 3.14159
#define mod 1000000007
using namespace std;
long long int a[500000];
int main()
{
	long long int n = 0,m = 0,a = 2,total_need = 0;
	cin>>n>>m;
	total_need = (n*m)/a;
	cout<<total_need;
	return 0;
}
<commit_msg>Delete Domino_piling.cpp<commit_after><|endoftext|>


<commit_before>/*
 * bacteria-core, core for cellular automaton
 * Copyright (C) 2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>

#include "Model.hpp"

typedef int (Implementation::Model::*IntOneArgMethod) (
    const Abstract::Point& coordinates
) const;

typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) (
    const Abstract::Point& coordinates
) const;

typedef void (Implementation::Model::*OneArgMethod) (
    const Abstract::Point& coordinates
);

typedef void (Implementation::Model::*TwoArgsMethod) (
    const Abstract::Point& coordinates,
    int change
);

typedef void (Implementation::Model::*IntThreeArgsMethod) (
    int team,
    int bacterium_index,
    int spec
);

typedef void (Implementation::Model::*ThreeArgsMethod) (
    int team,
    int bacterium_index,
    const Abstract::Point& coordinates
);

typedef void (Implementation::Model::*MultiArgsMethod) (
    const Abstract::Point& coordinates,
    int mass,
    int direction,
    int team,
    int instruction
);

template<typename Func>
static void checkOneArgMethod(
    Implementation::Model* model,
    Func model_method,
    int arg1,
    int arg2
) {
    Abstract::Point coordinates(arg1, arg2);
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(coordinates), Exception
    );
}

template<typename Func>
void checkModelMethodForThrow(
    Implementation::Model* model,
    Func model_method,
    int arg1,
    int arg2
) {
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(arg1, arg2), Exception
    );
}

template<>
void checkModelMethodForThrow<IntOneArgMethod>(
    Implementation::Model* model,
    IntOneArgMethod model_method,
    int arg1,
    int arg2
) {
    checkOneArgMethod(model, model_method, arg1, arg2);
}

template<>
void checkModelMethodForThrow<OneArgMethod>(
    Implementation::Model* model,
    OneArgMethod model_method,
    int arg1,
    int arg2
) {
    checkOneArgMethod(model, model_method, arg1, arg2);
}

template<>
void checkModelMethodForThrow<TwoArgsMethod>(
    Implementation::Model* model,
    TwoArgsMethod model_method,
    int arg1,
    int arg2
) {
    Abstract::Point coordinates(arg1, arg2);
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(coordinates, 0), Exception
    );
}

template<>
void checkModelMethodForThrow<MultiArgsMethod>(
    Implementation::Model* model,
    MultiArgsMethod model_method,
    int arg1,
    int arg2
) {
    Abstract::Point coordinates(arg1, arg2);
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(
            coordinates,
            DEFAULT_MASS,
            0,
            0,
            0
        ),
        Exception
    );
}

// "dead" test: attempt to do something with dead bacterium
template<typename Func>
static void deadTest(
    Implementation::Model* model,
    Func model_method
) {
    model->kill(0, 0);
    checkModelMethodForThrow(
        model,
        model_method,
        0,
        0
    );
}

template<typename Func>
static void checkErrorHandling(
    Implementation::Model* model,
    Func model_method,
    bool dead_test
) {
    // Range errors: test all combinations of
    // "wrong" (outside of correct range) arguments.
    // This solution works for coordinates and non-coordinates
    // methods of Model. (< 0, = 0, > MAX)
    int wrong_args[] = {-1, 0, MIN_WIDTH};
    BOOST_FOREACH (int arg1, wrong_args) {
        BOOST_FOREACH (int arg2, wrong_args) {
            if ((arg1 != 0) || (arg2 != 0)) {
                // (0, 0) is correct
                checkModelMethodForThrow(
                    model,
                    model_method,
                    arg1,
                    arg2
                );
            }
        }
    }
    if (dead_test) {
        // "dead" error
        // (attempt to do something with dead bacterium)
        deadTest(model, model_method);
    }
}

static Abstract::Point createInBaseCoordinates(
    Implementation::Model* model
) {
    Abstract::Point coordinates(0, 0);
    model->createNewByCoordinates(
        coordinates,
        DEFAULT_MASS,
        0,
        0,
        0
    );
    return coordinates;
}

static Implementation::Model* createBaseModel(
    int bacteria = 0,
    int teams = 1
) {
    Implementation::Model* model =
        Abstract::makeModel<Implementation::Model>(
            MIN_WIDTH,
            MIN_HEIGHT,
            bacteria,
            teams
        );
    return model;
}

BOOST_AUTO_TEST_CASE (get_team_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    int team = model->getTeamByCoordinates(coordinates);
    BOOST_REQUIRE(team == 0);
    checkErrorHandling<IntOneArgMethod>(
        model,
        &Implementation::Model::getTeamByCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (width_test) {
    Implementation::Model* model = createBaseModel();
    BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
    delete model;
}

BOOST_AUTO_TEST_CASE (height_test) {
    Implementation::Model* model = createBaseModel();
    BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
    delete model;
}

BOOST_AUTO_TEST_CASE (bacteria_number_test) {
    Implementation::Model* model = createBaseModel();
    int bacteria_number = model->getBacteriaNumber(0);
    BOOST_REQUIRE(bacteria_number == 0);
    createInBaseCoordinates(model);
    bacteria_number = model->getBacteriaNumber(0);
    BOOST_REQUIRE(bacteria_number == 1);
    // range errors
    BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
    BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
    delete model;
}

BOOST_AUTO_TEST_CASE (is_alive_test) {
    Implementation::Model* model = createBaseModel(1, 1);
    checkErrorHandling(
        model,
        &Implementation::Model::isAlive,
        false
    );
    BOOST_REQUIRE(model->isAlive(0, 0) == true);
    model->kill(0, 0);
    BOOST_REQUIRE(model->isAlive(0, 0) == false);
    delete model;
}

BOOST_AUTO_TEST_CASE (get_instruction_test) {
    Implementation::Model* model = createBaseModel(1, 1);
    int instruction = model->getInstruction(0, 0);
    BOOST_REQUIRE(instruction == 0);
    checkErrorHandling(
        model,
        &Implementation::Model::getInstruction,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (get_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    Abstract::Point derived_coordinates = model->getCoordinates(0, 0);
    BOOST_REQUIRE(derived_coordinates == coordinates);
    checkErrorHandling(
        model,
        &Implementation::Model::getCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (get_direction_test) {
    Implementation::Model* model = createBaseModel();
    createInBaseCoordinates(model);
    int direction = model->getDirection(0, 0);
    BOOST_REQUIRE(direction == Abstract::LEFT);
    checkErrorHandling(
        model,
        &Implementation::Model::getDirection,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (get_mass_test) {
    Implementation::Model* model = createBaseModel(1, 1);
    int mass = model->getMass(0, 0);
    BOOST_REQUIRE(mass == DEFAULT_MASS);
    checkErrorHandling(
        model,
        &Implementation::Model::getMass,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (kill_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    model->kill(0, 0);
    Abstract::CellState state = model->cellState(coordinates);
    BOOST_REQUIRE(state == Abstract::EMPTY);
    BOOST_REQUIRE(model->isAlive(0, 0) == false);
    // error handling checks
    createInBaseCoordinates(model);
    model->clearBeforeMove(0);
    checkErrorHandling(
        model,
        &Implementation::Model::kill,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    model->killByCoordinates(coordinates);
    Abstract::CellState state = model->cellState(coordinates);
    BOOST_REQUIRE(state == Abstract::EMPTY);
    BOOST_REQUIRE(model->isAlive(0, 0) == false);
    // error handling checks
    createInBaseCoordinates(model);
    model->clearBeforeMove(0);
    checkErrorHandling<OneArgMethod>(
        model,
        &Implementation::Model::killByCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    int test_val = 1;
    model->changeMassByCoordinates(coordinates, test_val);
    int new_mass = model->getMassByCoordinates(coordinates);
    BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));
    model->changeMassByCoordinates(coordinates, -test_val);
    new_mass = model->getMassByCoordinates(coordinates);
    BOOST_REQUIRE(new_mass == DEFAULT_MASS);
    checkErrorHandling<TwoArgsMethod>(
        model,
        &Implementation::Model::changeMassByCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (create_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    Abstract::CellState state = model->cellState(coordinates);
    BOOST_REQUIRE(state == Abstract::BACTERIUM);
    checkErrorHandling<MultiArgsMethod>(
        model,
        &Implementation::Model::createNewByCoordinates,
        false
    );
    delete model;
}
<commit_msg>Implement checkModelMethodForThrow <OneArgMethod2><commit_after>/*
 * bacteria-core, core for cellular automaton
 * Copyright (C) 2016 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>

#include "Model.hpp"

typedef int (Implementation::Model::*IntOneArgMethod) (
    const Abstract::Point& coordinates
) const;

typedef Abstract::CellState (Implementation::Model::*OneArgMethod2) (
    const Abstract::Point& coordinates
) const;

typedef void (Implementation::Model::*OneArgMethod) (
    const Abstract::Point& coordinates
);

typedef void (Implementation::Model::*TwoArgsMethod) (
    const Abstract::Point& coordinates,
    int change
);

typedef void (Implementation::Model::*IntThreeArgsMethod) (
    int team,
    int bacterium_index,
    int spec
);

typedef void (Implementation::Model::*ThreeArgsMethod) (
    int team,
    int bacterium_index,
    const Abstract::Point& coordinates
);

typedef void (Implementation::Model::*MultiArgsMethod) (
    const Abstract::Point& coordinates,
    int mass,
    int direction,
    int team,
    int instruction
);

template<typename Func>
static void checkOneArgMethod(
    Implementation::Model* model,
    Func model_method,
    int arg1,
    int arg2
) {
    Abstract::Point coordinates(arg1, arg2);
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(coordinates), Exception
    );
}

template<typename Func>
void checkModelMethodForThrow(
    Implementation::Model* model,
    Func model_method,
    int arg1,
    int arg2
) {
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(arg1, arg2), Exception
    );
}

template<>
void checkModelMethodForThrow<IntOneArgMethod>(
    Implementation::Model* model,
    IntOneArgMethod model_method,
    int arg1,
    int arg2
) {
    checkOneArgMethod(model, model_method, arg1, arg2);
}

template<>
void checkModelMethodForThrow<OneArgMethod2>(
    Implementation::Model* model,
    OneArgMethod2 model_method,
    int arg1,
    int arg2
) {
    checkOneArgMethod(model, model_method, arg1, arg2);
}

template<>
void checkModelMethodForThrow<OneArgMethod>(
    Implementation::Model* model,
    OneArgMethod model_method,
    int arg1,
    int arg2
) {
    checkOneArgMethod(model, model_method, arg1, arg2);
}

template<>
void checkModelMethodForThrow<TwoArgsMethod>(
    Implementation::Model* model,
    TwoArgsMethod model_method,
    int arg1,
    int arg2
) {
    Abstract::Point coordinates(arg1, arg2);
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(coordinates, 0), Exception
    );
}

template<>
void checkModelMethodForThrow<MultiArgsMethod>(
    Implementation::Model* model,
    MultiArgsMethod model_method,
    int arg1,
    int arg2
) {
    Abstract::Point coordinates(arg1, arg2);
    BOOST_REQUIRE_THROW(
        ((*model).*model_method)(
            coordinates,
            DEFAULT_MASS,
            0,
            0,
            0
        ),
        Exception
    );
}

// "dead" test: attempt to do something with dead bacterium
template<typename Func>
static void deadTest(
    Implementation::Model* model,
    Func model_method
) {
    model->kill(0, 0);
    checkModelMethodForThrow(
        model,
        model_method,
        0,
        0
    );
}

template<typename Func>
static void checkErrorHandling(
    Implementation::Model* model,
    Func model_method,
    bool dead_test
) {
    // Range errors: test all combinations of
    // "wrong" (outside of correct range) arguments.
    // This solution works for coordinates and non-coordinates
    // methods of Model. (< 0, = 0, > MAX)
    int wrong_args[] = {-1, 0, MIN_WIDTH};
    BOOST_FOREACH (int arg1, wrong_args) {
        BOOST_FOREACH (int arg2, wrong_args) {
            if ((arg1 != 0) || (arg2 != 0)) {
                // (0, 0) is correct
                checkModelMethodForThrow(
                    model,
                    model_method,
                    arg1,
                    arg2
                );
            }
        }
    }
    if (dead_test) {
        // "dead" error
        // (attempt to do something with dead bacterium)
        deadTest(model, model_method);
    }
}

static Abstract::Point createInBaseCoordinates(
    Implementation::Model* model
) {
    Abstract::Point coordinates(0, 0);
    model->createNewByCoordinates(
        coordinates,
        DEFAULT_MASS,
        0,
        0,
        0
    );
    return coordinates;
}

static Implementation::Model* createBaseModel(
    int bacteria = 0,
    int teams = 1
) {
    Implementation::Model* model =
        Abstract::makeModel<Implementation::Model>(
            MIN_WIDTH,
            MIN_HEIGHT,
            bacteria,
            teams
        );
    return model;
}

BOOST_AUTO_TEST_CASE (get_team_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    int team = model->getTeamByCoordinates(coordinates);
    BOOST_REQUIRE(team == 0);
    checkErrorHandling<IntOneArgMethod>(
        model,
        &Implementation::Model::getTeamByCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (width_test) {
    Implementation::Model* model = createBaseModel();
    BOOST_REQUIRE(model->getWidth() == MIN_WIDTH);
    delete model;
}

BOOST_AUTO_TEST_CASE (height_test) {
    Implementation::Model* model = createBaseModel();
    BOOST_REQUIRE(model->getHeight() == MIN_HEIGHT);
    delete model;
}

BOOST_AUTO_TEST_CASE (bacteria_number_test) {
    Implementation::Model* model = createBaseModel();
    int bacteria_number = model->getBacteriaNumber(0);
    BOOST_REQUIRE(bacteria_number == 0);
    createInBaseCoordinates(model);
    bacteria_number = model->getBacteriaNumber(0);
    BOOST_REQUIRE(bacteria_number == 1);
    // range errors
    BOOST_REQUIRE_THROW(model->getBacteriaNumber(-1), Exception);
    BOOST_REQUIRE_THROW(model->getBacteriaNumber(1), Exception);
    delete model;
}

BOOST_AUTO_TEST_CASE (is_alive_test) {
    Implementation::Model* model = createBaseModel(1, 1);
    checkErrorHandling(
        model,
        &Implementation::Model::isAlive,
        false
    );
    BOOST_REQUIRE(model->isAlive(0, 0) == true);
    model->kill(0, 0);
    BOOST_REQUIRE(model->isAlive(0, 0) == false);
    delete model;
}

BOOST_AUTO_TEST_CASE (get_instruction_test) {
    Implementation::Model* model = createBaseModel(1, 1);
    int instruction = model->getInstruction(0, 0);
    BOOST_REQUIRE(instruction == 0);
    checkErrorHandling(
        model,
        &Implementation::Model::getInstruction,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (get_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    Abstract::Point derived_coordinates = model->getCoordinates(0, 0);
    BOOST_REQUIRE(derived_coordinates == coordinates);
    checkErrorHandling(
        model,
        &Implementation::Model::getCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (get_direction_test) {
    Implementation::Model* model = createBaseModel();
    createInBaseCoordinates(model);
    int direction = model->getDirection(0, 0);
    BOOST_REQUIRE(direction == Abstract::LEFT);
    checkErrorHandling(
        model,
        &Implementation::Model::getDirection,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (get_mass_test) {
    Implementation::Model* model = createBaseModel(1, 1);
    int mass = model->getMass(0, 0);
    BOOST_REQUIRE(mass == DEFAULT_MASS);
    checkErrorHandling(
        model,
        &Implementation::Model::getMass,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (kill_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    model->kill(0, 0);
    Abstract::CellState state = model->cellState(coordinates);
    BOOST_REQUIRE(state == Abstract::EMPTY);
    BOOST_REQUIRE(model->isAlive(0, 0) == false);
    // error handling checks
    createInBaseCoordinates(model);
    model->clearBeforeMove(0);
    checkErrorHandling(
        model,
        &Implementation::Model::kill,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (kill_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    model->killByCoordinates(coordinates);
    Abstract::CellState state = model->cellState(coordinates);
    BOOST_REQUIRE(state == Abstract::EMPTY);
    BOOST_REQUIRE(model->isAlive(0, 0) == false);
    // error handling checks
    createInBaseCoordinates(model);
    model->clearBeforeMove(0);
    checkErrorHandling<OneArgMethod>(
        model,
        &Implementation::Model::killByCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (change_mass_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    int test_val = 1;
    model->changeMassByCoordinates(coordinates, test_val);
    int new_mass = model->getMassByCoordinates(coordinates);
    BOOST_REQUIRE(new_mass == (DEFAULT_MASS + test_val));
    model->changeMassByCoordinates(coordinates, -test_val);
    new_mass = model->getMassByCoordinates(coordinates);
    BOOST_REQUIRE(new_mass == DEFAULT_MASS);
    checkErrorHandling<TwoArgsMethod>(
        model,
        &Implementation::Model::changeMassByCoordinates,
        true
    );
    delete model;
}

BOOST_AUTO_TEST_CASE (create_coordinates_test) {
    Implementation::Model* model = createBaseModel();
    Abstract::Point coordinates = createInBaseCoordinates(model);
    Abstract::CellState state = model->cellState(coordinates);
    BOOST_REQUIRE(state == Abstract::BACTERIUM);
    checkErrorHandling<MultiArgsMethod>(
        model,
        &Implementation::Model::createNewByCoordinates,
        false
    );
    delete model;
}
<|endoftext|>