<commit_before>/**
 * @file cache.cpp
 *
 * @date Nov 21, 2012
 * @author perämäki
 */

#include "cache.h"
#include "logger_factory.h"
#include "info.h"
#include <time.h>
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
#include "regular_grid.h"

using namespace std;
using namespace himan::plugin;

typedef lock_guard<mutex> Lock;

cache::cache()
{
    itsLogger = logger_factory::Instance()->GetLog("cache");
}

string cache::UniqueName(const info& info)
{
	string producer_id = boost::lexical_cast<string> (info.Producer().Id());
	string forecast_time = info.Time().OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
	string valid_time = info.Time().ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
	string param = info.Param().Name();
	string level_value = boost::lexical_cast<string>(info.Level().Value());
	string level = HPLevelTypeToString.at(info.Level().Type());
	return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;

}

string cache::UniqueNameFromOptions(search_options& options)
{
	string producer_id = boost::lexical_cast<string> (options.prod.Id());
	string forecast_time = options.time.OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
	string valid_time = options.time.ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
	string param = options.param.Name();
	string level_value = boost::lexical_cast<string>((options.level).Value());
	string level = HPLevelTypeToString.at(options.level.Type());
	return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}

void cache::Insert(info& anInfo, bool pin)
{
	SplitToPool(anInfo, pin);
}

void cache::SplitToPool(info& anInfo, bool pin)
{

	// Cached data is never replaced by another data that has
	// the same uniqueName

	string uniqueName = UniqueName(anInfo);

	if (cache_pool::Instance()->Find(uniqueName))
	{
		itsLogger->Trace("Data with key " + uniqueName + " already exists at cache");

		// Update timestamp of this cache item
		cache_pool::Instance()->UpdateTime(uniqueName);
		return;
	}

#ifdef HAVE_CUDA
	if (anInfo.Grid()->IsPackedData())
	{
		itsLogger->Trace("Removing packed data from cached info");
		dynamic_cast<himan::regular_grid*> (anInfo.Grid())->PackedData().Clear();
	}
#endif

	assert(!anInfo.Grid()->IsPackedData());

	assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Ni() != 999999);
	assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Nj() != 999999);

	vector<param> params;
	vector<level> levels;
	vector<forecast_time> times;

	params.push_back(anInfo.Param());
	levels.push_back(anInfo.Level());
	times.push_back(anInfo.Time());

	auto newInfo = make_shared<info> (anInfo);

	newInfo->Params(params);
	newInfo->Levels(levels);
	newInfo->Times(times);
	newInfo->Create(anInfo.Grid());

	assert(uniqueName == UniqueName(*newInfo));

	// Race condition?
	cache_pool::Instance()->Insert(uniqueName, newInfo, pin);

}

vector<shared_ptr<himan::info>> cache::GetInfo(search_options& options)
{
	string uniqueName = UniqueNameFromOptions(options);

	vector<shared_ptr<himan::info>> info;

	if (cache_pool::Instance()->Find(uniqueName))
	{
		info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
		itsLogger->Trace( "Found matching data for " + uniqueName);
	}

	return info;
}

void cache::Clean()
{
	cache_pool::Instance()->Clean();
}

size_t cache::Size() const
{
	return cache_pool::Instance()->Size();
}

cache_pool* cache_pool::itsInstance = NULL;

cache_pool::cache_pool() : itsCacheLimit(-1)
{
    itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool"));
}

cache_pool* cache_pool::Instance()
{
	if (!itsInstance)
	{
		itsInstance = new cache_pool();
	}

	return itsInstance;
}

void cache_pool::CacheLimit(int theCacheLimit)
{
	itsCacheLimit = theCacheLimit;
}

bool cache_pool::Find(const string& uniqueName)
{
	for (const auto& kv : itsCache)
	{
		if (kv.first == uniqueName)
		{
			return true;
		}
	}

	return false;
}

void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo, bool pin)
{
	Lock lock(itsInsertMutex);

	cache_item item;
	item.info = anInfo;
	item.access_time = time(nullptr);
	item.pinned = pin;

	itsCache.insert(pair<string, cache_item>(uniqueName, item));
	itsLogger->Trace("Data added to cache with name: " + uniqueName + ", pinned: " + boost::lexical_cast<string> (pin));

	if (itsCacheLimit > -1 && itsCache.size() > static_cast<size_t> (itsCacheLimit))
	{
		Clean();
	}

}

void cache_pool::UpdateTime(const std::string& uniqueName)
{
	itsCache[uniqueName].access_time = time(nullptr);
}

void cache_pool::Clean()
{
	Lock lock(itsDeleteMutex);

	assert(itsCacheLimit > 0);
	if (itsCache.size() <= static_cast<size_t> (itsCacheLimit))
	{
		return;
	}

	string oldestName;
	time_t oldestTime = INT_MAX;

	for (const auto& kv : itsCache)
	{
		if (kv.second.access_time < oldestTime && !kv.second.pinned)
		{
			oldestName = kv.first;
			oldestTime = kv.second.access_time;
		}
	}

	assert(!oldestName.empty());

	itsCache.erase(oldestName);
	itsLogger->Trace("Data cleared from cache: " + oldestName + " with time: " + boost::lexical_cast<string> (oldestTime));
	itsLogger->Trace("Cache size: " + boost::lexical_cast<string> (itsCache.size()));

}

shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
	Lock lock(itsGetMutex);

	return make_shared<info> (*itsCache[uniqueName].info);
}

size_t cache_pool::Size() const
{
	return itsCache.size();
}
<commit_msg>Cache now supports ensemble forecasts<commit_after>/**
 * @file cache.cpp
 *
 * @date Nov 21, 2012
 * @author perämäki
 */

#include "cache.h"
#include "logger_factory.h"
#include "info.h"
#include <time.h>
#include "plugin_factory.h"
#include <boost/lexical_cast.hpp>
#include "regular_grid.h"

using namespace std;
using namespace himan::plugin;

typedef lock_guard<mutex> Lock;

cache::cache()
{
    itsLogger = logger_factory::Instance()->GetLog("cache");
}

string cache::UniqueName(const info& info)
{
	string producer_id = boost::lexical_cast<string> (info.Producer().Id());
	string forecast_time = info.Time().OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
	string valid_time = info.Time().ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
	string param = info.Param().Name();
	string level_value = boost::lexical_cast<string>(info.Level().Value());
	string level = HPLevelTypeToString.at(info.Level().Type());
	string forecast_value = boost::lexical_cast<string>(info.ForecastType().Value());
	return producer_id + '_' + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value
		+ '_' + forecast_value;
}

string cache::UniqueNameFromOptions(search_options& options)
{
	string producer_id = boost::lexical_cast<string> (options.prod.Id());
	string forecast_time = options.time.OriginDateTime().String("%Y-%m-%d_%H:%M:%S");
	string valid_time = options.time.ValidDateTime().String("%Y-%m-%d_%H:%M:%S");
	string param = options.param.Name();
	string level_value = boost::lexical_cast<string>((options.level).Value());
	string level = HPLevelTypeToString.at(options.level.Type());
	return producer_id + "_" + forecast_time + '_' + valid_time + '_' + param + '_' + level + '_' + level_value;
}

void cache::Insert(info& anInfo, bool pin)
{
	SplitToPool(anInfo, pin);
}

void cache::SplitToPool(info& anInfo, bool pin)
{

	// Cached data is never replaced by another data that has
	// the same uniqueName

	string uniqueName = UniqueName(anInfo);

	if (cache_pool::Instance()->Find(uniqueName))
	{
		itsLogger->Trace("Data with key " + uniqueName + " already exists at cache");

		// Update timestamp of this cache item
		cache_pool::Instance()->UpdateTime(uniqueName);
		return;
	}

#ifdef HAVE_CUDA
	if (anInfo.Grid()->IsPackedData())
	{
		itsLogger->Trace("Removing packed data from cached info");
		dynamic_cast<himan::regular_grid*> (anInfo.Grid())->PackedData().Clear();
	}
#endif

	assert(!anInfo.Grid()->IsPackedData());

	assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Ni() != 999999);
	assert(anInfo.Grid()->Type() == kIrregularGrid || !dynamic_cast<regular_grid*> (anInfo.Grid())->Nj() != 999999);

	vector<param> params;
	vector<level> levels;
	vector<forecast_time> times;

	params.push_back(anInfo.Param());
	levels.push_back(anInfo.Level());
	times.push_back(anInfo.Time());

	auto newInfo = make_shared<info> (anInfo);

	newInfo->Params(params);
	newInfo->Levels(levels);
	newInfo->Times(times);
	newInfo->Create(anInfo.Grid());

	assert(uniqueName == UniqueName(*newInfo));

	// Race condition?
	cache_pool::Instance()->Insert(uniqueName, newInfo, pin);

}

vector<shared_ptr<himan::info>> cache::GetInfo(search_options& options)
{
	string uniqueName = UniqueNameFromOptions(options);

	vector<shared_ptr<himan::info>> info;

	if (cache_pool::Instance()->Find(uniqueName))
	{
		info.push_back(cache_pool::Instance()->GetInfo(uniqueName));
		itsLogger->Trace( "Found matching data for " + uniqueName);
	}

	return info;
}

void cache::Clean()
{
	cache_pool::Instance()->Clean();
}

size_t cache::Size() const
{
	return cache_pool::Instance()->Size();
}

cache_pool* cache_pool::itsInstance = NULL;

cache_pool::cache_pool() : itsCacheLimit(-1)
{
    itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("cache_pool"));
}

cache_pool* cache_pool::Instance()
{
	if (!itsInstance)
	{
		itsInstance = new cache_pool();
	}

	return itsInstance;
}

void cache_pool::CacheLimit(int theCacheLimit)
{
	itsCacheLimit = theCacheLimit;
}

bool cache_pool::Find(const string& uniqueName)
{
	for (const auto& kv : itsCache)
	{
		if (kv.first == uniqueName)
		{
			return true;
		}
	}

	return false;
}

void cache_pool::Insert(const string& uniqueName, shared_ptr<himan::info> anInfo, bool pin)
{
	Lock lock(itsInsertMutex);

	cache_item item;
	item.info = anInfo;
	item.access_time = time(nullptr);
	item.pinned = pin;

	itsCache.insert(pair<string, cache_item>(uniqueName, item));
	itsLogger->Trace("Data added to cache with name: " + uniqueName + ", pinned: " + boost::lexical_cast<string> (pin));

	if (itsCacheLimit > -1 && itsCache.size() > static_cast<size_t> (itsCacheLimit))
	{
		Clean();
	}

}

void cache_pool::UpdateTime(const std::string& uniqueName)
{
	itsCache[uniqueName].access_time = time(nullptr);
}

