<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "mojo/public/cpp/utility/run_loop.h"

#include <assert.h>

#include <algorithm>
#include <vector>

#include "mojo/public/cpp/utility/lib/thread_local.h"
#include "mojo/public/cpp/utility/run_loop_handler.h"

namespace mojo {
namespace {

internal::ThreadLocalPointer<RunLoop> current_run_loop;

const MojoTimeTicks kInvalidTimeTicks = static_cast<MojoTimeTicks>(0);

}  // namespace

// State needed for one iteration of WaitMany().
struct RunLoop::WaitState {
  WaitState() : deadline(MOJO_DEADLINE_INDEFINITE) {}

  std::vector<Handle> handles;
  std::vector<MojoWaitFlags> wait_flags;
  MojoDeadline deadline;
};

struct RunLoop::RunState {
  RunState() : should_quit(false) {}

  bool should_quit;
};

RunLoop::RunLoop() : run_state_(NULL), next_handler_id_(0) {
  assert(!current());
  current_run_loop.Set(this);
}

RunLoop::~RunLoop() {
  assert(current() == this);
  current_run_loop.Set(NULL);
}

// static
void RunLoop::SetUp() {
  current_run_loop.Allocate();
}

// static
void RunLoop::TearDown() {
  assert(!current());
  current_run_loop.Free();
}

// static
RunLoop* RunLoop::current() {
  return current_run_loop.Get();
}

void RunLoop::AddHandler(RunLoopHandler* handler,
                         const Handle& handle,
                         MojoWaitFlags wait_flags,
                         MojoDeadline deadline) {
  assert(current() == this);
  assert(handler);
  assert(handle.is_valid());
  // Assume it's an error if someone tries to reregister an existing handle.
  assert(0u == handler_data_.count(handle));
  HandlerData handler_data;
  handler_data.handler = handler;
  handler_data.wait_flags = wait_flags;
  handler_data.deadline = (deadline == MOJO_DEADLINE_INDEFINITE) ?
      kInvalidTimeTicks :
      GetTimeTicksNow() + static_cast<MojoTimeTicks>(deadline);
  handler_data.id = next_handler_id_++;
  handler_data_[handle] = handler_data;
}

void RunLoop::RemoveHandler(const Handle& handle) {
  assert(current() == this);
  handler_data_.erase(handle);
}

bool RunLoop::HasHandler(const Handle& handle) const {
  return handler_data_.find(handle) != handler_data_.end();
}

void RunLoop::Run() {
  assert(current() == this);
  RunState* old_state = run_state_;
  RunState run_state;
  run_state_ = &run_state;
  while (!run_state.should_quit)
    Wait(false);
  run_state_ = old_state;
}

void RunLoop::RunUntilIdle() {
  assert(current() == this);
  RunState* old_state = run_state_;
  RunState run_state;
  run_state_ = &run_state;
  while (!run_state.should_quit) {
    if (!Wait(true))
      break;
  }
  run_state_ = old_state;
}

void RunLoop::Quit() {
  assert(current() == this);
  if (run_state_)
    run_state_->should_quit = true;
}

bool RunLoop::Wait(bool non_blocking) {
  const WaitState wait_state = GetWaitState(non_blocking);
  if (wait_state.handles.empty()) {
    Quit();
    return false;
  }

  const MojoResult result =
      WaitMany(wait_state.handles, wait_state.wait_flags, wait_state.deadline);
  if (result >= 0) {
    const size_t index = static_cast<size_t>(result);
    assert(handler_data_.find(wait_state.handles[index]) !=
           handler_data_.end());
    handler_data_[wait_state.handles[index]].handler->OnHandleReady(
        wait_state.handles[index]);
    return true;
  }

  switch (result) {
    case MOJO_RESULT_INVALID_ARGUMENT:
    case MOJO_RESULT_FAILED_PRECONDITION:
      return RemoveFirstInvalidHandle(wait_state);
    case MOJO_RESULT_DEADLINE_EXCEEDED:
      return NotifyDeadlineExceeded();
  }

  assert(false);
  return false;
}

bool RunLoop::NotifyDeadlineExceeded() {
  bool notified = false;

  // Make a copy in case someone tries to add/remove new handlers as part of
  // notifying.
  //
  // TODO(darin): This does not protect against removal of handlers! After a
  // call to OnHandleError, |cloned_handlers| could contain an invalid pointer
  // to a RunLoopHandler! See http://crbug.com/384578.
  //
  const HandleToHandlerData cloned_handlers(handler_data_);
  const MojoTimeTicks now(GetTimeTicksNow());
  for (HandleToHandlerData::const_iterator i = cloned_handlers.begin();
       i != cloned_handlers.end(); ++i) {
    // Since we're iterating over a clone of the handlers, verify the handler is
    // still valid before notifying.
    if (i->second.deadline != kInvalidTimeTicks &&
        i->second.deadline < now &&
        handler_data_.find(i->first) != handler_data_.end() &&
        handler_data_[i->first].id == i->second.id) {
      handler_data_.erase(i->first);
      i->second.handler->OnHandleError(i->first, MOJO_RESULT_DEADLINE_EXCEEDED);
      notified = true;
    }
  }

  return notified;
}

bool RunLoop::RemoveFirstInvalidHandle(const WaitState& wait_state) {
  for (size_t i = 0; i < wait_state.handles.size(); ++i) {
    const MojoResult result =
        mojo::Wait(wait_state.handles[i], wait_state.wait_flags[i],
                   static_cast<MojoDeadline>(0));
    if (result == MOJO_RESULT_INVALID_ARGUMENT ||
        result == MOJO_RESULT_FAILED_PRECONDITION) {
      // Remove the handle first, this way if OnHandleError() tries to remove
      // the handle our iterator isn't invalidated.
      assert(handler_data_.find(wait_state.handles[i]) != handler_data_.end());
      RunLoopHandler* handler =
          handler_data_[wait_state.handles[i]].handler;
      handler_data_.erase(wait_state.handles[i]);
      handler->OnHandleError(wait_state.handles[i], result);
      return true;
    }
    assert(MOJO_RESULT_DEADLINE_EXCEEDED == result);
  }
  return false;
}

RunLoop::WaitState RunLoop::GetWaitState(bool non_blocking) const {
  WaitState wait_state;
  MojoTimeTicks min_time = kInvalidTimeTicks;
  for (HandleToHandlerData::const_iterator i = handler_data_.begin();
       i != handler_data_.end(); ++i) {
    wait_state.handles.push_back(i->first);
    wait_state.wait_flags.push_back(i->second.wait_flags);
    if (!non_blocking && i->second.deadline != kInvalidTimeTicks &&
        (min_time == kInvalidTimeTicks || i->second.deadline < min_time)) {
      min_time = i->second.deadline;
    }
  }
  if (non_blocking) {
    wait_state.deadline = static_cast<MojoDeadline>(0);
  } else if (min_time != kInvalidTimeTicks) {
    const MojoTimeTicks now = GetTimeTicksNow();
    if (min_time < now)
      wait_state.deadline = static_cast<MojoDeadline>(0);
    else
      wait_state.deadline = static_cast<MojoDeadline>(min_time - now);
  }
  return wait_state;
}

}  // namespace mojo
<commit_msg>Mojo: Remove bogus TODO(darin) comment.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "mojo/public/cpp/utility/run_loop.h"

#include <assert.h>

#include <algorithm>
#include <vector>

#include "mojo/public/cpp/utility/lib/thread_local.h"
#include "mojo/public/cpp/utility/run_loop_handler.h"

namespace mojo {
namespace {

internal::ThreadLocalPointer<RunLoop> current_run_loop;

const MojoTimeTicks kInvalidTimeTicks = static_cast<MojoTimeTicks>(0);

}  // namespace

// State needed for one iteration of WaitMany().
struct RunLoop::WaitState {
  WaitState() : deadline(MOJO_DEADLINE_INDEFINITE) {}

  std::vector<Handle> handles;
  std::vector<MojoWaitFlags> wait_flags;
  MojoDeadline deadline;
};

struct RunLoop::RunState {
  RunState() : should_quit(false) {}