void cache_pool::Clean()
{
	Lock lock(itsDeleteMutex);

	assert(itsCacheLimit > 0);
	if (itsCache.size() <= static_cast<size_t> (itsCacheLimit))
	{
		return;
	}

	string oldestName;
	time_t oldestTime = INT_MAX;

	for (const auto& kv : itsCache)
	{
		if (kv.second.access_time < oldestTime && !kv.second.pinned)
		{
			oldestName = kv.first;
			oldestTime = kv.second.access_time;
		}
	}

	assert(!oldestName.empty());

	itsCache.erase(oldestName);
	itsLogger->Trace("Data cleared from cache: " + oldestName + " with time: " + boost::lexical_cast<string> (oldestTime));
	itsLogger->Trace("Cache size: " + boost::lexical_cast<string> (itsCache.size()));

}

shared_ptr<himan::info> cache_pool::GetInfo(const string& uniqueName)
{
	Lock lock(itsGetMutex);

	return make_shared<info> (*itsCache[uniqueName].info);
}

size_t cache_pool::Size() const
{
	return itsCache.size();
}
<|endoftext|>


<commit_before>#include "simdjson.h"
#include <unistd.h>

#include "benchmark.h"
// #define RAPIDJSON_SSE2 // bad for performance
// #define RAPIDJSON_SSE42 // bad for performance
#include "rapidjson/document.h"
#include "rapidjson/reader.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"

#include "sajson.h"

using namespace rapidjson;
using namespace simdjson;
struct stat_s {
  size_t number_count;
  size_t object_count;
  size_t array_count;
  size_t null_count;
  size_t true_count;
  size_t false_count;
  bool valid;
};

typedef struct stat_s stat_t;

bool stat_equal(const stat_t &s1, const stat_t &s2) {
  return (s1.valid == s2.valid) && (s1.number_count == s2.number_count) &&
         (s1.object_count == s2.object_count) &&
         (s1.array_count == s2.array_count) &&
         (s1.null_count == s2.null_count) && (s1.true_count == s2.true_count) &&
         (s1.false_count == s2.false_count);
}

void print_stat(const stat_t &s) {
  if (!s.valid) {
    printf("invalid\n");
    return;
  }
  printf("number: %zu object: %zu array: %zu null: %zu true: %zu false: %zu\n",
         s.number_count, s.object_count, s.array_count, s.null_count,
         s.true_count, s.false_count);
}

__attribute__((noinline)) stat_t
simdjson_compute_stats(const simdjson::padded_string &p) {
  stat_t answer;
  simdjson::ParsedJson pj = build_parsed_json(p);
  answer.valid = pj.is_valid();
  if (!answer.valid) {
    return answer;
  }
  answer.number_count = 0;
  answer.object_count = 0;
  answer.array_count = 0;
  answer.null_count = 0;
  answer.true_count = 0;
  answer.false_count = 0;
  size_t tape_idx = 0;
  uint64_t tape_val = pj.doc.tape[tape_idx++];
  uint8_t type = (tape_val >> 56);
  size_t how_many = 0;
  assert(type == 'r');
  how_many = tape_val & simdjson::internal::JSON_VALUE_MASK;
  for (; tape_idx < how_many; tape_idx++) {
    tape_val = pj.doc.tape[tape_idx];
    // uint64_t payload = tape_val & simdjson::internal::JSON_VALUE_MASK;
    type = (tape_val >> 56);
    switch (type) {
    case 'l': // we have a long int
      answer.number_count++;
      tape_idx++; // skipping the integer
      break;
    case 'u': // we have a long uint
      answer.number_count++;
      tape_idx++; // skipping the unsigned integer
      break;
    case 'd': // we have a double
      answer.number_count++;
      tape_idx++; // skipping the double
      break;
    case 'n': // we have a null
      answer.null_count++;
      break;
    case 't': // we have a true
      answer.true_count++;
      break;
    case 'f': // we have a false
      answer.false_count++;
      break;
    case '{': // we have an object
      answer.object_count++;
      break;
    case '}': // we end an object
      break;
    case '[': // we start an array
      answer.array_count++;
      break;
    case ']': // we end an array
      break;
    default:
      break; // ignore
    }
  }
  return answer;
}

// see
// https://github.com/miloyip/nativejson-benchmark/blob/master/src/tests/sajsontest.cpp
void sajson_traverse(stat_t &stats, const sajson::value &node) {
  using namespace sajson;
  switch (node.get_type()) {
  case TYPE_NULL:
    stats.null_count++;
    break;
  case TYPE_FALSE:
    stats.false_count++;
    break;
  case TYPE_TRUE:
    stats.true_count++;
    break;
  case TYPE_ARRAY: {
    stats.array_count++;
    auto length = node.get_length();
    for (size_t i = 0; i < length; ++i) {
      sajson_traverse(stats, node.get_array_element(i));
    }
    break;
  }
  case TYPE_OBJECT: {
    stats.object_count++;
    auto length = node.get_length();
    for (auto i = 0u; i < length; ++i) {
      sajson_traverse(stats, node.get_object_value(i));
    }
    break;
  }
  case TYPE_STRING:
    // skip
    break;

  case TYPE_DOUBLE:
  case TYPE_INTEGER:
    stats.number_count++; // node.get_number_value();
    break;
  default:
    assert(false && "unknown node type");
  }
}

__attribute__((noinline)) stat_t
sasjon_compute_stats(const simdjson::padded_string &p) {
  stat_t answer;
  char *buffer = (char *)malloc(p.size());
  if(buffer == nullptr) {
    return answer;
  }
  memcpy(buffer, p.data(), p.size());
  auto d = sajson::parse(sajson::dynamic_allocation(),
                         sajson::mutable_string_view(p.size(), buffer));
  answer.valid = d.is_valid();
  if (!answer.valid) {
    free(buffer);
    return answer;
  }
  answer.number_count = 0;
  answer.object_count = 0;
  answer.array_count = 0;
  answer.null_count = 0;
  answer.true_count = 0;
  answer.false_count = 0;
  sajson_traverse(answer, d.get_root());
  free(buffer);
  return answer;
}

void rapid_traverse(stat_t &stats, const rapidjson::Value &v) {
  switch (v.GetType()) {
  case kNullType:
    stats.null_count++;
    break;
  case kFalseType:
    stats.false_count++;
    break;
  case kTrueType:
    stats.true_count++;
    break;

  case kObjectType:
    for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd();
         ++m) {
      rapid_traverse(stats, m->value);
    }
    stats.object_count++;
    break;
  case kArrayType:
    for (Value::ConstValueIterator i = v.Begin(); i != v.End();
         ++i) { // v.Size();
      rapid_traverse(stats, *i);
    }
    stats.array_count++;
    break;

  case kStringType:
    break;

  case kNumberType:
    stats.number_count++;
    break;
  }
}

__attribute__((noinline)) stat_t
rapid_compute_stats(const simdjson::padded_string &p) {
  stat_t answer;
  char *buffer = (char *)malloc(p.size() + 1);
  if(buffer == nullptr) {
    return answer;
  }
  memcpy(buffer, p.data(), p.size());
  buffer[p.size()] = '\0';
  rapidjson::Document d;
  d.ParseInsitu<kParseValidateEncodingFlag>(buffer);
  answer.valid = !d.HasParseError();
  if (!answer.valid) {
    free(buffer);
    return answer;
  }
  answer.number_count = 0;
  answer.object_count = 0;
  answer.array_count = 0;
  answer.null_count = 0;
  answer.true_count = 0;
  answer.false_count = 0;
  rapid_traverse(answer, d);
  free(buffer);
  return answer;
}

__attribute__((noinline)) stat_t
rapid_accurate_compute_stats(const simdjson::padded_string &p) {
  stat_t answer;
  char *buffer = (char *)malloc(p.size() + 1);
  if(buffer == nullptr) {
    return answer;
  }
  memcpy(buffer, p.data(), p.size());
  buffer[p.size()] = '\0';
  rapidjson::Document d;
  d.ParseInsitu<kParseValidateEncodingFlag|kParseFullPrecisionFlag>(buffer);
  answer.valid = !d.HasParseError();
  if (!answer.valid) {
    free(buffer);
    return answer;
  }
  answer.number_count = 0;
  answer.object_count = 0;
  answer.array_count = 0;
  answer.null_count = 0;
  answer.true_count = 0;
  answer.false_count = 0;
  rapid_traverse(answer, d);
  free(buffer);
  return answer;
}
int main(int argc, char *argv[]) {
  bool verbose = false;
  bool just_data = false;

  int c;
  while ((c = getopt(argc, argv, "vt")) != -1)
    switch (c) {
    case 't':
      just_data = true;
      break;
    case 'v':
      verbose = true;
      break;
    default:
      abort();
    }
  if (optind >= argc) {
    std::cerr
        << "Using different parsers, we compute the content statistics of "
           "JSON documents."
        << std::endl;
    std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
    std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl;
    exit(1);
  }
  const char *filename = argv[optind];
  if (optind + 1 < argc) {
    std::cerr << "warning: ignoring everything after " << argv[optind + 1]
              << std::endl;
  }
  auto [p, error] = simdjson::padded_string::load(filename);
  if (error) {
    std::cerr << "Could not load the file " << filename << std::endl;
    return EXIT_FAILURE;
  }

  if (verbose) {
    std::cout << "Input has ";
    if (p.size() > 1024 * 1024)
      std::cout << p.size() / (1024 * 1024) << " MB ";
    else if (p.size() > 1024)
      std::cout << p.size() / 1024 << " KB ";
    else
      std::cout << p.size() << " B ";
    std::cout << std::endl;
  }
  stat_t s1 = simdjson_compute_stats(p);
  if (verbose) {
    printf("simdjson: ");
    print_stat(s1);
  }
  stat_t s2 = rapid_compute_stats(p);
  if (verbose) {
    printf("rapid:    ");
    print_stat(s2);
  }
  stat_t s2a = rapid_accurate_compute_stats(p);
  if (verbose) {
    printf("rapid full:    ");
    print_stat(s2);
  }
  stat_t s3 = sasjon_compute_stats(p);
  if (verbose) {
    printf("sasjon:   ");
    print_stat(s3);
  }
  assert(stat_equal(s1, s2));
  assert(stat_equal(s1, s3));
  int repeat = 50;
  int volume = p.size();
  if (just_data) {
    printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
  }
  BEST_TIME("simdjson  ", simdjson_compute_stats(p).valid, true, , repeat,
            volume, !just_data);
  BEST_TIME("RapidJSON  ", rapid_compute_stats(p).valid, true, , repeat, volume,
            !just_data);
  BEST_TIME("sasjon  ", sasjon_compute_stats(p).valid, true, , repeat, volume,
            !just_data);
}
<commit_msg>Fixing issue 601 (#618)<commit_after>#include "simdjson.h"
#include <unistd.h>

#include "benchmark.h"
// #define RAPIDJSON_SSE2 // bad for performance
// #define RAPIDJSON_SSE42 // bad for performance
#include "rapidjson/document.h"
#include "rapidjson/reader.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"

#include "sajson.h"

using namespace rapidjson;
using namespace simdjson;
struct stat_s {
  size_t number_count;
  size_t object_count;
  size_t array_count;
  size_t null_count;
  size_t true_count;
  size_t false_count;
  bool valid;
};

typedef struct stat_s stat_t;

bool stat_equal(const stat_t &s1, const stat_t &s2) {
  return (s1.valid == s2.valid) && (s1.number_count == s2.number_count) &&
         (s1.object_count == s2.object_count) &&
         (s1.array_count == s2.array_count) &&
         (s1.null_count == s2.null_count) && (s1.true_count == s2.true_count) &&
         (s1.false_count == s2.false_count);
}

void print_stat(const stat_t &s) {
  if (!s.valid) {
    printf("invalid\n");
    return;
  }
  printf("number: %zu object: %zu array: %zu null: %zu true: %zu false: %zu\n",
         s.number_count, s.object_count, s.array_count, s.null_count,
         s.true_count, s.false_count);
}

really_inline void simdjson_process_atom(stat_t &s,
                                         simdjson::document::element element) {
  if (element.is_number()) {
    s.number_count++;
  } else if (element.is_bool()) {
    if (element.as_bool()) {
      s.true_count++;
    } else {
      s.false_count++;
    }
  } else if (element.is_null()) {
    s.null_count++;
  }
}

void simdjson_recurse(stat_t &s, simdjson::document::element element) {
  if (element.is_array()) {
    s.array_count++;
    auto [array, array_error] = element.as_array();
    for (auto child : array) {
      if (child.is_array() || child.is_object()) {
        simdjson_recurse(s, child);
      } else {
        simdjson_process_atom(s, child);
      }
    }
  } else if (element.is_object()) {
    s.object_count++;
    auto [object, object_error] = element.as_object();
    for (auto [key, value] : object) {
      if (value.is_array() || value.is_object()) {
        simdjson_recurse(s, value);
      } else {
        simdjson_process_atom(s, value);
      }
    }
  } else {
    simdjson_process_atom(s, element);
  }
}

__attribute__((noinline)) stat_t
simdjson_compute_stats(const simdjson::padded_string &p) {
  stat_t s{};
  simdjson::document::parser parser;
  auto [doc, error] = parser.parse(p);
  if (error) {
    s.valid = false;
    return s;
  }
  s.valid = true;
  simdjson_recurse(s, doc.root());
  return s;
}

// see
// https://github.com/miloyip/nativejson-benchmark/blob/master/src/tests/sajsontest.cpp
void sajson_traverse(stat_t &stats, const sajson::value &node) {
  using namespace sajson;
  switch (node.get_type()) {
  case TYPE_NULL:
    stats.null_count++;
    break;
  case TYPE_FALSE:
    stats.false_count++;
    break;
  case TYPE_TRUE:
    stats.true_count++;
    break;
  case TYPE_ARRAY: {
    stats.array_count++;
    auto length = node.get_length();
    for (size_t i = 0; i < length; ++i) {
      sajson_traverse(stats, node.get_array_element(i));
    }
    break;
  }
  case TYPE_OBJECT: {
    stats.object_count++;
    auto length = node.get_length();
    for (auto i = 0u; i < length; ++i) {
      sajson_traverse(stats, node.get_object_value(i));
    }
    break;
  }
  case TYPE_STRING:
    // skip
    break;

  case TYPE_DOUBLE:
  case TYPE_INTEGER:
    stats.number_count++; // node.get_number_value();
    break;
  default:
    assert(false && "unknown node type");
  }
}

__attribute__((noinline)) stat_t
sasjon_compute_stats(const simdjson::padded_string &p) {
  stat_t answer;
  char *buffer = (char *)malloc(p.size());
  if (buffer == nullptr) {
    return answer;
  }
  memcpy(buffer, p.data(), p.size());
  auto d = sajson::parse(sajson::dynamic_allocation(),
                         sajson::mutable_string_view(p.size(), buffer));
  answer.valid = d.is_valid();
  if (!answer.valid) {
    free(buffer);
    return answer;
  }
  answer.number_count = 0;
  answer.object_count = 0;
  answer.array_count = 0;
  answer.null_count = 0;
  answer.true_count = 0;
  answer.false_count = 0;
  sajson_traverse(answer, d.get_root());
  free(buffer);
  return answer;
}

void rapid_traverse(stat_t &stats, const rapidjson::Value &v) {
  switch (v.GetType()) {
  case kNullType:
    stats.null_count++;
    break;
  case kFalseType:
    stats.false_count++;
    break;
  case kTrueType:
    stats.true_count++;
    break;

  case kObjectType:
    for (Value::ConstMemberIterator m = v.MemberBegin(); m != v.MemberEnd();
         ++m) {
      rapid_traverse(stats, m->value);
    }
    stats.object_count++;
    break;
  case kArrayType:
    for (Value::ConstValueIterator i = v.Begin(); i != v.End();
         ++i) { // v.Size();
      rapid_traverse(stats, *i);
    }
    stats.array_count++;
    break;

  case kStringType:
    break;

  case kNumberType:
    stats.number_count++;
    break;
  }
}

__attribute__((noinline)) stat_t
rapid_compute_stats(const simdjson::padded_string &p) {
  stat_t answer;
  char *buffer = (char *)malloc(p.size() + 1);
  if (buffer == nullptr) {
    return answer;
  }
  memcpy(buffer, p.data(), p.size());
  buffer[p.size()] = '\0';
  rapidjson::Document d;
  d.ParseInsitu<kParseValidateEncodingFlag>(buffer);
  answer.valid = !d.HasParseError();
  if (!answer.valid) {
    free(buffer);
    return answer;
  }
  answer.number_count = 0;
  answer.object_count = 0;
  answer.array_count = 0;
  answer.null_count = 0;
  answer.true_count = 0;
  answer.false_count = 0;
  rapid_traverse(answer, d);
  free(buffer);
  return answer;
}

__attribute__((noinline)) stat_t
rapid_accurate_compute_stats(const simdjson::padded_string &p) {
  stat_t answer;
  char *buffer = (char *)malloc(p.size() + 1);
  if (buffer == nullptr) {
    return answer;
  }
  memcpy(buffer, p.data(), p.size());
  buffer[p.size()] = '\0';
  rapidjson::Document d;
  d.ParseInsitu<kParseValidateEncodingFlag | kParseFullPrecisionFlag>(buffer);
  answer.valid = !d.HasParseError();
  if (!answer.valid) {
    free(buffer);
    return answer;
  }
  answer.number_count = 0;
  answer.object_count = 0;
  answer.array_count = 0;
  answer.null_count = 0;
  answer.true_count = 0;
  answer.false_count = 0;
  rapid_traverse(answer, d);
  free(buffer);
  return answer;
}
int main(int argc, char *argv[]) {
  bool verbose = false;
  bool just_data = false;

  int c;
  while ((c = getopt(argc, argv, "vt")) != -1)
    switch (c) {
    case 't':
      just_data = true;
      break;
    case 'v':
      verbose = true;
      break;
    default:
      abort();
    }
  if (optind >= argc) {
    std::cerr
        << "Using different parsers, we compute the content statistics of "
           "JSON documents."
        << std::endl;
    std::cerr << "Usage: " << argv[0] << " <jsonfile>" << std::endl;
    std::cerr << "Or " << argv[0] << " -v <jsonfile>" << std::endl;
    exit(1);
  }
  const char *filename = argv[optind];
  if (optind + 1 < argc) {
    std::cerr << "warning: ignoring everything after " << argv[optind + 1]
              << std::endl;
  }
  auto [p, error] = simdjson::padded_string::load(filename);
  if (error) {
    std::cerr << "Could not load the file " << filename << std::endl;
    return EXIT_FAILURE;
  }

  if (verbose) {
    std::cout << "Input has ";
    if (p.size() > 1024 * 1024)
      std::cout << p.size() / (1024 * 1024) << " MB ";
    else if (p.size() > 1024)
      std::cout << p.size() / 1024 << " KB ";
    else
      std::cout << p.size() << " B ";
    std::cout << std::endl;
  }
  stat_t s1 = simdjson_compute_stats(p);
  if (verbose) {
    printf("simdjson: ");
    print_stat(s1);
  }
  stat_t s2 = rapid_compute_stats(p);
  if (verbose) {
    printf("rapid:    ");
    print_stat(s2);
  }
  stat_t s2a = rapid_accurate_compute_stats(p);
  if (verbose) {
    printf("rapid full:    ");
    print_stat(s2a);
  }
  stat_t s3 = sasjon_compute_stats(p);
  if (verbose) {
    printf("sasjon:   ");
    print_stat(s3);
  }
  assert(stat_equal(s1, s2));
  assert(stat_equal(s1, s3));
  int repeat = 50;
  int volume = p.size();
  if (just_data) {
    printf("name cycles_per_byte cycles_per_byte_err gb_per_s gb_per_s_err \n");
  }
  BEST_TIME("simdjson            ", simdjson_compute_stats(p).valid, true, ,
            repeat, volume, !just_data);
  BEST_TIME("RapidJSON           ", rapid_compute_stats(p).valid, true, ,
            repeat, volume, !just_data);
  BEST_TIME("RapidJSON (precise) ", rapid_accurate_compute_stats(p).valid, true, ,
            repeat, volume, !just_data);
  BEST_TIME("sasjon              ", sasjon_compute_stats(p).valid, true, ,
            repeat, volume, !just_data);
}
<|endoftext|>


<commit_before>#include "metaEditorSupportPlugin.h"

#include <QtCore/QProcess>
#include <QtGui/QApplication>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtGui/QDesktopWidget>

#include "../../../qrkernel/settingsManager.h"
#include "../../../qrmc/metaCompiler.h"

#include "editorGenerator.h"
#include "xmlParser.h"

Q_EXPORT_PLUGIN2(metaEditorSupportPlugin, metaEditor::MetaEditorSupportPlugin)

using namespace qReal;
using namespace metaEditor;

MetaEditorSupportPlugin::MetaEditorSupportPlugin()
		: mGenerateEditorForQrxcAction(NULL)
		, mGenerateEditorWithQrmcAction(NULL)
		, mParseEditorXmlAction(NULL)
		, mRepoControlApi(NULL)
		, mCompilerSettingsPage(new PreferencesCompilerPage())
{
	mAppTranslator.load(":/metaEditorSupport_" + QLocale::system().name());
	QApplication::installTranslator(&mAppTranslator);
}

MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}