  bool should_quit;
};

RunLoop::RunLoop() : run_state_(NULL), next_handler_id_(0) {
  assert(!current());
  current_run_loop.Set(this);
}

RunLoop::~RunLoop() {
  assert(current() == this);
  current_run_loop.Set(NULL);
}

// static
void RunLoop::SetUp() {
  current_run_loop.Allocate();
}

// static
void RunLoop::TearDown() {
  assert(!current());
  current_run_loop.Free();
}

// static
RunLoop* RunLoop::current() {
  return current_run_loop.Get();
}

void RunLoop::AddHandler(RunLoopHandler* handler,
                         const Handle& handle,
                         MojoWaitFlags wait_flags,
                         MojoDeadline deadline) {
  assert(current() == this);
  assert(handler);
  assert(handle.is_valid());
  // Assume it's an error if someone tries to reregister an existing handle.
  assert(0u == handler_data_.count(handle));
  HandlerData handler_data;
  handler_data.handler = handler;
  handler_data.wait_flags = wait_flags;
  handler_data.deadline = (deadline == MOJO_DEADLINE_INDEFINITE) ?
      kInvalidTimeTicks :
      GetTimeTicksNow() + static_cast<MojoTimeTicks>(deadline);
  handler_data.id = next_handler_id_++;
  handler_data_[handle] = handler_data;
}

void RunLoop::RemoveHandler(const Handle& handle) {
  assert(current() == this);
  handler_data_.erase(handle);
}

bool RunLoop::HasHandler(const Handle& handle) const {
  return handler_data_.find(handle) != handler_data_.end();
}

void RunLoop::Run() {
  assert(current() == this);
  RunState* old_state = run_state_;
  RunState run_state;
  run_state_ = &run_state;
  while (!run_state.should_quit)
    Wait(false);
  run_state_ = old_state;
}

void RunLoop::RunUntilIdle() {
  assert(current() == this);
  RunState* old_state = run_state_;
  RunState run_state;
  run_state_ = &run_state;
  while (!run_state.should_quit) {
    if (!Wait(true))
      break;
  }
  run_state_ = old_state;
}

void RunLoop::Quit() {
  assert(current() == this);
  if (run_state_)
    run_state_->should_quit = true;
}

bool RunLoop::Wait(bool non_blocking) {
  const WaitState wait_state = GetWaitState(non_blocking);
  if (wait_state.handles.empty()) {
    Quit();
    return false;
  }

  const MojoResult result =
      WaitMany(wait_state.handles, wait_state.wait_flags, wait_state.deadline);
  if (result >= 0) {
    const size_t index = static_cast<size_t>(result);
    assert(handler_data_.find(wait_state.handles[index]) !=
           handler_data_.end());
    handler_data_[wait_state.handles[index]].handler->OnHandleReady(
        wait_state.handles[index]);
    return true;
  }

  switch (result) {
    case MOJO_RESULT_INVALID_ARGUMENT:
    case MOJO_RESULT_FAILED_PRECONDITION:
      return RemoveFirstInvalidHandle(wait_state);
    case MOJO_RESULT_DEADLINE_EXCEEDED:
      return NotifyDeadlineExceeded();
  }

  assert(false);
  return false;
}

bool RunLoop::NotifyDeadlineExceeded() {
  bool notified = false;

  // Make a copy in case someone tries to add/remove new handlers as part of
  // notifying.
  const HandleToHandlerData cloned_handlers(handler_data_);
  const MojoTimeTicks now(GetTimeTicksNow());
  for (HandleToHandlerData::const_iterator i = cloned_handlers.begin();
       i != cloned_handlers.end(); ++i) {
    // Since we're iterating over a clone of the handlers, verify the handler is
    // still valid before notifying.
    if (i->second.deadline != kInvalidTimeTicks &&
        i->second.deadline < now &&
        handler_data_.find(i->first) != handler_data_.end() &&
        handler_data_[i->first].id == i->second.id) {
      handler_data_.erase(i->first);
      i->second.handler->OnHandleError(i->first, MOJO_RESULT_DEADLINE_EXCEEDED);
      notified = true;
    }
  }

  return notified;
}

bool RunLoop::RemoveFirstInvalidHandle(const WaitState& wait_state) {
  for (size_t i = 0; i < wait_state.handles.size(); ++i) {
    const MojoResult result =
        mojo::Wait(wait_state.handles[i], wait_state.wait_flags[i],
                   static_cast<MojoDeadline>(0));
    if (result == MOJO_RESULT_INVALID_ARGUMENT ||
        result == MOJO_RESULT_FAILED_PRECONDITION) {
      // Remove the handle first, this way if OnHandleError() tries to remove
      // the handle our iterator isn't invalidated.
      assert(handler_data_.find(wait_state.handles[i]) != handler_data_.end());
      RunLoopHandler* handler =
          handler_data_[wait_state.handles[i]].handler;
      handler_data_.erase(wait_state.handles[i]);
      handler->OnHandleError(wait_state.handles[i], result);
      return true;
    }
    assert(MOJO_RESULT_DEADLINE_EXCEEDED == result);
  }
  return false;
}

RunLoop::WaitState RunLoop::GetWaitState(bool non_blocking) const {
  WaitState wait_state;
  MojoTimeTicks min_time = kInvalidTimeTicks;
  for (HandleToHandlerData::const_iterator i = handler_data_.begin();
       i != handler_data_.end(); ++i) {
    wait_state.handles.push_back(i->first);
    wait_state.wait_flags.push_back(i->second.wait_flags);
    if (!non_blocking && i->second.deadline != kInvalidTimeTicks &&
        (min_time == kInvalidTimeTicks || i->second.deadline < min_time)) {
      min_time = i->second.deadline;
    }
  }
  if (non_blocking) {
    wait_state.deadline = static_cast<MojoDeadline>(0);
  } else if (min_time != kInvalidTimeTicks) {
    const MojoTimeTicks now = GetTimeTicksNow();
    if (min_time < now)
      wait_state.deadline = static_cast<MojoDeadline>(0);
    else
      wait_state.deadline = static_cast<MojoDeadline>(min_time - now);
  }
  return wait_state;
}

}  // namespace mojo
<|endoftext|>


<commit_before>#include "service.h"

using namespace std;

//operator overloading functions for scientistSort. TODO REMOVE?? geyma bara age?
bool sortByAgeAsc (const Scientist &a, const Scientist &b) { return a.getAge()    <  b.getAge();    }
bool sortByAgeDesc(const Scientist &a, const Scientist &b) { return a.getAge()    >  b.getAge();    }

service::service()
{
     _scientists = _data.loadScientists();
}

// ---------------------------------- SCIENTIST FUNCTIONS ---------------------------------- //

vector<Scientist> service::getScientists()
{   // Returns the list of scientists from file.

    return _scientists;
}

bool service::addScientist(string name, char gender, int birth, int death)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesScientistExist(name) == false)
    {
        Scientist scientist(name, gender, birth, death);

        _scientists.push_back(scientist);
        _data.saveScientist(scientist);
        return true;
    }

    return false;

}
bool service::updateScientist(string name, char gender, int birth, int death)
{   // Updates a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesScientistExist(name) == true)
    {
        Scientist scientist(name, gender, birth, death);

        _scientists.push_back(scientist);
        _data.updateScientist(scientist);
        return true;
    }

    return false;

}

bool service::removeScientist(string name)
{   // Removes a scientist with that name from the vector. Case insensitive.
    // Returns true if removing succeded, false otherwise.

    vector<Scientist> scientistsToRemove = findScientist(1, name);

    if (scientistsToRemove.size() > 0)
    {
        for (size_t i = 0; i < scientistsToRemove.size(); i++)
        {
            Scientist toRemove = scientistsToRemove.at(i);

            _scientists.erase(remove(_scientists.begin(), _scientists.end(), toRemove), _scientists.end());
        }

        _data.removeScientist(name);

        return true;
    }

    return false;
}
void service::removeAllScientists()
{   // Removes ALL scientists from the list. Be careful with this.

    _scientists.clear();

    _data.removeAllScientists();
}

vector<Scientist> service::scientistSort(int sortType)
{    // Sort by sortType: 1 = name(A-Z), 2 = name(Z-A), 3 = gender (f-m), 4 = gender (m-f),
     // 5 = birth year(0-9), 6 = birth year(9-0) 7 = death year(0-9), 8 = death year(0-9), 9 = age(0-9), 10 = age(9-0)

    vector<Scientist> scientists = _scientists;

    if(sortType == 9)
    {
        sort(scientists.begin(), scientists.end(), sortByAgeAsc);
    }
    else if(sortType == 10)
    {
        sort(scientists.begin(), scientists.end(), sortByAgeDesc);
    }
    else
    {
        scientists = _data.sortScientists(sortType);
    }
    return scientists;
}

vector<Scientist> service::findScientist(int findType, string parameter)       // Search vector by type
{   // Returns all scientists whos name includes the string entered. Case insensitive.

    vector<Scientist> scientists;

    if(findType == 7)
    {
        for(unsigned int i = 0; i < _scientists.size(); i++)
        {

            if(_scientists[i].getAge() == stoi(parameter))
            {
                scientists.push_back(_scientists[i]);
            }
        }
    }
    else
    {
        scientists = _data.loadScientists(findType, parameter);
    }

    return scientists;
}
vector<Scientist> service::findScientist(int findType, string parameter1, string parameter2)       // Search vector by type
{   // Returns all scientists whos name includes the string entered. Case insensitive.

    vector<Scientist> scientists;

    if(findType == 8)
    {
        if(stoi(parameter1) > stoi(parameter2))
        {
            string temp = parameter1;
            parameter1 = parameter2;
            parameter2 = temp;
        }
        for(unsigned int i = 0; i < _scientists.size(); i++)
        {

            if((_scientists[i].getAge() >= stoi(parameter1)) && (_scientists[i].getAge() <= stoi(parameter2)))
            {
                scientists.push_back(_scientists[i]);
            }
        }
    }
    else
    {
        scientists = _data.loadScientists(findType, parameter1, parameter2);
    }

    return scientists;
}

bool service::doesScientistExist(string name)
{
    return _data.doesScientistExist(name);
}

// ---------------------------------- COMPUTER FUNCTIONS ---------------------------------- //

vector<Computer> service::getComputers()
{
    vector<Computer> computers;

    computers = _data.loadComputers();

    return computers;
}

bool service::addComputer(string name, int year, string type, bool built)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesComputerExist(name) == false)
    {
        Computer computer(name, year, type, built);

        _computers.push_back(computer);
        _data.saveComputer(computer);
        return true;
    }

    return false;

}
bool service::updateComputer(string name, int year, string type, bool built)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesComputerExist(name) == true)
    {
        Computer computer(name, year, type, built);

        _computers.push_back(computer);
        _data.updateComputer(computer);
        return true;
    }

    return false;

}

bool service::removeComputer(string name)
{
    _data.removeComputer(name);
    return true;
}
void service::removeAllComputers()
{
    _data.removeAllComputers();
}

vector<Computer> service::computerSort(int sortType)
{    // Sort by sortType: 1 = name(A-Z), 2 = name(Z-A), 3 = gender (f-m), 4 = gender (m-f),
     // 5 = birth year(0-9), 6 = birth year(9-0) 7 = death year(0-9), 8 = age(0-9), 9 = age(9-0)

    vector<Computer> computers;

    computers = _data.sortComputers(sortType);

    return computers;

}

vector<Computer> service::findComputer(int findType, string parameter)       // Search vector by type
{
    vector<Computer> computers;

    computers = _data.loadComputers(findType, parameter);

    return computers;
}
vector<Computer> service::findComputer(int findType, string parameter1, string parameter2)       // Search vector by type
{
    vector<Computer> computers;

    computers = _data.loadComputers(findType, parameter1, parameter2);

    return computers;
}

bool service::doesComputerExist(string name)
{
    return _data.doesComputerExist(name);
}

// ---------------------------------- RELATION FUNCTIONS ---------------------------------- //

vector<Relation> service::getRelations()
{
    vector<Relation> relations;

    relations = _data.loadRelations();

    return relations;
}

bool service::addRelation(string scientist, string computer)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    int year = _data.yearComputerBuilt(computer);

    if(_data.doesRelationExist(scientist, computer))
    {
    }
    else
    {
        Relation relation(scientist, computer, year);

        _relations.push_back(relation);
        _data.saveRelation(relation);

        return true;
    }

    return false;
}

bool service::removeRelation(int removeType, string name)
{
    _data.removeRelation(removeType, name);

    return true;
}

void service::removeAllRelations()
{
    _data.removeAllRelations();
}

vector<Relation> service::relationSort(int sortType)
{

    vector<Relation> relations;

    relations = _data.sortRelations(sortType);

    return relations;

}

vector<Relation> service::findRelation(int findType, string parameter)       // Search vector by type
{
    vector<Relation> relations;

    relations = _data.loadRelations(findType, parameter);

    return relations;
}
vector<Relation> service::findRelation(int findType, string parameter1, string parameter2)       // Search vector by type
{
    vector<Relation> relations;

    relations = _data.loadRelations(findType, parameter1, parameter2);

    return relations;
}

bool service::doesRelationExist(string scientist, string computer)
{
    return _data.doesRelationExist(scientist, computer);
}
<commit_msg>minor fixes<commit_after>#include "service.h"

using namespace std;

bool sortByAgeAsc (const Scientist &a, const Scientist &b) { return a.getAge()    <  b.getAge();    }
bool sortByAgeDesc(const Scientist &a, const Scientist &b) { return a.getAge()    >  b.getAge();    }

service::service()
{
     _scientists = _data.loadScientists();
}

// ---------------------------------- SCIENTIST FUNCTIONS ---------------------------------- //

vector<Scientist> service::getScientists()
{   // Returns the list of scientists from file.

    return _scientists;
}

bool service::addScientist(string name, char gender, int birth, int death)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesScientistExist(name) == false)
    {
        Scientist scientist(name, gender, birth, death);

        _scientists.push_back(scientist);
        _data.saveScientist(scientist);
        return true;
    }

    return false;

}
bool service::updateScientist(string name, char gender, int birth, int death)
{   // Updates a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesScientistExist(name) == true)
    {
        Scientist scientist(name, gender, birth, death);

        _scientists.push_back(scientist);
        _data.updateScientist(scientist);
        return true;
    }

    return false;

}

bool service::removeScientist(string name)
{   // Removes a scientist with that name from the vector. Case insensitive.
    // Returns true if removing succeded, false otherwise.

    vector<Scientist> scientistsToRemove = findScientist(1, name);

    if (scientistsToRemove.size() > 0)
    {
        for (size_t i = 0; i < scientistsToRemove.size(); i++)
        {
            Scientist toRemove = scientistsToRemove.at(i);

            _scientists.erase(remove(_scientists.begin(), _scientists.end(), toRemove), _scientists.end());
        }

        _data.removeScientist(name);

        return true;
    }

    return false;
}
void service::removeAllScientists()
{   // Removes ALL scientists from the list. Be careful with this.

    _scientists.clear();

    _data.removeAllScientists();
}

vector<Scientist> service::scientistSort(int sortType)
{    // Sort by sortType: 1 = name(A-Z), 2 = name(Z-A), 3 = gender (f-m), 4 = gender (m-f),
     // 5 = birth year(0-9), 6 = birth year(9-0) 7 = death year(0-9), 8 = death year(0-9), 9 = age(0-9), 10 = age(9-0)

    vector<Scientist> scientists = _scientists;

    if(sortType == 9)
    {
        sort(scientists.begin(), scientists.end(), sortByAgeAsc);
    }
    else if(sortType == 10)
    {
        sort(scientists.begin(), scientists.end(), sortByAgeDesc);
    }
    else
    {
        scientists = _data.sortScientists(sortType);
    }
    return scientists;
}

vector<Scientist> service::findScientist(int findType, string parameter)       // Search vector by type
{   // Returns all scientists whos name includes the string entered. Case insensitive.

    vector<Scientist> scientists;

    if(findType == 7)
    {
        for(unsigned int i = 0; i < _scientists.size(); i++)
        {

            if(_scientists[i].getAge() == stoi(parameter))
            {
                scientists.push_back(_scientists[i]);
            }
        }
    }
    else
    {
        scientists = _data.loadScientists(findType, parameter);
    }

    return scientists;
}
vector<Scientist> service::findScientist(int findType, string parameter1, string parameter2)       // Search vector by type
{   // Returns all scientists whos name includes the string entered. Case insensitive.

    vector<Scientist> scientists;

    if(findType == 8)
    {
        if(stoi(parameter1) > stoi(parameter2))
        {
            string temp = parameter1;
            parameter1 = parameter2;
            parameter2 = temp;
        }
        for(unsigned int i = 0; i < _scientists.size(); i++)
        {

            if((_scientists[i].getAge() >= stoi(parameter1)) && (_scientists[i].getAge() <= stoi(parameter2)))
            {
                scientists.push_back(_scientists[i]);
            }
        }
    }
    else
    {
        scientists = _data.loadScientists(findType, parameter1, parameter2);
    }

    return scientists;
}

bool service::doesScientistExist(string name)
{
    return _data.doesScientistExist(name);
}

// ---------------------------------- COMPUTER FUNCTIONS ---------------------------------- //

vector<Computer> service::getComputers()
{
    vector<Computer> computers;

    computers = _data.loadComputers();

    return computers;
}

bool service::addComputer(string name, int year, string type, bool built)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesComputerExist(name) == false)
    {
        Computer computer(name, year, type, built);

        _computers.push_back(computer);
        _data.saveComputer(computer);
        return true;
    }

    return false;

}
bool service::updateComputer(string name, int year, string type, bool built)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    if(_data.doesComputerExist(name) == true)
    {
        Computer computer(name, year, type, built);

        _computers.push_back(computer);
        _data.updateComputer(computer);
        return true;
    }

    return false;

}

bool service::removeComputer(string name)
{
    _data.removeComputer(name);
    return true;
}
void service::removeAllComputers()
{
    _data.removeAllComputers();
}

vector<Computer> service::computerSort(int sortType)
{    // Sort by sortType: 1 = name(A-Z), 2 = name(Z-A), 3 = gender (f-m), 4 = gender (m-f),
     // 5 = birth year(0-9), 6 = birth year(9-0) 7 = death year(0-9), 8 = age(0-9), 9 = age(9-0)

    vector<Computer> computers;

    computers = _data.sortComputers(sortType);

    return computers;

}

vector<Computer> service::findComputer(int findType, string parameter)       // Search vector by type
{
    vector<Computer> computers;

    computers = _data.loadComputers(findType, parameter);

    return computers;
}
vector<Computer> service::findComputer(int findType, string parameter1, string parameter2)       // Search vector by type
{
    vector<Computer> computers;

    computers = _data.loadComputers(findType, parameter1, parameter2);

    return computers;
}

bool service::doesComputerExist(string name)
{
    return _data.doesComputerExist(name);
}

// ---------------------------------- RELATION FUNCTIONS ---------------------------------- //

vector<Relation> service::getRelations()
{
    vector<Relation> relations;

    relations = _data.loadRelations();

    return relations;
}

bool service::addRelation(string scientist, string computer)
{   // Adds a scientist to the list and updates the file.
    // Returns true if adding succeded, false otherwise.

    int year = _data.yearComputerBuilt(computer);

    if(_data.doesRelationExist(scientist, computer))
    {
    }
    else
    {
        Relation relation(scientist, computer, year);

        _relations.push_back(relation);
        _data.saveRelation(relation);

        return true;
    }

    return false;
}

bool service::removeRelation(int removeType, string name)
{
    _data.removeRelation(removeType, name);

    return true;
}

void service::removeAllRelations()
{
    _data.removeAllRelations();
}