void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
	mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
	mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
	mRepoControlApi = &configurator.repoControlInterface();
}

QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
	mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
	ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
	connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));

	/*mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
	ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
	connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));

	mParseEditorXmlAction.setText(tr("Parse editor xml"));
	ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
	connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
	*/

	return QList<ActionInfo>() << generateEditorForQrxcActionInfo;
	//<< generateEditorWithQrmcActionInfo
	//<< parseEditorXmlActionInfo;
}

QPair<QString, PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
	return qMakePair(QObject::tr("Compiler"), static_cast<PreferencesPage*>(mCompilerSettingsPage));
}

void MetaEditorSupportPlugin::generateEditorForQrxc()
{
	EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());

	QDir dir(".");

	QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
	foreach (Id const &key, metamodelList.keys()) {
		QString const nameOfTheDirectory = metamodelList[key].first;
		QString const pathToQRealRoot = metamodelList[key].second;
		dir.mkpath(nameOfTheDirectory);
		QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);

		if (!mMainWindowInterface->errorReporter()->wereErrors()) {
			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
					QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
			{
				return;
			}
			loadNewEditor(nameOfTheDirectory, metamodelNames
					, SettingsManager::value("pathToQmake").toString()
					, SettingsManager::value("pathToMake").toString()
					, SettingsManager::value("pluginExtension").toString()
					, SettingsManager::value("prefix").toString());
		}
	}
	if (metamodelList.isEmpty()) {
		mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
	}
}

void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mRepoControlApi->workingFile());

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
		if (objectType == "MetamodelDiagram") {
			QString name = mLogicalRepoApi->stringProperty(key, "name of the directory");
			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(name)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(name)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + name);
				continue;
			}
			progress->setValue(20);

			QProcess builder;
			builder.setWorkingDirectory("../qrmc/plugins");
			builder.start(SettingsManager::value("pathToQmake").toString());
			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);

				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";
				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";

					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = name.at(0).toUpper() + name.mid(1);
					if (!name.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							+ name
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;
					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
	if (progress->value() != 100) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
	}
	progress->setValue(100);
	progress->close();
	delete progress;
}

void MetaEditorSupportPlugin::parseEditorXml()
{
	if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
		return;
	}
	QDir dir(".");
	QString directoryName = ".";
	while (dir.cdUp()) {
		QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
		foreach (QFileInfo const &directory, infoList){
			if (directory.baseName() == "qrxml") {
				directoryName = directory.absolutePath() + "/qrxml";
			}
		}
	}
	QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
			, tr("Select xml file to parse")
			, directoryName
			, "XML files (*.xml)");

	if (fileName.isEmpty())
		return;

	XmlParser parser(*mLogicalRepoApi);

	parser.parseFile(fileName);

	parser.loadIncludeList(fileName);

	mMainWindowInterface->reinitModels();
}

void MetaEditorSupportPlugin::deleteGeneratedFiles(QString const &directoryName, QString const &fileBaseName)
{
	QFile filePro(fileBaseName + ".pro");
	QFile fileXml(fileBaseName + ".xml");
	QDir::setCurrent(directoryName);
	filePro.remove();
	fileXml.remove();
}

void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
		, QPair<QString, QString> const &metamodelNames
		, QString const &commandFirst
		, QString const &commandSecond
		, QString const &extension
		, QString const &prefix)
{
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QString const metamodelName = metamodelNames.first;
	QString const normalizerMetamodelName = metamodelNames.second;

	if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
		return;
	}

	QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);

	QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();

	QApplication::processEvents();

	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);
	progress->setValue(5);

	if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot unload plugin"));
		deleteGeneratedFiles(directoryName, normalizerMetamodelName);
		progress->close();
		delete progress;
		return;
	}

	progress->setValue(20);

	QProcess builder;
	builder.setWorkingDirectory(directoryName);
	builder.start(commandFirst);

	if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
		progress->setValue(60);
		builder.start(commandSecond);
		if (builder.waitForFinished() && (builder.exitCode() == 0)) {
			progress->setValue(80);

			if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
				progress->setValue(100);
			}
		}
	}

	if (progress->value() != 100) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
		deleteGeneratedFiles(directoryName, normalizerMetamodelName);
	}
	progress->setValue(100);
	progress->close();
	delete progress;
}
<commit_msg>fixed bug with working directory for generation<commit_after>#include "metaEditorSupportPlugin.h"

#include <QtCore/QProcess>
#include <QtGui/QApplication>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
#include <QtGui/QProgressBar>
#include <QtGui/QDesktopWidget>

#include "../../../qrkernel/settingsManager.h"
#include "../../../qrmc/metaCompiler.h"

#include "editorGenerator.h"
#include "xmlParser.h"

Q_EXPORT_PLUGIN2(metaEditorSupportPlugin, metaEditor::MetaEditorSupportPlugin)

using namespace qReal;
using namespace metaEditor;

MetaEditorSupportPlugin::MetaEditorSupportPlugin()
		: mGenerateEditorForQrxcAction(NULL)
		, mGenerateEditorWithQrmcAction(NULL)
		, mParseEditorXmlAction(NULL)
		, mRepoControlApi(NULL)
		, mCompilerSettingsPage(new PreferencesCompilerPage())
{
	mAppTranslator.load(":/metaEditorSupport_" + QLocale::system().name());
	QApplication::installTranslator(&mAppTranslator);
}

MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}

void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
	mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
	mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
	mRepoControlApi = &configurator.repoControlInterface();
}

QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
	mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
	ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
	connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));

	/*mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
	ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
	connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));

	mParseEditorXmlAction.setText(tr("Parse editor xml"));
	ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
	connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
	*/

	return QList<ActionInfo>() << generateEditorForQrxcActionInfo;
	//<< generateEditorWithQrmcActionInfo
	//<< parseEditorXmlActionInfo;
}

QPair<QString, PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
	return qMakePair(QObject::tr("Compiler"), static_cast<PreferencesPage*>(mCompilerSettingsPage));
}

void MetaEditorSupportPlugin::generateEditorForQrxc()
{
	EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());

	QDir dir(".");

	QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
	foreach (Id const &key, metamodelList.keys()) {
		QString const nameOfTheDirectory = metamodelList[key].first;
		QString const pathToQRealRoot = metamodelList[key].second;
		dir.mkpath(nameOfTheDirectory);
		QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);

		if (!mMainWindowInterface->errorReporter()->wereErrors()) {
			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
					QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
			{
				return;
			}
			loadNewEditor(nameOfTheDirectory, metamodelNames
					, SettingsManager::value("pathToQmake").toString()
					, SettingsManager::value("pathToMake").toString()
					, SettingsManager::value("pluginExtension").toString()
					, SettingsManager::value("prefix").toString());
		}
	}
	if (metamodelList.isEmpty()) {
		mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
	}
}

void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
	qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../qrmc", mRepoControlApi->workingFile());

	IdList const metamodels = mLogicalRepoApi->children(Id::rootId());

	QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QApplication::processEvents();
	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);

	int forEditor = 60 / metamodels.size();

	foreach (Id const &key, metamodels) {
		QString const objectType = key.element();
		if (objectType == "MetamodelDiagram") {
			QString name = mLogicalRepoApi->stringProperty(key, "name of the directory");
			if (QMessageBox::question(mMainWindowInterface->windowWidget()
					, tr("loading..")
					, QString(tr("Do you want to compile and load editor %1?")).arg(name)
					, QMessageBox::Yes, QMessageBox::No)
					== QMessageBox::No)
			{
				continue;
			}

			progress->setValue(5);

			if (!metaCompiler.compile(name)) { // generating source code for all metamodels
				QMessageBox::warning(mMainWindowInterface->windowWidget()
						, tr("error")
						, tr("Cannot generate source code for editor ") + name);
				continue;
			}
			progress->setValue(20);

			QProcess builder;
			builder.setWorkingDirectory("../qrmc/plugins");
			builder.start(SettingsManager::value("pathToQmake").toString());
			qDebug()  << "qmake";
			if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
				progress->setValue(40);

				builder.start(SettingsManager::value("pathToMake").toString());

				bool finished = builder.waitForFinished(100000);
				qDebug()  << "make";
				if (finished && (builder.exitCode() == 0)) {
					qDebug()  << "make ok";

					progress->setValue(progress->value() + forEditor / 2);

					QString normalizedName = name.at(0).toUpper() + name.mid(1);
					if (!name.isEmpty()) {
						if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
							QMessageBox::warning(mMainWindowInterface->windowWidget()
									, tr("error")
									, tr("cannot unload plugin ") + normalizedName);
							progress->close();
							delete progress;
							continue;
						}
					}

					QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
							+ name
							+ "."
							+ SettingsManager::value("pluginExtension").toString()
							;
					if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
						progress->setValue(progress->value() + forEditor / 2);
					}
				}
				progress->setValue(100);
			}
		}
	}
	if (progress->value() != 100) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
	}
	progress->setValue(100);
	progress->close();
	delete progress;
}

void MetaEditorSupportPlugin::parseEditorXml()
{
	if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
		return;
	}
	QDir dir(".");
	QString directoryName = ".";
	while (dir.cdUp()) {
		QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
		foreach (QFileInfo const &directory, infoList){
			if (directory.baseName() == "qrxml") {
				directoryName = directory.absolutePath() + "/qrxml";
			}
		}
	}
	QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
			, tr("Select xml file to parse")
			, directoryName
			, "XML files (*.xml)");

	if (fileName.isEmpty())
		return;

	XmlParser parser(*mLogicalRepoApi);

	parser.parseFile(fileName);

	parser.loadIncludeList(fileName);

	mMainWindowInterface->reinitModels();
}

void MetaEditorSupportPlugin::deleteGeneratedFiles(QString const &directoryName, QString const &fileBaseName)
{
	QFile filePro(directoryName + "/" + fileBaseName + ".pro");
	QFile fileXml(directoryName + "/" + fileBaseName + ".xml");
	filePro.remove();
	fileXml.remove();
}

void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
		, QPair<QString, QString> const &metamodelNames
		, QString const &commandFirst
		, QString const &commandSecond
		, QString const &extension
		, QString const &prefix)
{
	int const progressBarWidth = 240;
	int const progressBarHeight = 20;

	QString const metamodelName = metamodelNames.first;
	QString const normalizerMetamodelName = metamodelNames.second;

	if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
		return;
	}

	QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);

	QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
	progress->show();

	QApplication::processEvents();

	QRect const screenRect = qApp->desktop()->availableGeometry();
	progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
	progress->setFixedWidth(progressBarWidth);
	progress->setFixedHeight(progressBarHeight);
	progress->setRange(0, 100);
	progress->setValue(5);

	if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot unload plugin"));
		deleteGeneratedFiles(directoryName, normalizerMetamodelName);
		progress->close();
		delete progress;
		return;
	}

	progress->setValue(20);

	QProcess builder;
	builder.setWorkingDirectory(directoryName);
	builder.start(commandFirst);

	if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
		progress->setValue(60);
		builder.start(commandSecond);
		if (builder.waitForFinished() && (builder.exitCode() == 0)) {
			progress->setValue(80);

			if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
				progress->setValue(100);
			}
		}
	}

	if (progress->value() != 100) {
		QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
		deleteGeneratedFiles(directoryName, normalizerMetamodelName);
	}
	progress->setValue(100);
	progress->close();
	delete progress;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <exception>
#include <math.h>
#include <string.h>

#include "calculator.h"
using namespace std;

// ======================================================================================
int check(const char*& text, int value, bool invalid=false);
void check_calc();

/*
 * ======================================================================================
 * ======================================================================================
 * ======================================================================================
 */
template<typename T>
void check(const char* text, T value, bool invalid=false)
{
    Calculator<T, Parser<T>> calc;
    const char* text_ptr = text;
    try
    {
        auto result = calc.token_sequence(text);
        if (almost_equal(result, value) && !invalid)
            std::cout << "Passed: " << text_ptr << " = " << value << std::endl;
        else
            std::cout << "Failed: " << text_ptr << " = " << result << " (" << value << " expected)" << std::endl;
    }
    catch(char const* msg)
    {
        if (invalid)
            std::cout << "Passed: " << text_ptr << " Exception message: " << msg << std::endl;
        else
            std::cout << "Failed: " << text_ptr << " Exception message: " << msg << " (" << value << " expected)" <<std::endl;
    }
}
template <typename T>
void check_calc()
{
    check<T>("1+2", 3);
    check<T>("2+ 2", 4);
    check<T>("2 +2", 4);
    check<T>("2 + 2", 4);
    check<T>("2 +       2", 4);
    check<T>("2", 2);
    check<T>("-2", -2);
    check<T>("-2 - 2", -4);
    check<T>("2- 2", 0);
    check<T>("2- -  2", 4);
    check<T>("100 + 2", 102);
    check<T>("101 + 2", 103);
    check<T>("8 - 6 * 2 / 2", 2);
    check<T>("8 - 6 / 2 * 2", 2);
    check<T>("8 - 6 / 2 * - 2", 14);
    check<T>("2 + 3 * 4 - -2", 16);
    check<T>("2*-2", -4);
    check<T>("Pi", (T)constants["Pi"]);
    check<T>("Pi + e", (T)constants["Pi"] + (T)constants["e"]);
    check<T>("-Pi + 11", -(T)constants["Pi"] + 11);

    check<T>("(2)", 2);
    check<T>("(-2)", -2);
    check<T>("(e)", (T)constants["e"]);
    check<T>("(-e)", -(T)constants["e"]);

    check<T>("(e*2)+2", (T)constants["e"]* 2 + 2);
    check<T>("(e+2)+2", (T)constants["e"]+ 2 + 2);
    check<T>("e+(2)+2", (T)constants["e"]+ 2 + 2);
    check<T>("e+(2+2)", (T)constants["e"]+ 2 + 2);
    check<T>("e/(2)", (T)(constants["e"] / 2));
    check<T>("(2+e)/2", (T)((2 + constants["e"]) / 2));

    check<T>("1.5 + 1.5", (T)(1.5) + (T)(1.5));
    check<T>("1.511111", (T)(1.511111));
    check<T>("1.5 * 2", (T)(1.5) * 2);

    check<T>("2-+2", 0, true);
    check<T>("2++2", 0, true);
    check<T>("2 c 2", 0, true);
    check<T>("2 2", 0, true);
    check<T>("((2+2", 0, true);
    check<T>("(2)+2)", 0, true);
    check<T>("(2)+2/(2-2)", 0, true);
    check<T>(".2 + 2", 0, true);
    check<T>("(2 + 2", 0, true);
    check<T>(")2 + 2", 0, true);

    check<T>("2*+ 2", 0, true);
    check<T>("2+* 2", 0, true);
    check<T>("2..+* 2", 0, true);
}

/*
 * ======================================================================================
 * ======================================================================================
 * ======================================================================================
 */

int main(int argc, char* argv[])
{
    if (argc < 3)
    {
        cout << "Not enough arguments. Try: " << argv[0] << " <type> <expr>." << endl;
        cout << "Inner test begun..." << endl;
        check_calc<int>();
        check_calc<double>();
        check_calc<long>();
        return 0;
    }

    const char* type = argv[1];
    const char* text = argv[2];

    try
    {
        if(strcmp(type, "int") == 0)
        {
            Calculator<int, Parser<int>> calc;
            //cout << "Input text = " << text << endl;
            cout << calc.token_sequence(text) << endl;

        }
        else if(strcmp(type, "long") == 0)
        {
            Calculator<long, Parser<long>> calc;
            //cout << "Input text = " << text << endl;
            cout << calc.token_sequence(text) << endl;

        }
        else if(strcmp(type, "double") == 0)
        {
            Calculator<double, Parser<double>> calc;
            //cout << "Input text = " << text << endl;
            cout << calc.token_sequence(text) << endl;

        }
        else
        {
            throw "Unknown type.";
        }
    }
    catch(char const* msg)
    {
        std::cout << endl << "Exception message: " << msg << std::endl;
        return -2;
    }
    return 0;
}
<commit_msg>Update main.cpp<commit_after>#include <iostream>
#include <exception>
#include <math.h>
#include <string.h>

#include "calculator.hpp"
using namespace std;

// ======================================================================================
int check(const char*& text, int value, bool invalid=false);
void check_calc();

/*
 * ======================================================================================
 * ======================================================================================
 * ======================================================================================
 */
template<typename T>
void check(const char* text, T value, bool invalid=false)
{
    Calculator<T, Parser<T>> calc;
    const char* text_ptr = text;
    try
    {
        auto result = calc.token_sequence(text);
        if (almost_equal(result, value) && !invalid)
            std::cout << "Passed: " << text_ptr << " = " << value << std::endl;
        else
            std::cout << "Failed: " << text_ptr << " = " << result << " (" << value << " expected)" << std::endl;
    }
    catch(char const* msg)
    {
        if (invalid)
            std::cout << "Passed: " << text_ptr << " Exception message: " << msg << std::endl;
        else
            std::cout << "Failed: " << text_ptr << " Exception message: " << msg << " (" << value << " expected)" <<std::endl;
    }
}
template <typename T>
void check_calc()
{
    check<T>("1+2", 3);
    check<T>("2+ 2", 4);
    check<T>("2 +2", 4);
    check<T>("2 + 2", 4);
    check<T>("2 +       2", 4);
    check<T>("2", 2);
    check<T>("-2", -2);
    check<T>("-2 - 2", -4);
    check<T>("2- 2", 0);
    check<T>("2- -  2", 4);
    check<T>("100 + 2", 102);
    check<T>("101 + 2", 103);
    check<T>("8 - 6 * 2 / 2", 2);
    check<T>("8 - 6 / 2 * 2", 2);
    check<T>("8 - 6 / 2 * - 2", 14);
    check<T>("2 + 3 * 4 - -2", 16);
    check<T>("2*-2", -4);
    check<T>("Pi", (T)constants["Pi"]);
    check<T>("Pi + e", (T)constants["Pi"] + (T)constants["e"]);
    check<T>("-Pi + 11", -(T)constants["Pi"] + 11);

    check<T>("(2)", 2);
    check<T>("(-2)", -2);
    check<T>("(e)", (T)constants["e"]);
    check<T>("(-e)", -(T)constants["e"]);

    check<T>("(e*2)+2", (T)constants["e"]* 2 + 2);
    check<T>("(e+2)+2", (T)constants["e"]+ 2 + 2);
    check<T>("e+(2)+2", (T)constants["e"]+ 2 + 2);
    check<T>("e+(2+2)", (T)constants["e"]+ 2 + 2);
    check<T>("e/(2)", (T)(constants["e"] / 2));
    check<T>("(2+e)/2", (T)((2 + constants["e"]) / 2));

    check<T>("1.5 + 1.5", (T)(1.5) + (T)(1.5));
    check<T>("1.511111", (T)(1.511111));
    check<T>("1.5 * 2", (T)(1.5) * 2);

    check<T>("2-+2", 0, true);
    check<T>("2++2", 0, true);
    check<T>("2 c 2", 0, true);
    check<T>("2 2", 0, true);
    check<T>("((2+2", 0, true);
    check<T>("(2)+2)", 0, true);
    check<T>("(2)+2/(2-2)", 0, true);
    check<T>(".2 + 2", 0, true);
    check<T>("(2 + 2", 0, true);
    check<T>(")2 + 2", 0, true);

    check<T>("2*+ 2", 0, true);
    check<T>("2+* 2", 0, true);
    check<T>("2..+* 2", 0, true);
}

/*
 * ======================================================================================
 * ======================================================================================
 * ======================================================================================
 */

int main(int argc, char* argv[])
{
    if (argc < 3)
    {
        cout << "Not enough arguments. Try: " << argv[0] << " <type> <expr>." << endl;
        cout << "Inner test begun..." << endl;
        check_calc<int>();
        check_calc<double>();
        check_calc<long>();
        return 0;
    }

    const char* type = argv[1];
    const char* text = argv[2];

    try
    {
        if(strcmp(type, "int") == 0)
        {
            Calculator<int, Parser<int>> calc;
            //cout << "Input text = " << text << endl;
            cout << calc.token_sequence(text) << endl;

        }
        else if(strcmp(type, "long") == 0)
        {
            Calculator<long, Parser<long>> calc;
            //cout << "Input text = " << text << endl;
            cout << calc.token_sequence(text) << endl;

        }
        else if(strcmp(type, "double") == 0)
        {
            Calculator<double, Parser<double>> calc;
            //cout << "Input text = " << text << endl;
            cout << calc.token_sequence(text) << endl;

        }
        else
        {
            throw "Unknown type.";
        }
    }
    catch(char const* msg)
    {
        std::cout << endl << "Exception message: " << msg << std::endl;
        return -2;
    }
    return 0;
}
<|endoftext|>