vector<Relation> service::relationSort(int sortType)
{

    vector<Relation> relations;

    relations = _data.sortRelations(sortType);

    return relations;

}

vector<Relation> service::findRelation(int findType, string parameter)       // Search vector by type
{
    vector<Relation> relations;

    relations = _data.loadRelations(findType, parameter);

    return relations;
}
vector<Relation> service::findRelation(int findType, string parameter1, string parameter2)       // Search vector by type
{
    vector<Relation> relations;

    relations = _data.loadRelations(findType, parameter1, parameter2);

    return relations;
}

bool service::doesRelationExist(string scientist, string computer)
{
    return _data.doesRelationExist(scientist, computer);
}
<|endoftext|>


<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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.

#pragma once

typedef enum
{
    Standard,
    Momad
} SNRMode;

struct Options
{
    // Debug mode
    bool debug = false;
    // Print messages to standard output
    bool print = false;
    // Use subband dedispersion
    bool subbandDedispersion = false;
    // Avoid merging batches of dispersed data into contiguous memory
    bool splitBatchesDedispersion = false;
    // Compact the triggered events in time and DM dimensions
    bool compactResults = false;
    // Threshold for triggering
    float threshold = 0.0f;
    // SNR mode
    SNRMode snrMode;
    // Step size for median of medians (MOMAD mode)
    unsigned int medianStepSize = 5;
    /**
     ** @brief Data dumping mode.
     ** In this mode, all data are dumped to disk. Only intended for debug purpose.
     */
    bool dataDump = false;
};

struct DeviceOptions
{
    // OpenCL synchronized operations
    bool synchronized = false;
    // OpenCL platform ID
    unsigned int platformID = 0;
    // OpenCL device ID
    unsigned int deviceID = 0;
    // OpenCL device name
    std::string deviceName{};
    // Padding of OpenCL devices
    AstroData::paddingConf padding{};
};

struct DataOptions
{
    // Use LOFAR file as input
    bool dataLOFAR = false;
    // Use SIGPROC file as input
    bool dataSIGPROC = false;
    // Use PSRDADA buffer as input
    bool dataPSRDADA = false;
    // SIGPROC streaming mode
    bool streamingMode = false;
    // Size (in bytes) of the SIGPROC file header
    unsigned int headerSizeSIGPROC = 0;
    // Name of the input file
    std::string dataFile{};
    // Basename for the output files
    std::string outputFile{};
    // Name of the file containing the zapped channels
    std::string channelsFile{};
    // Name of the file containing the integration steps
    std::string integrationFile{};
#ifdef HAVE_HDF5
    // Limit the number of batches processed from a LOFAR file
    bool limit = false;
    // Name of the LOFAR header file
    std::string headerFile{};
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    // PSRDADA buffer key
    key_t dadaKey = 0;
#endif // HAVE_PSRDADA
};

struct GeneratorOptions
{
    // Use random numbers in generated data
    bool random = false;
    // Width of random generated pulse
    unsigned int width = 0;
    // DM of random generated pulse
    float DM = 0.0f;
};

struct HostMemory
{
    // Input data when reading a whole input file
    std::vector<std::vector<std::vector<inputDataType> *> *> input;
    // Input data when in streaming mode
    std::vector<std::vector<inputDataType> *> inputStream;
    // Zapped channels
    std::vector<unsigned int> zappedChannels;
    // Integration steps
    std::set<unsigned int> integrationSteps;
    // Map to create synthesized beams
    std::vector<unsigned int> beamMapping;
    // Dispersed data
    std::vector<inputDataType> dispersedData;
    // Subbanded data
    std::vector<outputDataType> subbandedData;
    // Dedispersed data
    std::vector<outputDataType> dedispersedData;
    // Integrated data
    std::vector<outputDataType> integratedData;
    // SNR data (SNR mode)
    std::vector<float> snrData;
    // Index of the sample with highest SNR value (SNR mode)
    std::vector<unsigned int> snrSamples;
    // Value of max sample (MOMAD mode)
    std::vector<outputDataType> maxValues;
    // Index of max sample (MOMAD MODE)
    std::vector<unsigned int> maxIndices;
    // Medians of medians (MOMAD mode)
    std::vector<outputDataType> medianOfMedians;
    // Medians of medians absolute deviation (MOMAD mode)
    std::vector<outputDataType> medianOfMediansAbsoluteDeviation;
    // Shifts single step dedispersion
    std::vector<float> *shiftsSingleStep = nullptr;
    // Shifts step one subbanding dedispersion
    std::vector<float> *shiftsStepOne = nullptr;
    // Shifts step two subbanding dedispersion
    std::vector<float> *shiftsStepTwo = nullptr;
#ifdef HAVE_PSRDADA
    // PSRDADA ring buffer
    dada_hdu_t *ringBuffer = nullptr;
#endif // HAVE_PSRDADA
};

struct HostMemoryDumpFiles
{
    /**
     ** @brief File where to dump subbanded data.
     */
    std::ofstream subbandedData;
    /**
     ** @brief File where to dump dedispersed data.
     */
    std::ofstream dedispersedData;
    /**
     ** @brief File where to dump integrated data.
     */
    std::ofstream integratedData;
    /**
     ** @brief File where to dump SNR data (SNR mode).
     */
    std::ofstream snrData;
    /**
     ** @brief File where to dump max SNR sample indices (SNR mode) data.
     */
    std::ofstream snrSamplesData;
    /**
     ** @brief File where to dump max values (MOMAD mode) data.
     */
    std::ofstream maxValuesData;
    /**
     ** @brief File where to dump max indices (MOMAD mode) data.
     */
    std::ofstream maxIndicesData;
    /**
     ** @brief File where to dump medians of medians (MOMAD mode) data.
     */
    std::ofstream medianOfMediansData;
    /**
     ** @brief File where to dump median of medians absolute deviation (MOMAD mode) data.
     */
    std::ofstream medianOfMediansAbsoluteDeviationData;
};

struct DeviceMemory
{
    // Shifts single step dedispersion
    cl::Buffer shiftsSingleStep;
    // Shifts step one subbanding dedispersion
    cl::Buffer shiftsStepOne;
    // Shifts step two subbanding dedispersion
    cl::Buffer shiftsStepTwo;
    // Zapped channels
    cl::Buffer zappedChannels;
    // Map to create synthesized beams
    cl::Buffer beamMapping;
    // Dispersed dada
    cl::Buffer dispersedData;
    // Subbanded data
    cl::Buffer subbandedData;
    // Dedispersed data
    cl::Buffer dedispersedData;
    // Integrated data
    cl::Buffer integratedData;
    // SNR data (SNR mode)
    cl::Buffer snrData;
    // Index of the sample with highest SNR value (SNR mode)
    cl::Buffer snrSamples;
    // Value of max sample (MOMAD mode)
    cl::Buffer maxValues;
    // Index of max sample (MOMAD mode)
    cl::Buffer maxIndices;
    // Median of medians first step (MOMAD mode)
    cl::Buffer medianOfMediansStepOne;
    // Median of medians second step (MOMAD mode)
    cl::Buffer medianOfMediansStepTwo;
};

struct KernelConfigurations
{
    // Configuration of single step dedispersion kernel
    Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters;
    // Configuration of subband dedispersion kernel, step one
    Dedispersion::tunedDedispersionConf dedispersionStepOneParameters;
    // Configuration of subband dedispersion kernel, step two
    Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters;
    // Configuration of integration kernel
    Integration::tunedIntegrationConf integrationParameters;
    // Configuration of SNR kernel (SNR mode)
    SNR::tunedSNRConf snrParameters;
    // Configuration of max kernel (MOMAD mode)
    SNR::tunedSNRConf maxParameters;
    // Configuration of median of medians first step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepOneParameters;
    // Configuration of median of medians second step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepTwoParameters;
    // Configuration of median of medians absolute deviation (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansAbsoluteDeviationParameters;
};

struct Kernels
{
    // Single step dedispersion kernel
    cl::Kernel *dedispersionSingleStep = nullptr;
    // Step one subbanding dedispersion kernel
    cl::Kernel *dedispersionStepOne = nullptr;
    // Step two subbanding dedispersion kernel
    cl::Kernel *dedispersionStepTwo = nullptr;
    // Integration kernels, one for each integration step
    std::vector<cl::Kernel *> integration;
    // SNR kernels, one for the original data and one for each integration step (SNR mode)
    std::vector<cl::Kernel *> snr;
    // Max kernels, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> max;
    // Median of medians first step, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansStepOne;
    // Median of medians second step, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansStepTwo;
    // Median of medians absolute deviation, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansAbsoluteDeviation;
};

struct KernelRunTimeConfigurations
{
    // Global NDrange for single step dedispersion
    cl::NDRange dedispersionSingleStepGlobal;
    // Local NDRange for single step dedispersion
    cl::NDRange dedispersionSingleStepLocal;
    // Global NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneGlobal;
    // Local NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneLocal;
    // Global NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoGlobal;
    // Local NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoLocal;
    // Global NDRange for integration
    std::vector<cl::NDRange> integrationGlobal;
    // Local NDRange for integration
    std::vector<cl::NDRange> integrationLocal;
    // Global NDRange for SNR (SNR mode)
    std::vector<cl::NDRange> snrGlobal;
    // Local NDRange for SNR (SNR mode)
    std::vector<cl::NDRange> snrLocal;
    // Global NDRange for max (MOMAD mode)
    std::vector<cl::NDRange> maxGlobal;
    // Local NDRange for max (MOMAD mode)
    std::vector<cl::NDRange> maxLocal;
    // Global NDRange for median of medians first step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepOneGlobal;
    // Local NDRange for median of medians first step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepOneLocal;
    // Global NDRange for median of medians second step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepTwoGlobal;
    // Local NDRange for median of medians second step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepTwoLocal;
    // Global NDRange for median of medians absolute deviation (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationGlobal;
    // Local NDRange for median of medians absolute deviation (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationLocal;
};