<commit_before>
#include "manu343726/turbo_core/turbo_core.hpp"
#include <tick/requires.h>

#include <iostream>

template<typename metatype, typename ctor, typename value = ctor>
struct TypeDecorator
{
	using Type = metatype;
	using Ctor = ctor;
	using Value = value;
};

template<typename Type, typename BoxedValue>
struct is_a : std::false_type {};

template<typename Type, typename Ctor, typename Value>
struct is_a<Type, TypeDecorator<Type,Ctor,Value>> : std::true_type {};

template<typename Ctor, typename BoxedValue>
struct constructed_by : std::false_type {};

template<typename Type, typename Ctor, typename Value>
struct constructed_by<Ctor, TypeDecorator<Type,Ctor,Value>> : std::true_type {};

struct Maybe
{
	struct Just
	{
		template<typename T>
		struct apply
		{
			using type = TypeDecorator<Maybe, Just, T>;
		};
	};

	struct Nothing
	{
		using type = TypeDecorator<Maybe, Nothing>;
	};
};

#define IS_A(...) TICK_CLASS_REQUIRES(is_a<__VA_ARGS__>())
#define MATCHES(...) TICK_CLASS_REQUIRES(constructed_by<__VA_ARGS__>())

struct is_nothing
{
	template<typename T, typename = void>
	struct apply
	{
		typedef struct error {} type;
	};

	template<typename T>
	struct apply<T, MATCHES(Maybe::Just, T)>
	{
		using type = std::false_type;
	};

	template<typename T>
	struct apply<T, MATCHES(Maybe::Nothing, T)>
	{
		using type = std::true_type;
	};
};

using maybe_int = $(Maybe::Just, int);

int main()
{
	std::cout << tml::to_string<maybe_int>() << std::endl;
	std::cout << tml::to_string<$(is_nothing, maybe_int)>() << std::endl;
}<commit_msg>Currying as closure<commit_after>
#include "manu343726/turbo_core/turbo_core.hpp"
#include <tick/requires.h>

#include <iostream>

template<typename metatype, typename ctor, typename value = ctor>
struct TypeDecorator
{
	using Type = metatype;
	using Ctor = ctor;
	using Value = value;
};

template<typename Type, typename BoxedValue>
struct is_a : std::false_type {};

template<typename Type, typename Ctor, typename Value>
struct is_a<Type, TypeDecorator<Type,Ctor,Value>> : std::true_type {};

template<typename Ctor, typename BoxedValue>
struct constructed_by : std::false_type {};

template<typename Type, typename Ctor, typename Value>
struct constructed_by<Ctor, TypeDecorator<Type,Ctor,Value>> : std::true_type {};

struct Maybe
{
	struct Just
	{
		template<typename T>
		struct apply
		{
			using type = TypeDecorator<Maybe, Just, T>;
		};
	};

	struct Nothing
	{
		using type = TypeDecorator<Maybe, Nothing>;
	};
};

#define IS_A(...) TICK_CLASS_REQUIRES(is_a<__VA_ARGS__>())
#define MATCHES(...) TICK_CLASS_REQUIRES(constructed_by<__VA_ARGS__>())

struct is_nothing
{
	template<typename T, typename = void>
	struct apply
	{
		typedef struct error {} type;
	};

	template<typename T>
	struct apply<T, MATCHES(Maybe::Just, T)>
	{
		using type = std::false_type;
	};

	template<typename T>
	struct apply<T, MATCHES(Maybe::Nothing, T)>
	{
		using type = std::true_type;
	};
};

using maybe_int = $(Maybe::Just, int);

struct f
{
	template<typename... Head>
	struct apply
	{
		struct type
		{
			template<typename... Tail>
			using apply = f::apply<Head...,Tail...>;
		};
	};

	template<typename A, typename B, typename C>
	struct apply<A, B, C>
	{
		using type = C;
	};
};

using a = $(f, int);
using b = $(a, char);
using c = $(b, bool);

int main()
{
	std::cout << tml::to_string<a>() << std::endl;
	std::cout << tml::to_string<b>() << std::endl;
	std::cout << tml::to_string<c>() << std::endl;
}

<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

void test_is_same_dense()
{
  typedef Matrix<double,Dynamic,Dynamic,ColMajor> ColMatrixXd;
  ColMatrixXd m1(10,10);
  Ref<ColMatrixXd> ref_m1(m1);
  Ref<const ColMatrixXd> const_ref_m1(m1);
  VERIFY(is_same_dense(m1,m1));
  VERIFY(is_same_dense(m1,ref_m1));
  VERIFY(is_same_dense(const_ref_m1,m1));
  VERIFY(is_same_dense(const_ref_m1,ref_m1));

  VERIFY(is_same_dense(m1.block(0,0,m1.rows(),m1.cols()),m1));
  VERIFY(!is_same_dense(m1.row(0),m1.col(0)));

  Ref<const ColMatrixXd> const_ref_m1_row(m1.row(1));
  VERIFY(!is_same_dense(m1.row(1),const_ref_m1_row));

  Ref<const ColMatrixXd> const_ref_m1_col(m1.col(1));
  VERIFY(is_same_dense(m1.col(1),const_ref_m1_col));
}
<commit_msg>Fix unit test.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2015 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "main.h"

using internal::is_same_dense;

void test_is_same_dense()
{
  typedef Matrix<double,Dynamic,Dynamic,ColMajor> ColMatrixXd;
  ColMatrixXd m1(10,10);
  Ref<ColMatrixXd> ref_m1(m1);
  Ref<const ColMatrixXd> const_ref_m1(m1);
  VERIFY(is_same_dense(m1,m1));
  VERIFY(is_same_dense(m1,ref_m1));
  VERIFY(is_same_dense(const_ref_m1,m1));
  VERIFY(is_same_dense(const_ref_m1,ref_m1));

  VERIFY(is_same_dense(m1.block(0,0,m1.rows(),m1.cols()),m1));
  VERIFY(!is_same_dense(m1.row(0),m1.col(0)));

  Ref<const ColMatrixXd> const_ref_m1_row(m1.row(1));
  VERIFY(!is_same_dense(m1.row(1),const_ref_m1_row));

  Ref<const ColMatrixXd> const_ref_m1_col(m1.col(1));
  VERIFY(is_same_dense(m1.col(1),const_ref_m1_col));
}
<|endoftext|>


<commit_before>#pragma once
// math_frac.hpp: fractional functions for posits
//
// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.

namespace sw {
	namespace unum {

		// the current shims are NON-COMPLIANT with the posit standard, which says that every function must be
		// correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results.

		template<size_t nbits, size_t es>
		posit<nbits,es> frac(posit<nbits,es> x) {
			return posit<nbits,es>(double(x)-long(x));
		}

	}  // namespace unum

}  // namespace sw
<commit_msg>WIP: additional mathematical function shims<commit_after>#pragma once
// math_frac.hpp: fractional functions for posits
//
// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.

namespace sw {
	namespace unum {

		// the current shims are NON-COMPLIANT with the posit standard, which says that every function must be
		// correctly rounded for every input value. Anything less sacrifices bitwise reproducibility of results.

		template<size_t nbits, size_t es>
		posit<nbits,es> fmod(posit<nbits,es> x, posit<nbits,es> y) {
			return posit<nbits,es>(std::fmod(double(x), double(y)));
		}

		template<size_t nbits, size_t es>
		posit<nbits,es> remainder(posit<nbits,es> x, posit<nbits,es> y) {
			return posit<nbits,es>(std::remainder(double(x), double(y)));
		}

		template<size_t nbits, size_t es>
		posit<nbits,es> frac(posit<nbits,es> x) {
			return posit<nbits,es>(double(x)-long(x));
		}

	}  // namespace unum

}  // namespace sw
<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 11316 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "QmitkDialogBar.h"

#include "mitkProperties.h"

#include <qgroupbox.h>
#include <qlayout.h>
#include <qfont.h>
#include <qobjectlist.h>

QmitkDialogBar
::QmitkDialogBar(
  const char *caption, QObject *parent, const char *name, QmitkStdMultiWidget *multiWidget,
  mitk::DataTreeIteratorBase *dataIt )
: QmitkBaseFunctionalityComponent( parent, name, dataIt ),
  m_GroupBox( NULL ),
  m_MultiWidget( multiWidget ),
  m_Caption( caption )
{
}

QmitkDialogBar
::~QmitkDialogBar()
{
}

QWidget *
QmitkDialogBar
::CreateControlWidget( QWidget *parent )
{
  m_GroupBox = new QGroupBox( parent );
  m_GroupBox->setColumnLayout( 0, Qt::Vertical );
  m_GroupBox->layout()->setSpacing( 6 );
  m_GroupBox->setMargin( 11 );
  m_GroupBox->setTitle( m_Caption );

  QWidget *dialogBar = this->CreateDialogBar( m_GroupBox );

  QFont captionFont = m_GroupBox->font();
  captionFont.setBold( true );
  m_GroupBox->setFont( captionFont );

  QObjectList* childList = m_GroupBox->queryList( "QWidget" );
  QObjectListIt childIter( *childList );
  QObject* child;
  QWidget* widget;
  while ( (child = childIter.current()) )
  {
    if (child->inherits("QWidget"))
    {
      widget = static_cast<QWidget*>( child );
      widget->unsetFont();
      QFont normalFont = widget->font();
      normalFont.setBold( false );
      widget->setFont( normalFont );
    }

    ++childIter;
  }

  QGridLayout *grid = new QGridLayout( m_GroupBox->layout(), 1, 1, 2 );
  grid->setAlignment( Qt::AlignTop );
  grid->addWidget( dialogBar, 0, 0 );

  return m_GroupBox;
}

void
QmitkDialogBar
::ToggleVisible( bool visible )
{
  if ( m_GroupBox )
  {
    m_GroupBox->setHidden( !visible );
  }

  // Reflect new visible state in global preferences
  if ( m_GlobalOptions )
  {
    QString dialogBarStateName = "DialogBar " + m_Caption + " active";

    m_GlobalOptions->SetProperty(
      dialogBarStateName, new mitk::BoolProperty( visible ) );
  }
}

const QString &
QmitkDialogBar
::GetCaption() const
{
  return m_Caption;
}

QmitkStdMultiWidget *
QmitkDialogBar
::GetMultiWidget() const
{
  return m_MultiWidget;
}