struct Timers
{
    isa::utils::Timer inputLoad;
    isa::utils::Timer search;
    isa::utils::Timer inputHandling;
    isa::utils::Timer inputCopy;
    isa::utils::Timer dedispersionSingleStep;
    isa::utils::Timer dedispersionStepOne;
    isa::utils::Timer dedispersionStepTwo;
    isa::utils::Timer integration;
    isa::utils::Timer snr;
    isa::utils::Timer max;
    isa::utils::Timer medianOfMediansStepOne;
    isa::utils::Timer medianOfMediansStepTwo;
    isa::utils::Timer medianOfMediansAbsoluteDeviationStepOne;
    isa::utils::Timer medianOfMediansAbsoluteDeviationStepTwo;
    isa::utils::Timer outputCopy;
    isa::utils::Timer trigger;
};

struct TriggeredEvent
{
    unsigned int beam = 0;
    unsigned int sample = 0;
    unsigned int integration = 0;
    float DM = 0.0f;
    float SNR = 0.0f;
};

struct CompactedEvent : TriggeredEvent
{
    unsigned int compactedIntegration = 1;
    unsigned int compactedDMs = 1;
};

using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>;
using CompactedEvents = std::vector<std::vector<CompactedEvent>>;

struct OpenCLRunTime
{
    cl::Context *context = nullptr;
    std::vector<cl::Platform> *platforms = nullptr;
    std::vector<cl::Device> *devices = nullptr;
    std::vector<std::vector<cl::CommandQueue>> *queues = nullptr;
};
<commit_msg>Adding string to store the prefix for dump files.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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.

#pragma once

typedef enum
{
    Standard,
    Momad
} SNRMode;

struct Options
{
    // Debug mode
    bool debug = false;
    // Print messages to standard output
    bool print = false;
    // Use subband dedispersion
    bool subbandDedispersion = false;
    // Avoid merging batches of dispersed data into contiguous memory
    bool splitBatchesDedispersion = false;
    // Compact the triggered events in time and DM dimensions
    bool compactResults = false;
    // Threshold for triggering
    float threshold = 0.0f;
    // SNR mode
    SNRMode snrMode;
    // Step size for median of medians (MOMAD mode)
    unsigned int medianStepSize = 5;
    /**
     ** @brief Data dumping mode.
     ** In this mode, all data are dumped to disk. Only intended for debug purpose.
     */
    bool dataDump = false;
};

struct DeviceOptions
{
    // OpenCL synchronized operations
    bool synchronized = false;
    // OpenCL platform ID
    unsigned int platformID = 0;
    // OpenCL device ID
    unsigned int deviceID = 0;
    // OpenCL device name
    std::string deviceName{};
    // Padding of OpenCL devices
    AstroData::paddingConf padding{};
};

struct DataOptions
{
    // Use LOFAR file as input
    bool dataLOFAR = false;
    // Use SIGPROC file as input
    bool dataSIGPROC = false;
    // Use PSRDADA buffer as input
    bool dataPSRDADA = false;
    // SIGPROC streaming mode
    bool streamingMode = false;
    // Size (in bytes) of the SIGPROC file header
    unsigned int headerSizeSIGPROC = 0;
    // Name of the input file
    std::string dataFile{};
    // Basename for the output files
    std::string outputFile{};
    // Name of the file containing the zapped channels
    std::string channelsFile{};
    // Name of the file containing the integration steps
    std::string integrationFile{};
#ifdef HAVE_HDF5
    // Limit the number of batches processed from a LOFAR file
    bool limit = false;
    // Name of the LOFAR header file
    std::string headerFile{};
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    // PSRDADA buffer key
    key_t dadaKey = 0;
#endif // HAVE_PSRDADA
};

struct GeneratorOptions
{
    // Use random numbers in generated data
    bool random = false;
    // Width of random generated pulse
    unsigned int width = 0;
    // DM of random generated pulse
    float DM = 0.0f;
};

struct HostMemory
{
    // Input data when reading a whole input file
    std::vector<std::vector<std::vector<inputDataType> *> *> input;
    // Input data when in streaming mode
    std::vector<std::vector<inputDataType> *> inputStream;
    // Zapped channels
    std::vector<unsigned int> zappedChannels;
    // Integration steps
    std::set<unsigned int> integrationSteps;
    // Map to create synthesized beams
    std::vector<unsigned int> beamMapping;
    // Dispersed data
    std::vector<inputDataType> dispersedData;
    // Subbanded data
    std::vector<outputDataType> subbandedData;
    // Dedispersed data
    std::vector<outputDataType> dedispersedData;
    // Integrated data
    std::vector<outputDataType> integratedData;
    // SNR data (SNR mode)
    std::vector<float> snrData;
    // Index of the sample with highest SNR value (SNR mode)
    std::vector<unsigned int> snrSamples;
    // Value of max sample (MOMAD mode)
    std::vector<outputDataType> maxValues;
    // Index of max sample (MOMAD MODE)
    std::vector<unsigned int> maxIndices;
    // Medians of medians (MOMAD mode)
    std::vector<outputDataType> medianOfMedians;
    // Medians of medians absolute deviation (MOMAD mode)
    std::vector<outputDataType> medianOfMediansAbsoluteDeviation;
    // Shifts single step dedispersion
    std::vector<float> *shiftsSingleStep = nullptr;
    // Shifts step one subbanding dedispersion
    std::vector<float> *shiftsStepOne = nullptr;
    // Shifts step two subbanding dedispersion
    std::vector<float> *shiftsStepTwo = nullptr;
#ifdef HAVE_PSRDADA
    // PSRDADA ring buffer
    dada_hdu_t *ringBuffer = nullptr;
#endif // HAVE_PSRDADA
};

struct HostMemoryDumpFiles
{
    /**
     ** @brief Prefix for the dump files.
     */
    std::string dumpFilesPrefix{};
    /**
     ** @brief File where to dump subbanded data.
     */
    std::ofstream subbandedData;
    /**
     ** @brief File where to dump dedispersed data.
     */
    std::ofstream dedispersedData;
    /**
     ** @brief File where to dump integrated data.
     */
    std::ofstream integratedData;
    /**
     ** @brief File where to dump SNR data (SNR mode).
     */
    std::ofstream snrData;
    /**
     ** @brief File where to dump max SNR sample indices (SNR mode) data.
     */
    std::ofstream snrSamplesData;
    /**
     ** @brief File where to dump max values (MOMAD mode) data.
     */
    std::ofstream maxValuesData;
    /**
     ** @brief File where to dump max indices (MOMAD mode) data.
     */
    std::ofstream maxIndicesData;
    /**
     ** @brief File where to dump medians of medians (MOMAD mode) data.
     */
    std::ofstream medianOfMediansData;
    /**
     ** @brief File where to dump median of medians absolute deviation (MOMAD mode) data.
     */
    std::ofstream medianOfMediansAbsoluteDeviationData;
};

struct DeviceMemory
{
    // Shifts single step dedispersion
    cl::Buffer shiftsSingleStep;
    // Shifts step one subbanding dedispersion
    cl::Buffer shiftsStepOne;
    // Shifts step two subbanding dedispersion
    cl::Buffer shiftsStepTwo;
    // Zapped channels
    cl::Buffer zappedChannels;
    // Map to create synthesized beams
    cl::Buffer beamMapping;
    // Dispersed dada
    cl::Buffer dispersedData;
    // Subbanded data
    cl::Buffer subbandedData;
    // Dedispersed data
    cl::Buffer dedispersedData;
    // Integrated data
    cl::Buffer integratedData;
    // SNR data (SNR mode)
    cl::Buffer snrData;
    // Index of the sample with highest SNR value (SNR mode)
    cl::Buffer snrSamples;
    // Value of max sample (MOMAD mode)
    cl::Buffer maxValues;
    // Index of max sample (MOMAD mode)
    cl::Buffer maxIndices;
    // Median of medians first step (MOMAD mode)
    cl::Buffer medianOfMediansStepOne;
    // Median of medians second step (MOMAD mode)
    cl::Buffer medianOfMediansStepTwo;
};

struct KernelConfigurations
{
    // Configuration of single step dedispersion kernel
    Dedispersion::tunedDedispersionConf dedispersionSingleStepParameters;
    // Configuration of subband dedispersion kernel, step one
    Dedispersion::tunedDedispersionConf dedispersionStepOneParameters;
    // Configuration of subband dedispersion kernel, step two
    Dedispersion::tunedDedispersionConf dedispersionStepTwoParameters;
    // Configuration of integration kernel
    Integration::tunedIntegrationConf integrationParameters;
    // Configuration of SNR kernel (SNR mode)
    SNR::tunedSNRConf snrParameters;
    // Configuration of max kernel (MOMAD mode)
    SNR::tunedSNRConf maxParameters;
    // Configuration of median of medians first step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepOneParameters;
    // Configuration of median of medians second step (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansStepTwoParameters;
    // Configuration of median of medians absolute deviation (MOMAD mode)
    SNR::tunedSNRConf medianOfMediansAbsoluteDeviationParameters;
};

struct Kernels
{
    // Single step dedispersion kernel
    cl::Kernel *dedispersionSingleStep = nullptr;
    // Step one subbanding dedispersion kernel
    cl::Kernel *dedispersionStepOne = nullptr;
    // Step two subbanding dedispersion kernel
    cl::Kernel *dedispersionStepTwo = nullptr;
    // Integration kernels, one for each integration step
    std::vector<cl::Kernel *> integration;
    // SNR kernels, one for the original data and one for each integration step (SNR mode)
    std::vector<cl::Kernel *> snr;
    // Max kernels, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> max;
    // Median of medians first step, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansStepOne;
    // Median of medians second step, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansStepTwo;
    // Median of medians absolute deviation, one for the original data and one for each integration step (MOMAD mode)
    std::vector<cl::Kernel *> medianOfMediansAbsoluteDeviation;
};

struct KernelRunTimeConfigurations
{
    // Global NDrange for single step dedispersion
    cl::NDRange dedispersionSingleStepGlobal;
    // Local NDRange for single step dedispersion
    cl::NDRange dedispersionSingleStepLocal;
    // Global NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneGlobal;
    // Local NDRange for subbanding dedispersion step one
    cl::NDRange dedispersionStepOneLocal;
    // Global NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoGlobal;
    // Local NDRange for subbanding dedispersion step two
    cl::NDRange dedispersionStepTwoLocal;
    // Global NDRange for integration
    std::vector<cl::NDRange> integrationGlobal;
    // Local NDRange for integration
    std::vector<cl::NDRange> integrationLocal;
    // Global NDRange for SNR (SNR mode)
    std::vector<cl::NDRange> snrGlobal;
    // Local NDRange for SNR (SNR mode)
    std::vector<cl::NDRange> snrLocal;
    // Global NDRange for max (MOMAD mode)
    std::vector<cl::NDRange> maxGlobal;
    // Local NDRange for max (MOMAD mode)
    std::vector<cl::NDRange> maxLocal;
    // Global NDRange for median of medians first step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepOneGlobal;
    // Local NDRange for median of medians first step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepOneLocal;
    // Global NDRange for median of medians second step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepTwoGlobal;
    // Local NDRange for median of medians second step (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansStepTwoLocal;
    // Global NDRange for median of medians absolute deviation (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationGlobal;
    // Local NDRange for median of medians absolute deviation (MOMAD mode)
    std::vector<cl::NDRange> medianOfMediansAbsoluteDeviationLocal;
};

struct Timers
{
    isa::utils::Timer inputLoad;
    isa::utils::Timer search;
    isa::utils::Timer inputHandling;
    isa::utils::Timer inputCopy;
    isa::utils::Timer dedispersionSingleStep;
    isa::utils::Timer dedispersionStepOne;
    isa::utils::Timer dedispersionStepTwo;
    isa::utils::Timer integration;
    isa::utils::Timer snr;
    isa::utils::Timer max;
    isa::utils::Timer medianOfMediansStepOne;
    isa::utils::Timer medianOfMediansStepTwo;
    isa::utils::Timer medianOfMediansAbsoluteDeviationStepOne;
    isa::utils::Timer medianOfMediansAbsoluteDeviationStepTwo;
    isa::utils::Timer outputCopy;
    isa::utils::Timer trigger;
};

struct TriggeredEvent
{
    unsigned int beam = 0;
    unsigned int sample = 0;
    unsigned int integration = 0;
    float DM = 0.0f;
    float SNR = 0.0f;
};

struct CompactedEvent : TriggeredEvent
{
    unsigned int compactedIntegration = 1;
    unsigned int compactedDMs = 1;
};

using TriggeredEvents = std::vector<std::map<unsigned int, std::vector<TriggeredEvent>>>;
using CompactedEvents = std::vector<std::vector<CompactedEvent>>;

struct OpenCLRunTime
{
    cl::Context *context = nullptr;
    std::vector<cl::Platform> *platforms = nullptr;
    std::vector<cl::Device> *devices = nullptr;
    std::vector<std::vector<cl::CommandQueue>> *queues = nullptr;
};
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <vector>
#include <string>

#include "Nodes.hpp"

namespace eddic {

class MainDeclaration : public ParseNode {
   public:
        MainDeclaration(Context* context) : ParseNode(context) {};

        void write(AssemblyFileWriter& writer);
};

class Function : public ParseNode {
	private:
		std::string m_name;

	public:
		Function(Context* context, const std::string& name) : ParseNode(context), m_name(name) {}

        void write(AssemblyFileWriter& writer);

        std::string name(){
            return m_name;
        }
};

class FunctionCall : public ParseNode {
    private:
        std::string m_function;

    public:
        FunctionCall(Context* context, const std::string& function) : ParseNode(context), m_function(function) {}

        void write(AssemblyFileWriter& writer);
        void checkFunctions(Program& program);
};

} //end of eddic

#endif
<commit_msg>Add parameters to function declarations<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <vector>
#include <string>

#include "Nodes.hpp"

namespace eddic {

class MainDeclaration : public ParseNode {
   public:
        MainDeclaration(Context* context) : ParseNode(context) {};

        void write(AssemblyFileWriter& writer);
};

class Parameter {
    private:
        std::string m_name;
        Type m_type;

    public:
        Parameter(const std::string& name, Type type) : m_name(name), m_type(type) {}
};

class Function : public ParseNode {
	private:
		std::string m_name;
        std::vector<Parameter> m_parameters;

	public:
		Function(Context* context, const std::string& name) : ParseNode(context), m_name(name) {}

        void write(AssemblyFileWriter& writer);

        std::string name(){
            return m_name;
        }

        void addParameter(Parameter parameter){
            m_parameters.push_back(parameter);
        }
};

class FunctionCall : public ParseNode {
    private:
        std::string m_function;

    public:
        FunctionCall(Context* context, const std::string& function) : ParseNode(context), m_function(function) {}

        void write(AssemblyFileWriter& writer);
        void checkFunctions(Program& program);
};

} //end of eddic

#endif
<|endoftext|>


<commit_before>#include "optionsmodel.h"
#include "bitcoinunits.h"
#include <QSettings>

#include "init.h"
#include "walletdb.h"
#include "guiutil.h"

OptionsModel::OptionsModel(QObject *parent) :
    QAbstractListModel(parent)
{
    Init();
}

bool static ApplyProxySettings()
{
    QSettings settings;
    CService addrProxy(settings.value("addrProxy", "127.0.0.1:9050").toString().toStdString());
    int nSocksVersion(settings.value("nSocksVersion", 5).toInt());
    if (!settings.value("fUseProxy", false).toBool()) {
        addrProxy = CService();
        nSocksVersion = 0;
        return false;
    }
    if (nSocksVersion && !addrProxy.IsValid())
        return false;
    if (!IsLimited(NET_IPV4))
        SetProxy(NET_IPV4, addrProxy, nSocksVersion);
    if (nSocksVersion > 4) {
#ifdef USE_IPV6
        if (!IsLimited(NET_IPV6))
            SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
        SetNameProxy(addrProxy, nSocksVersion);
    }
    return true;
}

void OptionsModel::Init()
{
    QSettings settings;

    // These are Qt-only settings:
    nDisplayUnit = settings.value("nDisplayUnit", BitcoinUnits::BTC).toInt();
    bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool();
    fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool();
    fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool();
	fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();
    nTransactionFee = settings.value("nTransactionFee").toLongLong();
    language = settings.value("language", "").toString();

    // These are shared with core Bitcoin; we want
    // command-line options to override the GUI settings:
    if (settings.contains("fUseUPnP"))
        SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool());
    if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool())
        SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString());
    if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool())
        SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString());
    if (settings.contains("detachDB"))
        SoftSetBoolArg("-detachdb", settings.value("detachDB").toBool());
    if (!language.isEmpty())
        SoftSetArg("-lang", language.toStdString());
}

void OptionsModel::Reset()
{
    QSettings settings;

    // Remove all entries in this QSettings object
    settings.clear();

    // default setting for OptionsModel::StartAtStartup - disabled
    if (GUIUtil::GetStartOnSystemStartup())
        GUIUtil::SetStartOnSystemStartup(false);

    // Re-Init to get default values
    Init();

    // Ensure Upgrade() is not running again by setting the bImportFinished flag
    settings.setValue("bImportFinished", true);
}