void
QmitkDialogBar
::SetGlobalOptions( mitk::PropertyList::Pointer options )
{
  m_GlobalOptions = options;
}
<commit_msg>ENH (#876): Hide DialogBar by default right after instantiation<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 11316 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "QmitkDialogBar.h"

#include "mitkProperties.h"

#include <qgroupbox.h>
#include <qlayout.h>
#include <qfont.h>
#include <qobjectlist.h>

QmitkDialogBar
::QmitkDialogBar(
  const char *caption, QObject *parent, const char *name, QmitkStdMultiWidget *multiWidget,
  mitk::DataTreeIteratorBase *dataIt )
: QmitkBaseFunctionalityComponent( parent, name, dataIt ),
  m_GroupBox( NULL ),
  m_MultiWidget( multiWidget ),
  m_Caption( caption )
{
}

QmitkDialogBar
::~QmitkDialogBar()
{
}

QWidget *
QmitkDialogBar
::CreateControlWidget( QWidget *parent )
{
  m_GroupBox = new QGroupBox( parent );
  m_GroupBox->setHidden( true );

  m_GroupBox->setColumnLayout( 0, Qt::Vertical );
  m_GroupBox->layout()->setSpacing( 6 );
  m_GroupBox->setMargin( 11 );
  m_GroupBox->setTitle( m_Caption );

  QWidget *dialogBar = this->CreateDialogBar( m_GroupBox );

  QFont captionFont = m_GroupBox->font();
  captionFont.setBold( true );
  m_GroupBox->setFont( captionFont );

  QObjectList* childList = m_GroupBox->queryList( "QWidget" );
  QObjectListIt childIter( *childList );
  QObject* child;
  QWidget* widget;
  while ( (child = childIter.current()) )
  {
    if (child->inherits("QWidget"))
    {
      widget = static_cast<QWidget*>( child );
      widget->unsetFont();
      QFont normalFont = widget->font();
      normalFont.setBold( false );
      widget->setFont( normalFont );
    }

    ++childIter;
  }

  QGridLayout *grid = new QGridLayout( m_GroupBox->layout(), 1, 1, 2 );
  grid->setAlignment( Qt::AlignTop );
  grid->addWidget( dialogBar, 0, 0 );

  return m_GroupBox;
}

void
QmitkDialogBar
::ToggleVisible( bool visible )
{
  if ( m_GroupBox )
  {
    m_GroupBox->setHidden( !visible );
  }

  // Reflect new visible state in global preferences
  if ( m_GlobalOptions )
  {
    QString dialogBarStateName = "DialogBar " + m_Caption + " active";

    m_GlobalOptions->SetProperty(
      dialogBarStateName, new mitk::BoolProperty( visible ) );
  }
}

const QString &
QmitkDialogBar
::GetCaption() const
{
  return m_Caption;
}

QmitkStdMultiWidget *
QmitkDialogBar
::GetMultiWidget() const
{
  return m_MultiWidget;
}

void
QmitkDialogBar
::SetGlobalOptions( mitk::PropertyList::Pointer options )
{
  m_GlobalOptions = options;
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "Filterflipuv.h"
#include "Pixeldefs.h"

#include <assert.h>

namespace avg {

FilterFlipUV::FilterFlipUV()
  : Filter()
{
}

FilterFlipUV::~FilterFlipUV()
{

}

void FilterFlipUV::applyInPlace(BitmapPtr pBmp) const
{
    PixelFormat PF = pBmp->getPixelFormat();
    assert(pBmp->getPixelFormat() == YCbCr422);

    for (int y = 0; y < pBmp->getSize().y; y++) {
        unsigned char * pLine = pBmp->getPixels()+y*pBmp->getStride();
        for (int x = 0; x < pBmp->getSize().x/2; x++) {
                unsigned char tmp = pLine[x*4+1];
                pLine[x*4+1] = pLine[x*4+3];
                pLine[x*4+3] = tmp;
            }
    }
}

} // namespace
<commit_msg>Fixed compiler warning.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "Filterflipuv.h"
#include "Pixeldefs.h"

#include <assert.h>

namespace avg {

FilterFlipUV::FilterFlipUV()
  : Filter()
{
}

FilterFlipUV::~FilterFlipUV()
{

}

void FilterFlipUV::applyInPlace(BitmapPtr pBmp) const
{
    assert(pBmp->getPixelFormat() == YCbCr422);

    for (int y = 0; y < pBmp->getSize().y; y++) {
        unsigned char * pLine = pBmp->getPixels()+y*pBmp->getStride();
        for (int x = 0; x < pBmp->getSize().x/2; x++) {
                unsigned char tmp = pLine[x*4+1];
                pLine[x*4+1] = pLine[x*4+3];
                pLine[x*4+3] = tmp;
            }
    }
}

} // namespace
<|endoftext|>


<commit_before>#include "SqlBuilderBase.h"

#include <QSqlError>
#include <QSqlRecord>
#include <QString>
#include <QSqlDriver>

#include "ClassMapBase.h"
#include "ConfigurationMap.h"
#include "QueryModels/DeleteQueryModel.h"
#include "QueryModels/InsertQueryModel.h"
#include "QueryModels/SelectQueryModel.h"
#include "QueryModels/UpdateFieldQueryModel.h"
#include "QueryModels/UpdateQueryModel.h"

namespace QtOrm {
namespace Sql {
using namespace Config;

SqlBuilderBase::SqlBuilderBase(QObject *parent) : QObject(parent) {
}

QSqlQuery SqlBuilderBase::selectQuery() {
  queryModel = getQueryModel(QueryModelType::Select);

  QSqlQuery query(database);
  query.prepare(queryModel->getSqlText());

  QSharedPointer<SelectQueryModel> selectQueryModel = queryModel.dynamicCast<SelectQueryModel>();
  QSharedPointer<GroupConditions> sharedConditions = QSharedPointer<GroupConditions>::create(conditions);
  bindValues(query, sharedConditions, selectQueryModel->getConditionPlaceholder());
  selectQueryModel->clearPlaceHolders();

  return query;
}

QString SqlBuilderBase::getPlaceHolder(const QString &param) {
  return QString(":%1").arg(param);
}

void SqlBuilderBase::bindValues(QSqlQuery &query, const QSharedPointer<GroupConditions> &conditions,
                                const QMap<QSharedPointer<Condition>, QString> &placeHolders) {
  for (QSharedPointer<Condition> &condition : conditions->getConditions()) {
    if (!condition->getValues().isEmpty()) {
      QString placeHolder = placeHolders[condition];

      QList<Operation> operations{Operation::Between, Operation::In};
      //      bool betweenOrIn = condition.dynamicCast<ConditionBetween>() || condition.dynamicCast<ConditionIn>();

      bool betweenOrIn = operations.contains(condition->getOperation());

      if (betweenOrIn) {
        QString almostReadyPlaceHolder = getPlaceHolder(placeHolder);
        int i = 1;
        for (QVariant &value : condition->getValues()) {
          QString valuePlaceholder = QString("%1_%2").arg(almostReadyPlaceHolder).arg(i);
          query.bindValue(valuePlaceholder, value);
          i++;
        }
      } else {
        query.bindValue(getPlaceHolder(placeHolder), condition->getValues().first());
      }

      for (QSharedPointer<GroupConditions> &g : conditions->getGroups()) {
        bindValues(query, g, placeHolders);
      }
    }
  }
}

QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel(QueryModelType queryType) {
  QString className = classBase->getClassName();
  if (queryCache) {
    if (QSharedPointer<QueryModel> model = queryCache->getModel(queryType, className, propertyName)) {
      if (queryType == QueryModelType::Select) {
        QSharedPointer<SelectQueryModel> selectModel = model.dynamicCast<SelectQueryModel>();
        selectModel->setConditions(conditions);
        selectModel->setOrderColumns(orderBy);
      }
      return model;
    }
  }

  return createModelAndAddToCache(queryType);
}

QSharedPointer<QueryModel> SqlBuilderBase::createModelAndAddToCache(QueryModelType queryType) {
  QString className = classBase->getClassName();
  QSharedPointer<QueryModel> newModel = createModel(queryType);
  if (queryCache) {
    queryCache->addModel(queryType, newModel, className, propertyName);
  }

  return newModel;
}

QSharedPointer<QueryModel> SqlBuilderBase::createModel(QueryModelType queryType) {
  QSharedPointer<QueryModel> result;

  switch (queryType) {
  case QueryModelType::Select: {
    QSharedPointer<SelectQueryModel> selectModel = QSharedPointer<SelectQueryModel>::create();
    selectModel->setClassBase(classBase);
    selectModel->buildModel();
    selectModel->setConditions(conditions);
    selectModel->setOrderColumns(orderBy);
    result = selectModel;
    break;
  }
  case QueryModelType::Insert: {
    QSharedPointer<InsertQueryModel> insertModel = QSharedPointer<InsertQueryModel>::create();
    insertModel->setClassBase(classBase);
    insertModel->setHasLastInsertedIdFeature(hasLastInsertedIdFeature());
    insertModel->buildModel();
    result = insertModel;
    break;
  }
  case QueryModelType::Update: {
    QSharedPointer<UpdateQueryModel> updateModel = QSharedPointer<UpdateQueryModel>::create();
    updateModel->setClassBase(classBase);
    updateModel->buildModel();
    result = updateModel;
    break;
  }
  case QueryModelType::UpdateColumn: {
    QSharedPointer<UpdateFieldQueryModel> updateColumnModel = QSharedPointer<UpdateFieldQueryModel>::create();
    updateColumnModel->setClassBase(classBase);
    updateColumnModel->setPropertyName(propertyName);
    updateColumnModel->buildModel();
    result = updateColumnModel;
    break;
  }
  case QueryModelType::Delete: {
    QSharedPointer<DeleteQueryModel> deleteModel = QSharedPointer<DeleteQueryModel>::create();
    deleteModel->setClassBase(classBase);
    deleteModel->buildModel();
    result = deleteModel;
    break;
  }
    // throw exception
  }

  return result;
}

bool SqlBuilderBase::hasLastInsertedIdFeature() {
  return database.driver()->hasFeature(QSqlDriver::LastInsertId) && database.driverName() != "QPSQL";
}

QList<OrderColumn> SqlBuilderBase::getOrderBy() const {
  return orderBy;
}

void SqlBuilderBase::setOrderBy(const QList<OrderColumn> &value) {
  orderBy = value;
}

QSharedPointer<QueryCache> SqlBuilderBase::getQueryCache() const {
  return queryCache;
}

void SqlBuilderBase::setQueryCache(QSharedPointer<QueryCache> value) {
  queryCache = value;
}

QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel() const {
  return queryModel;
}

QSqlDatabase SqlBuilderBase::getDatabase() const {
  return database;
}

void SqlBuilderBase::setDatabase(const QSqlDatabase &value) {
  database = value;
}

QSharedPointer<QObject> SqlBuilderBase::getObject() const {
  return object;
}

void SqlBuilderBase::setObject(QSharedPointer<QObject> value) {
  object = value;
}

QSharedPointer<ClassMapBase> SqlBuilderBase::getClassBase() const {
  return classBase;
}

void SqlBuilderBase::setClassBase(QSharedPointer<ClassMapBase> value) {
  classBase = value;
}

GroupConditions SqlBuilderBase::getConditions() const {
  return conditions;
}

void SqlBuilderBase::setConditions(const GroupConditions &value) {
  conditions = value;
}
}
}
<commit_msg>deep parse for bind values<commit_after>#include "SqlBuilderBase.h"

#include <QSqlError>
#include <QSqlRecord>
#include <QString>
#include <QSqlDriver>

#include "ClassMapBase.h"
#include "ConfigurationMap.h"
#include "QueryModels/DeleteQueryModel.h"
#include "QueryModels/InsertQueryModel.h"
#include "QueryModels/SelectQueryModel.h"
#include "QueryModels/UpdateFieldQueryModel.h"
#include "QueryModels/UpdateQueryModel.h"

namespace QtOrm {
namespace Sql {
using namespace Config;

SqlBuilderBase::SqlBuilderBase(QObject *parent) : QObject(parent) {
}

QSqlQuery SqlBuilderBase::selectQuery() {
  queryModel = getQueryModel(QueryModelType::Select);

  QSqlQuery query(database);
  query.prepare(queryModel->getSqlText());

  QSharedPointer<SelectQueryModel> selectQueryModel = queryModel.dynamicCast<SelectQueryModel>();
  QSharedPointer<GroupConditions> sharedConditions = QSharedPointer<GroupConditions>::create(conditions);
  bindValues(query, sharedConditions, selectQueryModel->getConditionPlaceholder());
  selectQueryModel->clearPlaceHolders();

  return query;
}

QString SqlBuilderBase::getPlaceHolder(const QString &param) {
  return QString(":%1").arg(param);
}

void SqlBuilderBase::bindValues(QSqlQuery &query, const QSharedPointer<GroupConditions> &conditions,
                                const QMap<QSharedPointer<Condition>, QString> &placeHolders) {
  for (QSharedPointer<Condition> &condition : conditions->getConditions()) {
    if (!condition->getValues().isEmpty()) {
      QString placeHolder = placeHolders[condition];

      QList<Operation> operations{Operation::Between, Operation::In};
      //      bool betweenOrIn = condition.dynamicCast<ConditionBetween>() || condition.dynamicCast<ConditionIn>();

      bool betweenOrIn = operations.contains(condition->getOperation());

      if (betweenOrIn) {
        QString almostReadyPlaceHolder = getPlaceHolder(placeHolder);
        int i = 1;
        for (QVariant &value : condition->getValues()) {
          QString valuePlaceholder = QString("%1_%2").arg(almostReadyPlaceHolder).arg(i);
          query.bindValue(valuePlaceholder, value);
          i++;
        }
      } else {
        query.bindValue(getPlaceHolder(placeHolder), condition->getValues().first());
      }
    }
  }

  for (QSharedPointer<GroupConditions> &g : conditions->getGroups()) {
    bindValues(query, g, placeHolders);
  }
}

QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel(QueryModelType queryType) {
  QString className = classBase->getClassName();
  if (queryCache) {
    if (QSharedPointer<QueryModel> model = queryCache->getModel(queryType, className, propertyName)) {
      if (queryType == QueryModelType::Select) {
        QSharedPointer<SelectQueryModel> selectModel = model.dynamicCast<SelectQueryModel>();
        selectModel->setConditions(conditions);
        selectModel->setOrderColumns(orderBy);
      }
      return model;
    }
  }

  return createModelAndAddToCache(queryType);
}

QSharedPointer<QueryModel> SqlBuilderBase::createModelAndAddToCache(QueryModelType queryType) {
  QString className = classBase->getClassName();
  QSharedPointer<QueryModel> newModel = createModel(queryType);
  if (queryCache) {
    queryCache->addModel(queryType, newModel, className, propertyName);
  }

  return newModel;
}

QSharedPointer<QueryModel> SqlBuilderBase::createModel(QueryModelType queryType) {
  QSharedPointer<QueryModel> result;

  switch (queryType) {
  case QueryModelType::Select: {
    QSharedPointer<SelectQueryModel> selectModel = QSharedPointer<SelectQueryModel>::create();
    selectModel->setClassBase(classBase);
    selectModel->buildModel();
    selectModel->setConditions(conditions);
    selectModel->setOrderColumns(orderBy);
    result = selectModel;
    break;
  }
  case QueryModelType::Insert: {
    QSharedPointer<InsertQueryModel> insertModel = QSharedPointer<InsertQueryModel>::create();
    insertModel->setClassBase(classBase);
    insertModel->setHasLastInsertedIdFeature(hasLastInsertedIdFeature());
    insertModel->buildModel();
    result = insertModel;
    break;
  }
  case QueryModelType::Update: {
    QSharedPointer<UpdateQueryModel> updateModel = QSharedPointer<UpdateQueryModel>::create();
    updateModel->setClassBase(classBase);
    updateModel->buildModel();
    result = updateModel;
    break;
  }
  case QueryModelType::UpdateColumn: {
    QSharedPointer<UpdateFieldQueryModel> updateColumnModel = QSharedPointer<UpdateFieldQueryModel>::create();
    updateColumnModel->setClassBase(classBase);
    updateColumnModel->setPropertyName(propertyName);
    updateColumnModel->buildModel();
    result = updateColumnModel;
    break;
  }
  case QueryModelType::Delete: {
    QSharedPointer<DeleteQueryModel> deleteModel = QSharedPointer<DeleteQueryModel>::create();
    deleteModel->setClassBase(classBase);
    deleteModel->buildModel();
    result = deleteModel;
    break;
  }
    // throw exception
  }

  return result;
}

bool SqlBuilderBase::hasLastInsertedIdFeature() {
  return database.driver()->hasFeature(QSqlDriver::LastInsertId) && database.driverName() != "QPSQL";
}

QList<OrderColumn> SqlBuilderBase::getOrderBy() const {
  return orderBy;
}

void SqlBuilderBase::setOrderBy(const QList<OrderColumn> &value) {
  orderBy = value;
}

QSharedPointer<QueryCache> SqlBuilderBase::getQueryCache() const {
  return queryCache;
}

void SqlBuilderBase::setQueryCache(QSharedPointer<QueryCache> value) {
  queryCache = value;
}

QSharedPointer<QueryModel> SqlBuilderBase::getQueryModel() const {
  return queryModel;
}

QSqlDatabase SqlBuilderBase::getDatabase() const {
  return database;
}

void SqlBuilderBase::setDatabase(const QSqlDatabase &value) {
  database = value;
}

QSharedPointer<QObject> SqlBuilderBase::getObject() const {
  return object;
}

void SqlBuilderBase::setObject(QSharedPointer<QObject> value) {
  object = value;
}

QSharedPointer<ClassMapBase> SqlBuilderBase::getClassBase() const {
  return classBase;
}

void SqlBuilderBase::setClassBase(QSharedPointer<ClassMapBase> value) {
  classBase = value;
}

GroupConditions SqlBuilderBase::getConditions() const {
  return conditions;
}

void SqlBuilderBase::setConditions(const GroupConditions &value) {
  conditions = value;
}
}
}
<|endoftext|>


<commit_before>#include "BVSExampleModule.h"

// This is your module's constructor.
// Please do not change its signature as it is called by the framework (so the
// framework actually creates your module) and the framework assigns the unique
// identifier and gives you access to the its config.
// However, you might use it to create your data structures etc., or you can use
// the onLoad() and onClose() functions, just be consistent in order to avoid
// weird errors.
BVSExampleModule::BVSExampleModule(const std::string id, const BVS::Config& config)
	: BVS::Module()
	, id(id)
	, logger(id)
	, config(config)
	, input("testIn", BVS::ConnectorType::INPUT)
	, output("testOut", BVS::ConnectorType::OUTPUT)
{

}

// This is your module's destructor.
// See the constructor for more info.
BVSExampleModule::~BVSExampleModule()
{

}

// Executed at module load.
BVS::Status BVSExampleModule::onLoad()
{
	LOG(2, "loaded BVSExampleModule module!");

	return BVS::Status::OK;
}

// UNUSED
BVS::Status BVSExampleModule::preExecute()
{
	return BVS::Status::OK;
}

// Put all your work here.
BVS::Status BVSExampleModule::execute()
{
	LOG(2, "Execution of " << id << "!");

	return BVS::Status::OK;
}

// UNUSED
BVS::Status BVSExampleModule::postExecute()
{
	return BVS::Status::OK;
}

BVS::Status BVSExampleModule::debugDisplay()
{
	return BVS::Status::OK;
}

// Executed at module unload.
BVS::Status BVSExampleModule::onClose()
{
	return BVS::Status::OK;
}

// This function is called by the framework upon creating a module instance of
// this class. It creates the module and registers it within the framework.
// DO NOT CHANGE OR DELETE
extern "C" {
	// register with framework
	int bvsRegisterModule(std::string id, BVS::Config& config)
	{
		registerModule(id, new BVSExampleModule(id, config));

		return 0;
	}
}

<commit_msg>namespace: fix missing module stuff<commit_after>#include "BVSExampleModule.h"

// This is your module's constructor.
// Please do not change its signature as it is called by the framework (so the
// framework actually creates your module) and the framework assigns the unique
// identifier and gives you access to the its config.
// However, you might use it to create your data structures etc., or you can use
// the onLoad() and onClose() functions, just be consistent in order to avoid
// weird errors.
BVSExampleModule::BVSExampleModule(const std::string id, const BVS::Config& config)
	: BVS::Module()
	, id(id)
	, logger(id)
	, config(config)
	, input("testIn", BVS::ConnectorType::INPUT)
	, output("testOut", BVS::ConnectorType::OUTPUT)
{

}

// This is your module's destructor.
// See the constructor for more info.
BVSExampleModule::~BVSExampleModule()
{

}

// Put all your work here.
BVS::Status BVSExampleModule::execute()
{
	LOG(2, "Execution of " << id << "!");

	return BVS::Status::OK;
}

// UNUSED
BVS::Status BVSExampleModule::debugDisplay()
{
	return BVS::Status::OK;
}

// This function is called by the framework upon creating a module instance of
// this class. It creates the module and registers it within the framework.
// DO NOT CHANGE OR DELETE
extern "C" {
	// register with framework
	int bvsRegisterModule(std::string id, BVS::Config& config)
	{
		registerModule(id, new BVSExampleModule(id, config));

		return 0;
	}
}

<|endoftext|>