bool OptionsModel::Upgrade()
{
    QSettings settings;

    if (settings.contains("bImportFinished"))
        return false; // Already upgraded

    settings.setValue("bImportFinished", true);

    // Move settings from old wallet.dat (if any):
    CWalletDB walletdb("wallet.dat");

    QList<QString> intOptions;
    intOptions << "nDisplayUnit" << "nTransactionFee";
    foreach(QString key, intOptions)
    {
        int value = 0;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    QList<QString> boolOptions;
    boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP";
    foreach(QString key, boolOptions)
    {
        bool value = false;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    try
    {
        CAddress addrProxyAddress;
        if (walletdb.ReadSetting("addrProxy", addrProxyAddress))
        {
            settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
    catch (std::ios_base::failure &e)
    {
        // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress
        CService addrProxy;
        if (walletdb.ReadSetting("addrProxy", addrProxy))
        {
            settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
    ApplyProxySettings();
    Init();

    return true;
}

int OptionsModel::rowCount(const QModelIndex & parent) const
{
    return OptionIDRowCount;
}

QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return QVariant(GUIUtil::GetStartOnSystemStartup());
        case MinimizeToTray:
            return QVariant(fMinimizeToTray);
        case MapPortUPnP:
            return settings.value("fUseUPnP", GetBoolArg("-upnp", true));
        case MinimizeOnClose:
            return QVariant(fMinimizeOnClose);
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QVariant(QString::fromStdString(proxy.first.ToStringIP()));
            else
                return QVariant(QString::fromStdString("127.0.0.1"));
        }
        case ProxyPort: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QVariant(proxy.first.GetPort());
            else
                return QVariant(9050);
        }
        case ProxySocksVersion:
            return settings.value("nSocksVersion", 5);
        case Fee:
            return QVariant(nTransactionFee);
        case DisplayUnit:
            return QVariant(nDisplayUnit);
        case DisplayAddresses:
            return QVariant(bDisplayAddresses);
        case DetachDatabases:
            return QVariant(bitdb.GetDetach());
        case Language:
            return settings.value("language", "");
		case CoinControlFeatures:
            return QVariant(fCoinControlFeatures);

        default:
            return QVariant();
        }
    }
    return QVariant();
}

bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    bool successful = true; /* set to false on parse error */
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
            break;
        case MinimizeToTray:
            fMinimizeToTray = value.toBool();
            settings.setValue("fMinimizeToTray", fMinimizeToTray);
            break;
        case MapPortUPnP:
            fUseUPnP = value.toBool();
            settings.setValue("fUseUPnP", fUseUPnP);
            MapPort();
            break;
        case MinimizeOnClose:
            fMinimizeOnClose = value.toBool();
            settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
            break;
        case ProxyUse:
            settings.setValue("fUseProxy", value.toBool());
            ApplyProxySettings();
            break;
        case ProxyIP: {
            proxyType proxy;
            proxy.first = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            CNetAddr addr(value.toString().toStdString());
            proxy.first.SetIP(addr);
            settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case ProxyPort: {
            proxyType proxy;
            proxy.first = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            proxy.first.SetPort(value.toInt());
            settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case ProxySocksVersion: {
            proxyType proxy;
            proxy.second = 5;
            GetProxy(NET_IPV4, proxy);

            proxy.second = value.toInt();
            settings.setValue("nSocksVersion", proxy.second);
            successful = ApplyProxySettings();
        }
        break;
        case Fee:
            nTransactionFee = value.toLongLong();
            settings.setValue("nTransactionFee", nTransactionFee);
			emit transactionFeeChanged(nTransactionFee);
            break;
        case DisplayUnit:
            nDisplayUnit = value.toInt();
            settings.setValue("nDisplayUnit", nDisplayUnit);
            emit displayUnitChanged(nDisplayUnit);
            break;
        case DisplayAddresses:
            bDisplayAddresses = value.toBool();
            settings.setValue("bDisplayAddresses", bDisplayAddresses);
            break;
        case DetachDatabases: {
            bool fDetachDB = value.toBool();
            bitdb.SetDetach(fDetachDB);
            settings.setValue("detachDB", fDetachDB);
            }
            break;
        case Language:
            settings.setValue("language", value);
            break;
		case CoinControlFeatures: {
            fCoinControlFeatures = value.toBool();
            settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
            emit coinControlFeaturesChanged(fCoinControlFeatures);
            }
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}

qint64 OptionsModel::getTransactionFee()
{
    return nTransactionFee;
}

bool OptionsModel::getCoinControlFeatures()
{
     return fCoinControlFeatures;
}

bool OptionsModel::getMinimizeToTray()
{
    return fMinimizeToTray;
}

bool OptionsModel::getMinimizeOnClose()
{
    return fMinimizeOnClose;
}

int OptionsModel::getDisplayUnit()
{
    return nDisplayUnit;
}

bool OptionsModel::getDisplayAddresses()
{
    return bDisplayAddresses;
}
<commit_msg>ifdef USE_UPNP in optionsmodel<commit_after>#include "optionsmodel.h"
#include "bitcoinunits.h"
#include <QSettings>

#include "init.h"
#include "walletdb.h"
#include "guiutil.h"

OptionsModel::OptionsModel(QObject *parent) :
    QAbstractListModel(parent)
{
    Init();
}

bool static ApplyProxySettings()
{
    QSettings settings;
    CService addrProxy(settings.value("addrProxy", "127.0.0.1:9050").toString().toStdString());
    int nSocksVersion(settings.value("nSocksVersion", 5).toInt());
    if (!settings.value("fUseProxy", false).toBool()) {
        addrProxy = CService();
        nSocksVersion = 0;
        return false;
    }
    if (nSocksVersion && !addrProxy.IsValid())
        return false;
    if (!IsLimited(NET_IPV4))
        SetProxy(NET_IPV4, addrProxy, nSocksVersion);
    if (nSocksVersion > 4) {
#ifdef USE_IPV6
        if (!IsLimited(NET_IPV6))
            SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
        SetNameProxy(addrProxy, nSocksVersion);
    }
    return true;
}

void OptionsModel::Init()
{
    QSettings settings;

    // These are Qt-only settings:
    nDisplayUnit = settings.value("nDisplayUnit", BitcoinUnits::BTC).toInt();
    bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool();
    fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool();
    fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool();
	fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();
    nTransactionFee = settings.value("nTransactionFee").toLongLong();
    language = settings.value("language", "").toString();

    // These are shared with core Bitcoin; we want
    // command-line options to override the GUI settings:
    if (settings.contains("fUseUPnP"))
        SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool());
    if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool())
        SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString());
    if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool())
        SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString());
    if (settings.contains("detachDB"))
        SoftSetBoolArg("-detachdb", settings.value("detachDB").toBool());
    if (!language.isEmpty())
        SoftSetArg("-lang", language.toStdString());
}

void OptionsModel::Reset()
{
    QSettings settings;

    // Remove all entries in this QSettings object
    settings.clear();

    // default setting for OptionsModel::StartAtStartup - disabled
    if (GUIUtil::GetStartOnSystemStartup())
        GUIUtil::SetStartOnSystemStartup(false);

    // Re-Init to get default values
    Init();

    // Ensure Upgrade() is not running again by setting the bImportFinished flag
    settings.setValue("bImportFinished", true);
}

bool OptionsModel::Upgrade()
{
    QSettings settings;

    if (settings.contains("bImportFinished"))
        return false; // Already upgraded

    settings.setValue("bImportFinished", true);

    // Move settings from old wallet.dat (if any):
    CWalletDB walletdb("wallet.dat");

    QList<QString> intOptions;
    intOptions << "nDisplayUnit" << "nTransactionFee";
    foreach(QString key, intOptions)
    {
        int value = 0;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    QList<QString> boolOptions;
    boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP";
    foreach(QString key, boolOptions)
    {
        bool value = false;
        if (walletdb.ReadSetting(key.toStdString(), value))
        {
            settings.setValue(key, value);
            walletdb.EraseSetting(key.toStdString());
        }
    }
    try
    {
        CAddress addrProxyAddress;
        if (walletdb.ReadSetting("addrProxy", addrProxyAddress))
        {
            settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
    catch (std::ios_base::failure &e)
    {
        // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress
        CService addrProxy;
        if (walletdb.ReadSetting("addrProxy", addrProxy))
        {
            settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str());
            walletdb.EraseSetting("addrProxy");
        }
    }
    ApplyProxySettings();
    Init();

    return true;
}

int OptionsModel::rowCount(const QModelIndex & parent) const
{
    return OptionIDRowCount;
}

QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return QVariant(GUIUtil::GetStartOnSystemStartup());
        case MinimizeToTray:
            return QVariant(fMinimizeToTray);
        case MapPortUPnP:
#ifdef USE_UPNP
            return settings.value("fUseUPnP", GetBoolArg("-upnp", true));
#else
            return QVariant(false);
#endif
        case MinimizeOnClose:
            return QVariant(fMinimizeOnClose);
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QVariant(QString::fromStdString(proxy.first.ToStringIP()));
            else
                return QVariant(QString::fromStdString("127.0.0.1"));
        }
        case ProxyPort: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QVariant(proxy.first.GetPort());
            else
                return QVariant(9050);
        }
        case ProxySocksVersion:
            return settings.value("nSocksVersion", 5);
        case Fee:
            return QVariant(nTransactionFee);
        case DisplayUnit:
            return QVariant(nDisplayUnit);
        case DisplayAddresses:
            return QVariant(bDisplayAddresses);
        case DetachDatabases:
            return QVariant(bitdb.GetDetach());
        case Language:
            return settings.value("language", "");
		case CoinControlFeatures:
            return QVariant(fCoinControlFeatures);

        default:
            return QVariant();
        }
    }
    return QVariant();
}

bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    bool successful = true; /* set to false on parse error */
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
            break;
        case MinimizeToTray:
            fMinimizeToTray = value.toBool();
            settings.setValue("fMinimizeToTray", fMinimizeToTray);
            break;
        case MapPortUPnP:
            fUseUPnP = value.toBool();
            settings.setValue("fUseUPnP", fUseUPnP);
            MapPort();
            break;
        case MinimizeOnClose:
            fMinimizeOnClose = value.toBool();
            settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
            break;
        case ProxyUse:
            settings.setValue("fUseProxy", value.toBool());
            ApplyProxySettings();
            break;
        case ProxyIP: {
            proxyType proxy;
            proxy.first = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            CNetAddr addr(value.toString().toStdString());
            proxy.first.SetIP(addr);
            settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case ProxyPort: {
            proxyType proxy;
            proxy.first = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            proxy.first.SetPort(value.toInt());
            settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case ProxySocksVersion: {
            proxyType proxy;
            proxy.second = 5;
            GetProxy(NET_IPV4, proxy);

            proxy.second = value.toInt();
            settings.setValue("nSocksVersion", proxy.second);
            successful = ApplyProxySettings();
        }
        break;
        case Fee:
            nTransactionFee = value.toLongLong();
            settings.setValue("nTransactionFee", nTransactionFee);
			emit transactionFeeChanged(nTransactionFee);
            break;
        case DisplayUnit:
            nDisplayUnit = value.toInt();
            settings.setValue("nDisplayUnit", nDisplayUnit);
            emit displayUnitChanged(nDisplayUnit);
            break;
        case DisplayAddresses:
            bDisplayAddresses = value.toBool();
            settings.setValue("bDisplayAddresses", bDisplayAddresses);
            break;
        case DetachDatabases: {
            bool fDetachDB = value.toBool();
            bitdb.SetDetach(fDetachDB);
            settings.setValue("detachDB", fDetachDB);
            }
            break;
        case Language:
            settings.setValue("language", value);
            break;
		case CoinControlFeatures: {
            fCoinControlFeatures = value.toBool();
            settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
            emit coinControlFeaturesChanged(fCoinControlFeatures);
            }
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}

qint64 OptionsModel::getTransactionFee()
{
    return nTransactionFee;
}

bool OptionsModel::getCoinControlFeatures()
{
     return fCoinControlFeatures;
}

bool OptionsModel::getMinimizeToTray()
{
    return fMinimizeToTray;
}

bool OptionsModel::getMinimizeOnClose()
{
    return fMinimizeOnClose;
}

int OptionsModel::getDisplayUnit()
{
    return nDisplayUnit;
}

bool OptionsModel::getDisplayAddresses()
{
    return bDisplayAddresses;
}
<|endoftext|>


<commit_before>#include "splashscreen.h"
#include "clientversion.h"
#include "util.h"

#include <QPainter>
#undef loop /* ugh, remove this when the #define loop is gone from util.h */
#include <QApplication>

SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
    QSplashScreen(pixmap, f)
{
    // set reference point, paddings
    int paddingLeftCol2         = 230;
    int paddingTopCol2          = 376;
    int line1 = 0;
    int line2 = 13;
    int line3 = 26;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
    QString versionText     = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText1   = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers"));
    QString copyrightText2   = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The limecoin developers"));

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(70,70,70));

    pixPaint.setFont(QFont(font, 9*fontFactor));
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 9*fontFactor));
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1);
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2);

    pixPaint.end();

    this->setPixmap(newPixmap);
}
<commit_msg>remove info from slash screen<commit_after>#include "splashscreen.h"
#include "clientversion.h"
#include "util.h"

#include <QPainter>
#undef loop /* ugh, remove this when the #define loop is gone from util.h */
#include <QApplication>

SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) :
    QSplashScreen(pixmap, f)
{
    // set reference point, paddings
    int paddingLeftCol2         = 230;
    int paddingTopCol2          = 376;
    int line1 = 0;
    int line2 = 13;
    int line3 = 26;

    float fontFactor            = 1.0;

    // define text to place
    QString titleText       = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down
    QString versionText     = QString("").arg(QString::fromStdString(FormatFullVersion()));
    QString copyrightText1   = QChar(0xA9)+QString("").arg(COPYRIGHT_YEAR) + QString(tr(""));
    QString copyrightText2   = QChar(0xA9)+QString("").arg(COPYRIGHT_YEAR) + QString(tr(""));

    QString font            = "Arial";

    // load the bitmap for writing some text over it
    QPixmap newPixmap;
    if(GetBoolArg("-testnet")) {
        newPixmap     = QPixmap(":/images/splash_testnet");
    }
    else {
        newPixmap     = QPixmap(":/images/splash");
    }

    QPainter pixPaint(&newPixmap);
    pixPaint.setPen(QColor(70,70,70));

    pixPaint.setFont(QFont(font, 9*fontFactor));
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText);

    // draw copyright stuff
    pixPaint.setFont(QFont(font, 9*fontFactor));
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1);
    pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2);

    pixPaint.end();

    this->setPixmap(newPixmap);
}
<|endoftext|>


<commit_before>#ifndef RunManager_HH
#define RunManager_HH

#include <G4RunManager.hh>

class G4UserEventAction;
class G4UserRunAction;
class G4UserSteppingAction;
class G4UserTrackingAction;

namespace g4
{
    class RunListener;
    class CompositeEventAction;
    class CompositeRunAction;
    class CompositeSteppingAction;
    class CompositeTrackingAction;

    /**
      * Class providing geometry, physics and particle generator
      * for the RunManger.
      *
      * In this library, G4Application is the only subclass
      * but it is possible to create other subclasses in applications
      * without G4Application class.
      */
    class RunInitializer
    {
    public:
        virtual void InitializeGeometry() = 0;

        virtual void InitializePhysics() = 0;

        virtual void InitializeParticleGenerator() = 0;
    };

    /**
      * @short Custom version of G4RunManager that enables us to
      * step in the middle of state transitions.
      *
      * Note: it can be done in another way, from outside
      *   via special callback classes (see manual).
      *
      * AddXXXAction() methods register user actions
      * inside the composite actions.
      *
      * Run manager catches SIGINT signal and stops the run
      * instead of the whole application. Another interrupt
      * makes the application really stop.
      */
    class RunManager : public G4RunManager
    {
    public:
        RunManager(RunInitializer& init);

        /**
          * @short Do what is necessary for the application and do standard initialize.
          *
          * This invokes all the builders from plugins.
          * It is called with /run/initialize
          */
        virtual void Initialize();

        virtual void DoEventLoop(G4int n_event,const char* macroFile=0,G4int n_select=-1);

        virtual void RunTermination();

        void AddAction(G4UserEventAction* action);

        void AddAction(G4UserRunAction* action);

        void AddAction(G4UserSteppingAction* action);

        void AddAction(G4UserTrackingAction* action);

        void InitializeUserActions();

        void AddListener(RunListener* listener);

        void RemoveListener(RunListener* listener);

    private:
        RunInitializer& _initializer;

        CompositeEventAction* _eventAction;

        CompositeRunAction* _runAction;

        CompositeSteppingAction* _steppingAction;

        CompositeTrackingAction* _trackingAction;

        std::vector<RunListener*> _listeners;
    };
}

#endif // RunManager_HH
<commit_msg>RunInitializer: virtual destructor<commit_after>#ifndef RunManager_HH
#define RunManager_HH

#include <G4RunManager.hh>

class G4UserEventAction;
class G4UserRunAction;
class G4UserSteppingAction;
class G4UserTrackingAction;

namespace g4
{
    class RunListener;
    class CompositeEventAction;
    class CompositeRunAction;
    class CompositeSteppingAction;
    class CompositeTrackingAction;

    /**
      * Class providing geometry, physics and particle generator
      * for the RunManger.
      *
      * In this library, G4Application is the only subclass
      * but it is possible to create other subclasses in applications
      * without G4Application class.
      */
    class RunInitializer
    {
    public:
        virtual void InitializeGeometry() = 0;

        virtual void InitializePhysics() = 0;

        virtual void InitializeParticleGenerator() = 0;

        virtual ~RunInitializer() { };
    };

    /**
      * @short Custom version of G4RunManager that enables us to
      * step in the middle of state transitions.
      *
      * Note: it can be done in another way, from outside
      *   via special callback classes (see manual).
      *
      * AddXXXAction() methods register user actions
      * inside the composite actions.
      *
      * Run manager catches SIGINT signal and stops the run
      * instead of the whole application. Another interrupt
      * makes the application really stop.
      */
    class RunManager : public G4RunManager
    {
    public:
        RunManager(RunInitializer& init);

        /**
          * @short Do what is necessary for the application and do standard initialize.
          *
          * This invokes all the builders from plugins.
          * It is called with /run/initialize
          */
        virtual void Initialize();

        virtual void DoEventLoop(G4int n_event,const char* macroFile=0,G4int n_select=-1);

        virtual void RunTermination();

        void AddAction(G4UserEventAction* action);

        void AddAction(G4UserRunAction* action);

        void AddAction(G4UserSteppingAction* action);

        void AddAction(G4UserTrackingAction* action);

        void InitializeUserActions();

        void AddListener(RunListener* listener);

        void RemoveListener(RunListener* listener);

    private:
        RunInitializer& _initializer;

        CompositeEventAction* _eventAction;

        CompositeRunAction* _runAction;

        CompositeSteppingAction* _steppingAction;

        CompositeTrackingAction* _trackingAction;

        std::vector<RunListener*> _listeners;
    };
}

#endif // RunManager_HH
<|endoftext|>