text stringlengths 54 60.6k |
|---|
<commit_before>#ifndef HLL_HEADER_ONLY
# include "hll.h"
#endif
#include <stdexcept>
#include <cstring>
#include <numeric>
#include <thread>
#include <cinttypes>
#include <atomic>
#include "kthread.h"
namespace hll {
#if !NDEBUG
template<typename T>
std::string arrstr(T it, T it2) {
std::string ret;
for(auto i(it); i != it2; ++i) ret += "," + std::to_string(*i);
return ret;
}
#endif
_STORAGE_ void hll_t::sum() {
using detail::SIMDHolder;
uint64_t counts[64]{0};
SIMDHolder tmp, *p((SIMDHolder *)core_.data()), *pend((SIMDHolder *)&*core_.end());
do {
tmp = *p++;
tmp.inc_counts(counts);
} while(p < pend);
value_ = detail::calculate_estimate(counts, use_ertl_, m(), np_, alpha());
is_calculated_ = 1;
}
template<typename CoreType>
struct parsum_data_t {
std::atomic<uint64_t> *counts_; // Array decayed to pointer.
const CoreType &core_;
const uint64_t l_;
const uint64_t pb_; // Per-batch
};
template<typename CoreType>
_STORAGE_ void parsum_helper(void *data_, long index, int tid) {
using detail::SIMDHolder;
parsum_data_t<CoreType> &data(*(parsum_data_t<CoreType> *)data_);
uint64_t local_counts[64]{0};
SIMDHolder tmp, *p((SIMDHolder *)&data.core_[index * data.pb_]),
*pend((SIMDHolder *)&data.core_[std::min(data.l_, (index+1) * data.pb_)]);
do {
tmp = *p++;
tmp.inc_counts(local_counts);
} while(p < pend);
for(uint64_t i = 0; i < 64ull; ++i) data.counts_[i] += local_counts[i];
}
_STORAGE_ void hll_t::parsum(int nthreads, std::size_t pb) {
if(nthreads < 0) nthreads = std::thread::hardware_concurrency();
std::atomic<uint64_t> acounts[64];
std::memset(acounts, 0, sizeof acounts);
parsum_data_t<decltype(core_)> data{acounts, core_, m(), pb};
const uint64_t nr(core_.size() / pb + (core_.size() % pb != 0));
kt_for(nthreads, parsum_helper<decltype(core_)>, &data, nr);
uint64_t counts[64];
std::memcpy(counts, acounts, sizeof(counts));
value_ = detail::calculate_estimate(counts, use_ertl_, m(), np_, alpha());
is_calculated_ = 1;
}
_STORAGE_ double hll_t::creport() const {
if(!is_calculated_) throw std::runtime_error("Result must be calculated in order to report."
" Try the report() function.");
return value_;
}
_STORAGE_ double hll_t::cest_err() const {
if(!is_calculated_) throw std::runtime_error("Result must be calculated in order to report.");
return relative_error() * creport();
}
_STORAGE_ double hll_t::est_err() noexcept {
if(!is_calculated_) sum();
return cest_err();
}
_STORAGE_ hll_t &hll_t::operator+=(const hll_t &other) {
if(other.np_ != np_) {
char buf[256];
sprintf(buf, "For operator +=: np_ (%u) != other.np_ (%u)\n", np_, other.np_);
throw std::runtime_error(buf);
}
unsigned i;
#if HAS_AVX_512
__m512i *els(reinterpret_cast<__m512i *>(core_.data()));
const __m512i *oels(reinterpret_cast<const __m512i *>(other.core_.data()));
for(i = 0; i < m() >> 6; ++i) els[i] = _mm512_max_epu8(els[i], oels[i]);
if(m() < 64) for(;i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#elif __AVX2__
__m256i *els(reinterpret_cast<__m256i *>(core_.data()));
const __m256i *oels(reinterpret_cast<const __m256i *>(other.core_.data()));
for(i = 0; i < m() >> 5; ++i) els[i] = _mm256_max_epu8(els[i], oels[i]);
if(m() < 32) for(;i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#elif __SSE2__
__m128i *els(reinterpret_cast<__m128i *>(core_.data()));
const __m128i *oels(reinterpret_cast<const __m128i *>(other.core_.data()));
for(i = 0; i < m() >> 4; ++i) els[i] = _mm_max_epu8(els[i], oels[i]);
if(m() < 16) for(; i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#else
for(i = 0; i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#endif
not_ready();
return *this;
}
_STORAGE_ hll_t &hll_t::operator&=(const hll_t &other) {
std::fprintf(stderr, "Warning: This method doesn't work very well at all. For some reason. Do not trust.\n");
if(other.np_ != np_) {
char buf[256];
sprintf(buf, "For operator &=: np_ (%u) != other.np_ (%u)\n", np_, other.np_);
throw std::runtime_error(buf);
}
unsigned i;
#if HAS_AVX_512
__m512i *els(reinterpret_cast<__m512i *>(core_.data()));
const __m512i *oels(reinterpret_cast<const __m512i *>(other.core_.data()));
for(i = 0; i < m() >> 6; ++i) els[i] = _mm512_min_epu8(els[i], oels[i]);
if(m() < 64) for(;i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#elif __AVX2__
__m256i *els(reinterpret_cast<__m256i *>(core_.data()));
const __m256i *oels(reinterpret_cast<const __m256i *>(other.core_.data()));
for(i = 0; i < m() >> 5; ++i) {
els[i] = _mm256_min_epu8(els[i], oels[i]);
}
if(m() < 32) for(;i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#elif __SSE2__
__m128i *els(reinterpret_cast<__m128i *>(core_.data()));
const __m128i *oels(reinterpret_cast<const __m128i *>(other.core_.data()));
for(i = 0; i < m() >> 4; ++i) els[i] = _mm_min_epu8(els[i], oels[i]);
if(m() < 16) for(;i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#else
for(i = 0; i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#endif
not_ready();
return *this;
}
// Returns the size of a symmetric set difference.
_STORAGE_ double operator^(hll_t &first, hll_t &other) {
return 2*(hll_t(first) + other).report() - first.report() - other.report();
}
// Returns the set intersection
_STORAGE_ hll_t operator&(hll_t &first, hll_t &other) {
hll_t tmp(first);
tmp &= other;
return tmp;
}
_STORAGE_ hll_t operator+(const hll_t &one, const hll_t &other) {
if(other.p() != one.p())
LOG_EXIT("p (%zu) != other.p (%zu)\n", one.p(), other.p());
hll_t ret(one);
ret += other;
return ret;
}
_STORAGE_ double intersection_size(hll_t &first, hll_t &other) noexcept {
first.sum(); other.sum();
return intersection_size((const hll_t &)first, (const hll_t &)other);
}
_STORAGE_ double jaccard_index(hll_t &first, hll_t &other) noexcept {
first.sum(); other.sum();
return jaccard_index((const hll_t &)first, (const hll_t &)other);
}
_STORAGE_ double jaccard_index(const hll_t &first, const hll_t &other) {
double i(intersection_size(first, other));
i /= (first.creport() + other.creport() - i);
return i;
}
// Clears, allows reuse with different np.
_STORAGE_ void hll_t::resize(std::size_t new_size) {
new_size = roundup64(new_size);
LOG_DEBUG("Resizing to %zu, with np = %zu\n", new_size, (std::size_t)std::log2(new_size));
clear();
core_.resize(new_size);
np_ = (std::size_t)std::log2(new_size);
}
_STORAGE_ void hll_t::clear() {
std::fill(std::begin(core_), std::end(core_), 0u);
value_ = is_calculated_ = 0;
}
_STORAGE_ std::string hll_t::to_string() const {
std::string params(std::string("p:") + std::to_string(np_) + ";");
return (params + (is_calculated_ ? std::to_string(creport()) + ", +- " + std::to_string(cest_err())
: desc_string()));
}
_STORAGE_ std::string hll_t::desc_string() const {
char buf[512];
std::sprintf(buf, "Size: %u. nb: %llu. error: %lf. Is calculated: %s. value: %lf\n",
np_, static_cast<long long unsigned int>(m()), relative_error(), is_calculated_ ? "true": "false", value_);
return buf;
}
_STORAGE_ void hll_t::free() {
decltype(core_) tmp{};
std::swap(core_, tmp);
}
_STORAGE_ void hll_t::write(const int fileno) {
uint32_t bf[3]{is_calculated_, use_ertl_, nthreads_};
::write(fileno, bf, sizeof(bf));
::write(fileno, &np_, sizeof(np_));
::write(fileno, &value_, sizeof(value_));
::write(fileno, core_.data(), core_.size() * sizeof(core_[0]));
}
_STORAGE_ void hll_t::read(const int fileno) {
uint32_t bf[3];
::read(fileno, bf, sizeof(bf));
is_calculated_ = bf[0]; use_ertl_ = bf[1]; nthreads_ = bf[2];
::read(fileno, &np_, sizeof(np_));
::read(fileno, &value_, sizeof(value_));
core_.resize(m());
::read(fileno, core_.data(), core_.size());
}
_STORAGE_ void hll_t::write(std::FILE *fp) {
#if _POSIX_VERSION
write(fileno(fp));
#else
static_assert(false, "Needs posix for now, will write non-posix version later.");
#endif
}
_STORAGE_ void hll_t::read(std::FILE *fp) {
#if _POSIX_VERSION
read(fileno(fp));
#else
static_assert(false, "Needs posix for now, will write non-posix version later.");
#endif
}
_STORAGE_ void hll_t::read(const char *path) {
std::FILE *fp(std::fopen(path, "rb"));
if(fp == nullptr) throw std::runtime_error(std::string("Could not open file at ") + path);
read(fp);
std::fclose(fp);
}
_STORAGE_ void hll_t::write(const char *path) {
std::FILE *fp(std::fopen(path, "wb"));
if(fp == nullptr) throw std::runtime_error(std::string("Could not open file at ") + path);
write(fp);
std::fclose(fp);
}
} // namespace hll
<commit_msg>Only calculate sum during intersection size if necessary.<commit_after>#ifndef HLL_HEADER_ONLY
# include "hll.h"
#endif
#include <stdexcept>
#include <cstring>
#include <numeric>
#include <thread>
#include <cinttypes>
#include <atomic>
#include "kthread.h"
namespace hll {
#if !NDEBUG
template<typename T>
std::string arrstr(T it, T it2) {
std::string ret;
for(auto i(it); i != it2; ++i) ret += "," + std::to_string(*i);
return ret;
}
#endif
_STORAGE_ void hll_t::sum() {
using detail::SIMDHolder;
uint64_t counts[64]{0};
SIMDHolder tmp, *p((SIMDHolder *)core_.data()), *pend((SIMDHolder *)&*core_.end());
do {
tmp = *p++;
tmp.inc_counts(counts);
} while(p < pend);
value_ = detail::calculate_estimate(counts, use_ertl_, m(), np_, alpha());
is_calculated_ = 1;
}
template<typename CoreType>
struct parsum_data_t {
std::atomic<uint64_t> *counts_; // Array decayed to pointer.
const CoreType &core_;
const uint64_t l_;
const uint64_t pb_; // Per-batch
};
template<typename CoreType>
_STORAGE_ void parsum_helper(void *data_, long index, int tid) {
using detail::SIMDHolder;
parsum_data_t<CoreType> &data(*(parsum_data_t<CoreType> *)data_);
uint64_t local_counts[64]{0};
SIMDHolder tmp, *p((SIMDHolder *)&data.core_[index * data.pb_]),
*pend((SIMDHolder *)&data.core_[std::min(data.l_, (index+1) * data.pb_)]);
do {
tmp = *p++;
tmp.inc_counts(local_counts);
} while(p < pend);
for(uint64_t i = 0; i < 64ull; ++i) data.counts_[i] += local_counts[i];
}
_STORAGE_ void hll_t::parsum(int nthreads, std::size_t pb) {
if(nthreads < 0) nthreads = std::thread::hardware_concurrency();
std::atomic<uint64_t> acounts[64];
std::memset(acounts, 0, sizeof acounts);
parsum_data_t<decltype(core_)> data{acounts, core_, m(), pb};
const uint64_t nr(core_.size() / pb + (core_.size() % pb != 0));
kt_for(nthreads, parsum_helper<decltype(core_)>, &data, nr);
uint64_t counts[64];
std::memcpy(counts, acounts, sizeof(counts));
value_ = detail::calculate_estimate(counts, use_ertl_, m(), np_, alpha());
is_calculated_ = 1;
}
_STORAGE_ double hll_t::creport() const {
if(!is_calculated_) throw std::runtime_error("Result must be calculated in order to report."
" Try the report() function.");
return value_;
}
_STORAGE_ double hll_t::cest_err() const {
if(!is_calculated_) throw std::runtime_error("Result must be calculated in order to report.");
return relative_error() * creport();
}
_STORAGE_ double hll_t::est_err() noexcept {
if(!is_calculated_) sum();
return cest_err();
}
_STORAGE_ hll_t &hll_t::operator+=(const hll_t &other) {
if(other.np_ != np_) {
char buf[256];
sprintf(buf, "For operator +=: np_ (%u) != other.np_ (%u)\n", np_, other.np_);
throw std::runtime_error(buf);
}
unsigned i;
#if HAS_AVX_512
__m512i *els(reinterpret_cast<__m512i *>(core_.data()));
const __m512i *oels(reinterpret_cast<const __m512i *>(other.core_.data()));
for(i = 0; i < m() >> 6; ++i) els[i] = _mm512_max_epu8(els[i], oels[i]);
if(m() < 64) for(;i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#elif __AVX2__
__m256i *els(reinterpret_cast<__m256i *>(core_.data()));
const __m256i *oels(reinterpret_cast<const __m256i *>(other.core_.data()));
for(i = 0; i < m() >> 5; ++i) els[i] = _mm256_max_epu8(els[i], oels[i]);
if(m() < 32) for(;i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#elif __SSE2__
__m128i *els(reinterpret_cast<__m128i *>(core_.data()));
const __m128i *oels(reinterpret_cast<const __m128i *>(other.core_.data()));
for(i = 0; i < m() >> 4; ++i) els[i] = _mm_max_epu8(els[i], oels[i]);
if(m() < 16) for(; i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#else
for(i = 0; i < m(); ++i) core_[i] = std::max(core_[i], other.core_[i]);
#endif
not_ready();
return *this;
}
_STORAGE_ hll_t &hll_t::operator&=(const hll_t &other) {
std::fprintf(stderr, "Warning: This method doesn't work very well at all. For some reason. Do not trust.\n");
if(other.np_ != np_) {
char buf[256];
sprintf(buf, "For operator &=: np_ (%u) != other.np_ (%u)\n", np_, other.np_);
throw std::runtime_error(buf);
}
unsigned i;
#if HAS_AVX_512
__m512i *els(reinterpret_cast<__m512i *>(core_.data()));
const __m512i *oels(reinterpret_cast<const __m512i *>(other.core_.data()));
for(i = 0; i < m() >> 6; ++i) els[i] = _mm512_min_epu8(els[i], oels[i]);
if(m() < 64) for(;i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#elif __AVX2__
__m256i *els(reinterpret_cast<__m256i *>(core_.data()));
const __m256i *oels(reinterpret_cast<const __m256i *>(other.core_.data()));
for(i = 0; i < m() >> 5; ++i) {
els[i] = _mm256_min_epu8(els[i], oels[i]);
}
if(m() < 32) for(;i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#elif __SSE2__
__m128i *els(reinterpret_cast<__m128i *>(core_.data()));
const __m128i *oels(reinterpret_cast<const __m128i *>(other.core_.data()));
for(i = 0; i < m() >> 4; ++i) els[i] = _mm_min_epu8(els[i], oels[i]);
if(m() < 16) for(;i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#else
for(i = 0; i < m(); ++i) core_[i] = std::min(core_[i], other.core_[i]);
#endif
not_ready();
return *this;
}
// Returns the size of a symmetric set difference.
_STORAGE_ double operator^(hll_t &first, hll_t &other) {
return 2*(hll_t(first) + other).report() - first.report() - other.report();
}
// Returns the set intersection
_STORAGE_ hll_t operator&(hll_t &first, hll_t &other) {
hll_t tmp(first);
tmp &= other;
return tmp;
}
_STORAGE_ hll_t operator+(const hll_t &one, const hll_t &other) {
if(other.p() != one.p())
LOG_EXIT("p (%zu) != other.p (%zu)\n", one.p(), other.p());
hll_t ret(one);
ret += other;
return ret;
}
_STORAGE_ double intersection_size(hll_t &first, hll_t &other) noexcept {
if(!first.is_calculated_()) first.sum();
if(!other.is_calculated_()) other.sum();
return intersection_size((const hll_t &)first, (const hll_t &)other);
}
_STORAGE_ double jaccard_index(hll_t &first, hll_t &other) noexcept {
if(!first.is_calculated_()) first.sum();
if(!other.is_calculated_()) other.sum();
return jaccard_index((const hll_t &)first, (const hll_t &)other);
}
_STORAGE_ double jaccard_index(const hll_t &first, const hll_t &other) {
double i(intersection_size(first, other));
i /= (first.creport() + other.creport() - i);
return i;
}
// Clears, allows reuse with different np.
_STORAGE_ void hll_t::resize(std::size_t new_size) {
new_size = roundup64(new_size);
LOG_DEBUG("Resizing to %zu, with np = %zu\n", new_size, (std::size_t)std::log2(new_size));
clear();
core_.resize(new_size);
np_ = (std::size_t)std::log2(new_size);
}
_STORAGE_ void hll_t::clear() {
std::fill(std::begin(core_), std::end(core_), 0u);
value_ = is_calculated_ = 0;
}
_STORAGE_ std::string hll_t::to_string() const {
std::string params(std::string("p:") + std::to_string(np_) + ";");
return (params + (is_calculated_ ? std::to_string(creport()) + ", +- " + std::to_string(cest_err())
: desc_string()));
}
_STORAGE_ std::string hll_t::desc_string() const {
char buf[512];
std::sprintf(buf, "Size: %u. nb: %llu. error: %lf. Is calculated: %s. value: %lf\n",
np_, static_cast<long long unsigned int>(m()), relative_error(), is_calculated_ ? "true": "false", value_);
return buf;
}
_STORAGE_ void hll_t::free() {
decltype(core_) tmp{};
std::swap(core_, tmp);
}
_STORAGE_ void hll_t::write(const int fileno) {
uint32_t bf[3]{is_calculated_, use_ertl_, nthreads_};
::write(fileno, bf, sizeof(bf));
::write(fileno, &np_, sizeof(np_));
::write(fileno, &value_, sizeof(value_));
::write(fileno, core_.data(), core_.size() * sizeof(core_[0]));
}
_STORAGE_ void hll_t::read(const int fileno) {
uint32_t bf[3];
::read(fileno, bf, sizeof(bf));
is_calculated_ = bf[0]; use_ertl_ = bf[1]; nthreads_ = bf[2];
::read(fileno, &np_, sizeof(np_));
::read(fileno, &value_, sizeof(value_));
core_.resize(m());
::read(fileno, core_.data(), core_.size());
}
_STORAGE_ void hll_t::write(std::FILE *fp) {
#if _POSIX_VERSION
write(fileno(fp));
#else
static_assert(false, "Needs posix for now, will write non-posix version later.");
#endif
}
_STORAGE_ void hll_t::read(std::FILE *fp) {
#if _POSIX_VERSION
read(fileno(fp));
#else
static_assert(false, "Needs posix for now, will write non-posix version later.");
#endif
}
_STORAGE_ void hll_t::read(const char *path) {
std::FILE *fp(std::fopen(path, "rb"));
if(fp == nullptr) throw std::runtime_error(std::string("Could not open file at ") + path);
read(fp);
std::fclose(fp);
}
_STORAGE_ void hll_t::write(const char *path) {
std::FILE *fp(std::fopen(path, "wb"));
if(fp == nullptr) throw std::runtime_error(std::string("Could not open file at ") + path);
write(fp);
std::fclose(fp);
}
} // namespace hll
<|endoftext|> |
<commit_before>#pragma once
#include "detail/function_traits.hpp"
#include "detail/traits.hpp"
#include "detail/utils.hpp"
#include "detail/container_service.hpp"
#include "detail/invoke.hpp"
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
#include <algorithm>
#include <vector>
namespace kgr {
struct ForkService;
struct Container {
private:
template<typename Condition, typename T = int> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = int> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using decay = typename std::decay<T>::type;
template<typename T> using is_single = std::is_base_of<Single, decay<T>>;
template<typename T> using is_container_service = std::integral_constant<bool, std::is_same<T, ContainerService>::value || std::is_same<T, ForkService>::value>;
template<typename T> using is_base_of_container_service = std::is_base_of<detail::ContainerServiceBase, T>;
template<typename T> using parent_types = typename decay<T>::ParentTypes;
template<int S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type;
template<typename Tuple, int n> using tuple_seq_minus = typename detail::seq_gen<std::tuple_size<Tuple>::value - n>::type;
template<typename T> using instance_ptr = std::unique_ptr<T, void(*)(void*)>;
template<template<typename> class Map, typename T> using service_map_t = typename Map<T>::Service;
template<typename T> using is_invoke_call = typename std::is_base_of<detail::InvokeCallTag, T>::type;
template<typename T> using has_autocall = typename std::is_base_of<detail::AutocallTag, T>::type;
using instance_cont = std::vector<instance_ptr<void>>;
using service_cont = std::unordered_map<detail::type_id_t, void*>;
template<typename T>
static void deleter(void* i) {
delete static_cast<T*>(i);
}
template<typename T, typename C = T, typename... Args, enable_if<std::is_constructible<T, Args...>> = 0>
static instance_ptr<C> makeInstancePtr(Args&&... args) {
return instance_ptr<T>{new T(std::forward<Args>(args)...), &Container::deleter<C>};
}
template<typename T, typename C = T, typename... Args, disable_if<std::is_constructible<T, Args...>> = 0>
static instance_ptr<C> makeInstancePtr(Args&&... args) {
return instance_ptr<T>{new T{std::forward<Args>(args)...}, &Container::deleter<C>};
}
public:
Container() = default;
Container(const Container &) = delete;
Container& operator=(const Container &) = delete;
Container(Container&&) = default;
Container& operator=(Container&&) = default;
virtual ~Container() = default;
template<typename T, enable_if<is_single<decay<T>>> = 0>
void instance(T&& service) {
save_instance(std::forward<T>(service));
}
template<typename T, typename... Args, enable_if<is_single<T>> = 0>
void instance(Args&& ...args) {
save_new_instance<T>(std::forward<Args>(args)...);
}
template<typename T, typename... Args>
ServiceType<T> service(Args&& ...args) {
return get_service<T>(std::forward<Args>(args)...).forward();
}
template<template<typename> class Map, typename U, typename ...Args>
detail::function_result_t<decay<U>> invoke(U&& function, Args&&... args) {
return invoke<Map>(tuple_seq_minus<detail::function_arguments_t<decay<U>>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)...);
}
template<typename... Services, typename U, typename ...Args>
detail::function_result_t<decay<U>> invoke(U&& function, Args&&... args) {
return std::forward<U>(function)(service<Services>()..., std::forward<Args>(args)...);
}
inline void clear() {
_instances.clear();
_services.clear();
}
inline Container fork() {
return Container{_services};
}
inline void merge(Container&& other) {
_instances.insert(_instances.end(), std::make_move_iterator(other._instances.begin()), std::make_move_iterator(other._instances.end()));
_services.insert(other._services.begin(), other._services.end());
}
private:
Container(service_cont& services) : _services{services} {};
///////////////////////
// save instance //
///////////////////////
template<typename T, typename... Args, enable_if<is_single<T>> = 0, disable_if<std::is_abstract<T>> = 0>
T& save_new_instance(Args&&... args) {
auto service = save_instance(make_service_instance<T>(std::forward<Args>(args)...));
invoke_service(service);
return service;
}
template<typename T, typename... Args, enable_if<is_single<T>> = 0, enable_if<std::is_abstract<T>> = 0>
T& save_new_instance(Args&&...) {
throw std::out_of_range{"No instance found for the requested abstract service"};
}
template<typename T, enable_if<detail::has_overrides<decay<T>>> = 0>
T& save_instance(T&& service) {
return save_instance(std::forward<T>(service), detail::tuple_seq<parent_types<T>>{});
}
template<typename T, disable_if<detail::has_overrides<decay<T>>> = 0>
T& save_instance(T&& service) {
using U = decay<T>;
return save_instance_helper<U>(makeInstancePtr<U>(std::move(service)));
}
template<typename T, int... S>
T& save_instance(T&& service, detail::seq<S...>) {
using U = decay<T>;
return save_instance_helper<U, tuple_element_t<S, parent_types<U>>...>(makeInstancePtr<U>(std::move(service)));
}
template<typename T>
T& save_instance_helper(instance_ptr<T> service) {
auto& serviceRef = *service;
_services[detail::type_id<T>] = service.get();
_instances.emplace_back(std::move(service));
return serviceRef;
}
template<typename T, typename Override, typename... Others>
T& save_instance_helper(instance_ptr<T> service) {
auto overrideService = makeInstancePtr<detail::ServiceOverride<T, Override>, Override>(*service);
_services[detail::type_id<Override>] = overrideService.get();
_instances.emplace_back(std::move(overrideService));
return save_instance_helper<T, Others...>(std::move(service));
}
///////////////////////
// get service //
///////////////////////
template<typename T, typename... Args, disable_if<is_single<T>> = 0, disable_if<is_base_of_container_service<T>> = 0>
T get_service(Args&&... args) {
auto service = make_service_instance<T>(std::forward<Args>(args)...);
invoke_service(service);
return service;
}
template<typename T, enable_if<is_container_service<T>> = 0>
T get_service() {
return T{*this};
}
template<typename T, enable_if<is_base_of_container_service<T>> = 0, disable_if<is_container_service<T>> = 0>
T get_service() {
return T{*dynamic_cast<typename T::Type*>(this)};
}
template<typename T, enable_if<is_single<T>> = 0, disable_if<is_base_of_container_service<T>> = 0>
T& get_service() {
if (auto&& service = _services[detail::type_id<T>]) {
return *static_cast<T*>(service);
} else {
return save_new_instance<T>();
}
}
///////////////////////
// make instance //
///////////////////////
template<typename T, typename... Args>
T make_service_instance(Args&&... args) {
return invoke_raw(&T::construct, std::forward<Args>(args)...);
}
///////////////////////
// invoke //
///////////////////////
template<typename U, typename ...Args, int... S>
detail::function_result_t<decay<U>> invoke(detail::seq<S...>, U&& function, Args&&... args) {
return std::forward<U>(function)(get_service<decay<detail::function_argument_t<S, decay<U>>>>()..., std::forward<Args>(args)...);
}
template<template<typename> class Map, typename U, typename ...Args, int... S>
detail::function_result_t<decay<U>> invoke(detail::seq<S...>, U&& function, Args&&... args) {
return std::forward<U>(function)(service<service_map_t<Map, detail::function_argument_t<S, decay<U>>>>()..., std::forward<Args>(args)...);
}
template<typename U, typename ...Args, enable_if<is_invoke_call<decay<U>>> = 0>
detail::function_result_t<decay<U>> invoke(U&& function, Args&&... args) {
using V = decay<U>;
return invoke(detail::tuple_seq<typename V::Params>{}, std::forward<U>(function), std::forward<Args>(args)...);
}
template<typename U, typename ...Args, int... S, enable_if<is_invoke_call<decay<U>>> = 0>
detail::function_result_t<decay<U>> invoke(detail::seq<S...>, U&& function, Args&&... args) {
using V = decay<U>;
return invoke<tuple_element_t<S, typename V::Params>...>(std::forward<U>(function), std::forward<Args>(args)...);
}
template<typename U, typename ...Args, disable_if<is_invoke_call<decay<U>>> = 0>
detail::function_result_t<decay<U>> invoke_raw(U&& function, Args&&... args) {
return invoke(tuple_seq_minus<detail::function_arguments_t<decay<U>>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)...);
}
///////////////////////
// autocall //
///////////////////////
// This function starts the iteration (invoke_service_helper)
template<typename T, enable_if<detail::has_invoke<decay<T>>> = 0>
void invoke_service(T&& service) {
using U = decay<T>;
invoke_service_helper<typename U::invoke>(std::forward<T>(service));
}
// This function is the iteration for invoke_service
template<typename Method, typename T, enable_if<detail::has_next<Method>> = 0>
void invoke_service_helper(T&& service) {
do_invoke_service<Method>(std::forward<T>(service));
invoke_service_helper<typename Method::Next>(std::forward<T>(service));
}
// This is the last iteration of invoke_service
template<typename Method, typename T, disable_if<detail::has_next<Method>> = 0>
void invoke_service_helper(T&&) {}
// This function is the do_invoke_service when <Method> is kgr::Invoke with parameters explicitly listed.
template<typename Method, typename T, enable_if<is_invoke_call<Method>> = 0>
void do_invoke_service(T&& service) {
do_invoke_service<Method>(detail::tuple_seq<typename Method::Params>{}, std::forward<T>(service));
}
// This function is a helper for do_invoke_service when <Method> is kgr::Invoke with parameters explicitly listed.
template<typename Method, typename T, int... S>
void do_invoke_service(detail::seq<S...>, T&& service) {
using U = decay<T>;
do_invoke_service(
detail::tuple_seq<detail::function_arguments_t<typename Method::value_type>>{},
std::forward<T>(service),
&U::template autocall<Method, tuple_element_t<S, typename Method::Params>...>
);
}
// This function is the do_invoke_service handling the new syntax for autocall
template<typename Method, typename T, disable_if<is_invoke_call<Method>> = 0, enable_if<has_autocall<decay<T>>> = 0>
void do_invoke_service(T&& service) {
using U = decay<T>;
do_invoke_service(detail::tuple_seq<std::tuple<ContainerService>>{}, std::forward<T>(service), &U::template autocall<Method, U::template Map>);
}
// This function is the do_invoke_service with the old syntax
template<typename Method, typename T, disable_if<is_invoke_call<Method>> = 0, disable_if<has_autocall<decay<T>>> = 0>
void do_invoke_service(T&& service) {
do_invoke_service(detail::tuple_seq<detail::function_arguments_t<typename Method::value_type>>{}, std::forward<T>(service), Method::value);
}
// This function is the do_invoke_service that take the method to invoke as parameter.
template<typename T, typename F, int... S>
void do_invoke_service(detail::seq<S...>, T&& service, F&& function) {
invoke_raw([&service, &function](detail::function_argument_t<S, decay<F>>... args){
(std::forward<T>(service).*std::forward<F>(function))(std::forward<detail::function_argument_t<S, decay<F>>>(args)...);
});
}
template<typename T, disable_if<detail::has_invoke<decay<T>>> = 0>
void invoke_service(T&&) {}
///////////////////////
// instances //
///////////////////////
instance_cont _instances;
service_cont _services;
};
} // namespace kgr
<commit_msg>fixed compilation error, sorry<commit_after>#pragma once
#include "detail/function_traits.hpp"
#include "detail/traits.hpp"
#include "detail/utils.hpp"
#include "detail/container_service.hpp"
#include "detail/invoke.hpp"
#include <unordered_map>
#include <memory>
#include <type_traits>
#include <tuple>
#include <algorithm>
#include <vector>
namespace kgr {
struct ForkService;
struct Container {
private:
template<typename Condition, typename T = int> using enable_if = detail::enable_if_t<Condition::value, T>;
template<typename Condition, typename T = int> using disable_if = detail::enable_if_t<!Condition::value, T>;
template<typename T> using decay = typename std::decay<T>::type;
template<typename T> using is_single = std::is_base_of<Single, decay<T>>;
template<typename T> using is_container_service = std::integral_constant<bool, std::is_same<T, ContainerService>::value || std::is_same<T, ForkService>::value>;
template<typename T> using is_base_of_container_service = std::is_base_of<detail::ContainerServiceBase, T>;
template<typename T> using parent_types = typename decay<T>::ParentTypes;
template<int S, typename T> using tuple_element_t = typename std::tuple_element<S, T>::type;
template<typename Tuple, int n> using tuple_seq_minus = typename detail::seq_gen<std::tuple_size<Tuple>::value - n>::type;
template<typename T> using instance_ptr = std::unique_ptr<T, void(*)(void*)>;
template<template<typename> class Map, typename T> using service_map_t = typename Map<T>::Service;
template<typename T> using is_invoke_call = typename std::is_base_of<detail::InvokeCallTag, T>::type;
template<typename T> using has_autocall = typename std::is_base_of<detail::AutocallTag, T>::type;
using instance_cont = std::vector<instance_ptr<void>>;
using service_cont = std::unordered_map<detail::type_id_t, void*>;
template<typename T>
static void deleter(void* i) {
delete static_cast<T*>(i);
}
template<typename T, typename C = T, typename... Args, enable_if<std::is_constructible<T, Args...>> = 0>
static instance_ptr<C> makeInstancePtr(Args&&... args) {
return instance_ptr<T>{new T(std::forward<Args>(args)...), &Container::deleter<C>};
}
template<typename T, typename C = T, typename... Args, disable_if<std::is_constructible<T, Args...>> = 0>
static instance_ptr<C> makeInstancePtr(Args&&... args) {
return instance_ptr<T>{new T{std::forward<Args>(args)...}, &Container::deleter<C>};
}
public:
Container() = default;
Container(const Container &) = delete;
Container& operator=(const Container &) = delete;
Container(Container&&) = default;
Container& operator=(Container&&) = default;
virtual ~Container() = default;
template<typename T, enable_if<is_single<decay<T>>> = 0>
void instance(T&& service) {
save_instance(std::forward<T>(service));
}
template<typename T, typename... Args, enable_if<is_single<T>> = 0>
void instance(Args&& ...args) {
save_new_instance<T>(std::forward<Args>(args)...);
}
template<typename T, typename... Args>
ServiceType<T> service(Args&& ...args) {
return get_service<T>(std::forward<Args>(args)...).forward();
}
template<template<typename> class Map, typename U, typename ...Args>
detail::function_result_t<decay<U>> invoke(U&& function, Args&&... args) {
return invoke<Map>(tuple_seq_minus<detail::function_arguments_t<decay<U>>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)...);
}
template<typename... Services, typename U, typename ...Args>
detail::function_result_t<decay<U>> invoke(U&& function, Args&&... args) {
return std::forward<U>(function)(service<Services>()..., std::forward<Args>(args)...);
}
inline void clear() {
_instances.clear();
_services.clear();
}
inline Container fork() {
return Container{_services};
}
inline void merge(Container&& other) {
_instances.insert(_instances.end(), std::make_move_iterator(other._instances.begin()), std::make_move_iterator(other._instances.end()));
_services.insert(other._services.begin(), other._services.end());
}
private:
Container(service_cont& services) : _services{services} {};
///////////////////////
// save instance //
///////////////////////
template<typename T, typename... Args, enable_if<is_single<T>> = 0, disable_if<std::is_abstract<T>> = 0>
T& save_new_instance(Args&&... args) {
auto& service = save_instance(make_service_instance<T>(std::forward<Args>(args)...));
invoke_service(service);
return service;
}
template<typename T, typename... Args, enable_if<is_single<T>> = 0, enable_if<std::is_abstract<T>> = 0>
T& save_new_instance(Args&&...) {
throw std::out_of_range{"No instance found for the requested abstract service"};
}
template<typename T, enable_if<detail::has_overrides<decay<T>>> = 0>
T& save_instance(T&& service) {
return save_instance(std::forward<T>(service), detail::tuple_seq<parent_types<T>>{});
}
template<typename T, disable_if<detail::has_overrides<decay<T>>> = 0>
T& save_instance(T&& service) {
using U = decay<T>;
return save_instance_helper<U>(makeInstancePtr<U>(std::move(service)));
}
template<typename T, int... S>
T& save_instance(T&& service, detail::seq<S...>) {
using U = decay<T>;
return save_instance_helper<U, tuple_element_t<S, parent_types<U>>...>(makeInstancePtr<U>(std::move(service)));
}
template<typename T>
T& save_instance_helper(instance_ptr<T> service) {
auto& serviceRef = *service;
_services[detail::type_id<T>] = service.get();
_instances.emplace_back(std::move(service));
return serviceRef;
}
template<typename T, typename Override, typename... Others>
T& save_instance_helper(instance_ptr<T> service) {
auto overrideService = makeInstancePtr<detail::ServiceOverride<T, Override>, Override>(*service);
_services[detail::type_id<Override>] = overrideService.get();
_instances.emplace_back(std::move(overrideService));
return save_instance_helper<T, Others...>(std::move(service));
}
///////////////////////
// get service //
///////////////////////
template<typename T, typename... Args, disable_if<is_single<T>> = 0, disable_if<is_base_of_container_service<T>> = 0>
T get_service(Args&&... args) {
auto service = make_service_instance<T>(std::forward<Args>(args)...);
invoke_service(service);
return service;
}
template<typename T, enable_if<is_container_service<T>> = 0>
T get_service() {
return T{*this};
}
template<typename T, enable_if<is_base_of_container_service<T>> = 0, disable_if<is_container_service<T>> = 0>
T get_service() {
return T{*dynamic_cast<typename T::Type*>(this)};
}
template<typename T, enable_if<is_single<T>> = 0, disable_if<is_base_of_container_service<T>> = 0>
T& get_service() {
if (auto&& service = _services[detail::type_id<T>]) {
return *static_cast<T*>(service);
} else {
return save_new_instance<T>();
}
}
///////////////////////
// make instance //
///////////////////////
template<typename T, typename... Args>
T make_service_instance(Args&&... args) {
return invoke_raw(&T::construct, std::forward<Args>(args)...);
}
///////////////////////
// invoke //
///////////////////////
template<typename U, typename ...Args, int... S>
detail::function_result_t<decay<U>> invoke(detail::seq<S...>, U&& function, Args&&... args) {
return std::forward<U>(function)(get_service<decay<detail::function_argument_t<S, decay<U>>>>()..., std::forward<Args>(args)...);
}
template<template<typename> class Map, typename U, typename ...Args, int... S>
detail::function_result_t<decay<U>> invoke(detail::seq<S...>, U&& function, Args&&... args) {
return std::forward<U>(function)(service<service_map_t<Map, detail::function_argument_t<S, decay<U>>>>()..., std::forward<Args>(args)...);
}
template<typename U, typename ...Args, enable_if<is_invoke_call<decay<U>>> = 0>
detail::function_result_t<decay<U>> invoke(U&& function, Args&&... args) {
using V = decay<U>;
return invoke(detail::tuple_seq<typename V::Params>{}, std::forward<U>(function), std::forward<Args>(args)...);
}
template<typename U, typename ...Args, int... S, enable_if<is_invoke_call<decay<U>>> = 0>
detail::function_result_t<decay<U>> invoke(detail::seq<S...>, U&& function, Args&&... args) {
using V = decay<U>;
return invoke<tuple_element_t<S, typename V::Params>...>(std::forward<U>(function), std::forward<Args>(args)...);
}
template<typename U, typename ...Args, disable_if<is_invoke_call<decay<U>>> = 0>
detail::function_result_t<decay<U>> invoke_raw(U&& function, Args&&... args) {
return invoke(tuple_seq_minus<detail::function_arguments_t<decay<U>>, sizeof...(Args)>{}, std::forward<U>(function), std::forward<Args>(args)...);
}
///////////////////////
// autocall //
///////////////////////
// This function starts the iteration (invoke_service_helper)
template<typename T, enable_if<detail::has_invoke<decay<T>>> = 0>
void invoke_service(T&& service) {
using U = decay<T>;
invoke_service_helper<typename U::invoke>(std::forward<T>(service));
}
// This function is the iteration for invoke_service
template<typename Method, typename T, enable_if<detail::has_next<Method>> = 0>
void invoke_service_helper(T&& service) {
do_invoke_service<Method>(std::forward<T>(service));
invoke_service_helper<typename Method::Next>(std::forward<T>(service));
}
// This is the last iteration of invoke_service
template<typename Method, typename T, disable_if<detail::has_next<Method>> = 0>
void invoke_service_helper(T&&) {}
// This function is the do_invoke_service when <Method> is kgr::Invoke with parameters explicitly listed.
template<typename Method, typename T, enable_if<is_invoke_call<Method>> = 0>
void do_invoke_service(T&& service) {
do_invoke_service<Method>(detail::tuple_seq<typename Method::Params>{}, std::forward<T>(service));
}
// This function is a helper for do_invoke_service when <Method> is kgr::Invoke with parameters explicitly listed.
template<typename Method, typename T, int... S>
void do_invoke_service(detail::seq<S...>, T&& service) {
using U = decay<T>;
do_invoke_service(
detail::tuple_seq<detail::function_arguments_t<typename Method::value_type>>{},
std::forward<T>(service),
&U::template autocall<Method, tuple_element_t<S, typename Method::Params>...>
);
}
// This function is the do_invoke_service handling the new syntax for autocall
template<typename Method, typename T, disable_if<is_invoke_call<Method>> = 0, enable_if<has_autocall<decay<T>>> = 0>
void do_invoke_service(T&& service) {
using U = decay<T>;
do_invoke_service(detail::tuple_seq<std::tuple<ContainerService>>{}, std::forward<T>(service), &U::template autocall<Method, U::template Map>);
}
// This function is the do_invoke_service with the old syntax
template<typename Method, typename T, disable_if<is_invoke_call<Method>> = 0, disable_if<has_autocall<decay<T>>> = 0>
void do_invoke_service(T&& service) {
do_invoke_service(detail::tuple_seq<detail::function_arguments_t<typename Method::value_type>>{}, std::forward<T>(service), Method::value);
}
// This function is the do_invoke_service that take the method to invoke as parameter.
template<typename T, typename F, int... S>
void do_invoke_service(detail::seq<S...>, T&& service, F&& function) {
invoke_raw([&service, &function](detail::function_argument_t<S, decay<F>>... args){
(std::forward<T>(service).*std::forward<F>(function))(std::forward<detail::function_argument_t<S, decay<F>>>(args)...);
});
}
template<typename T, disable_if<detail::has_invoke<decay<T>>> = 0>
void invoke_service(T&&) {}
///////////////////////
// instances //
///////////////////////
instance_cont _instances;
service_cont _services;
};
} // namespace kgr
<|endoftext|> |
<commit_before>/*
* SessionClang.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionClang.hpp"
#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/system/System.hpp>
#include <core/system/Process.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionUserSettings.hpp>
#include "libclang/LibClang.hpp"
#include "libclang/UnsavedFiles.hpp"
#include "libclang/SourceIndex.hpp"
#include "CodeCompletion.hpp"
#include "CompilationDatabase.hpp"
using namespace core ;
namespace session {
namespace modules {
namespace clang {
using namespace libclang;
namespace {
bool isCppSourceDoc(const FilePath& filePath)
{
std::string ex = filePath.extensionLowerCase();
return (ex == ".c" || ex == ".cc" || ex == ".cpp" ||
ex == ".m" || ex == ".mm");
}
void onSourceDocUpdated(boost::shared_ptr<source_database::SourceDocument> pDoc)
{
// ignore if the file doesn't have a path
if (pDoc->path().empty())
return;
// resolve to a full path
FilePath docPath = module_context::resolveAliasedPath(pDoc->path());
// verify that it's an indexable C/C++ file (we allow any and all
// files into the database here since these files are open within
// the source editor)
if (!isCppSourceDoc(docPath))
return;
// update unsaved files (we do this even if the document is dirty
// as even in this case it will need to be removed from the list
// of unsaved files)
unsavedFiles().update(pDoc->id(), docPath, pDoc->contents(), pDoc->dirty());
// dirty files indicate active user editing, prime if necessary
if (pDoc->dirty())
{
module_context::scheduleDelayedWork(
boost::posix_time::milliseconds(100),
boost::bind(&SourceIndex::primeTranslationUnit,
&(sourceIndex()), docPath),
true); // require idle
}
}
// diagnostic function to assist in determine whether/where
// libclang was loaded from (and any errors which occurred
// that prevented loading, e.g. inadequate version, missing
// symbols, etc.)
SEXP rs_isLibClangAvailable()
{
// check availability
std::string diagnostics;
bool isAvailable = isLibClangAvailable(&diagnostics);
// print diagnostics
module_context::consoleWriteOutput(diagnostics);
// return status
r::sexp::Protect rProtect;
return r::sexp::create(isAvailable, &rProtect);
}
} // anonymous namespace
bool isAvailable()
{
return clang().isLoaded();
}
Error initialize()
{
// if we don't have a recent version of Rcpp (that can do dryRun with
// sourceCpp) then forget it
if (!module_context::isPackageVersionInstalled("Rcpp", "0.11.3"))
return Success();
// attempt to load clang interface
loadLibClang();
// connect the source index to the compilation database
sourceIndex().initialize(
boost::bind(&CompilationDatabase::argsForSourceFile,
&compilationDatabase(), _1),
session::userSettings().clangVerbose()
);
// register diagnostics function
R_CallMethodDef methodDef ;
methodDef.name = "rs_isLibClangAvailable" ;
methodDef.fun = (DL_FUNC)rs_isLibClangAvailable;
methodDef.numArgs = 0;
r::routines::addCallMethod(methodDef);
// subscribe to source docs events for maintaining the unsaved files list
// main source index and the unsaved files list)
source_database::events().onDocUpdated.connect(onSourceDocUpdated);
source_database::events().onDocRemoved.connect(
boost::bind(&UnsavedFiles::remove, &unsavedFiles(), _1));
source_database::events().onRemoveAll.connect(
boost::bind(&UnsavedFiles::removeAll, &unsavedFiles()));
ExecBlock initBlock ;
using boost::bind;
using namespace module_context;
initBlock.addFunctions()
(bind(sourceModuleRFile, "SessionClang.R"))
(bind(registerRpcMethod, "print_cpp_completions", printCppCompletions));
return initBlock.execute();
// return success
return Success();
}
} // namespace clang
} // namespace modules
} // namesapce session
<commit_msg>correct initialization behavior for libclang not found<commit_after>/*
* SessionClang.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionClang.hpp"
#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/system/System.hpp>
#include <core/system/Process.hpp>
#include <r/RSexp.hpp>
#include <r/RRoutines.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionUserSettings.hpp>
#include "libclang/LibClang.hpp"
#include "libclang/UnsavedFiles.hpp"
#include "libclang/SourceIndex.hpp"
#include "CodeCompletion.hpp"
#include "CompilationDatabase.hpp"
using namespace core ;
namespace session {
namespace modules {
namespace clang {
using namespace libclang;
namespace {
bool isCppSourceDoc(const FilePath& filePath)
{
std::string ex = filePath.extensionLowerCase();
return (ex == ".c" || ex == ".cc" || ex == ".cpp" ||
ex == ".m" || ex == ".mm");
}
void onSourceDocUpdated(boost::shared_ptr<source_database::SourceDocument> pDoc)
{
// ignore if the file doesn't have a path
if (pDoc->path().empty())
return;
// resolve to a full path
FilePath docPath = module_context::resolveAliasedPath(pDoc->path());
// verify that it's an indexable C/C++ file (we allow any and all
// files into the database here since these files are open within
// the source editor)
if (!isCppSourceDoc(docPath))
return;
// update unsaved files (we do this even if the document is dirty
// as even in this case it will need to be removed from the list
// of unsaved files)
unsavedFiles().update(pDoc->id(), docPath, pDoc->contents(), pDoc->dirty());
// dirty files indicate active user editing, prime if necessary
if (pDoc->dirty())
{
module_context::scheduleDelayedWork(
boost::posix_time::milliseconds(100),
boost::bind(&SourceIndex::primeTranslationUnit,
&(sourceIndex()), docPath),
true); // require idle
}
}
const char * const kRequiredRcpp = "0.11.3";
bool haveRequiredRcpp()
{
return module_context::isPackageVersionInstalled("Rcpp", kRequiredRcpp);
}
// diagnostic function to assist in determine whether/where
// libclang was loaded from (and any errors which occurred
// that prevented loading, e.g. inadequate version, missing
// symbols, etc.)
SEXP rs_isLibClangAvailable()
{
bool isAvailable = false;
std::string diagnostics;
// check for required Rcpp
if (haveRequiredRcpp())
{
isAvailable = isLibClangAvailable(&diagnostics);
}
else
{
diagnostics = "Rcpp version " + std::string(kRequiredRcpp) + " or "
"greater is required in order to use libclang.\n";
}
// print diagnostics
module_context::consoleWriteOutput(diagnostics);
// return status
r::sexp::Protect rProtect;
return r::sexp::create(isAvailable, &rProtect);
}
} // anonymous namespace
bool isAvailable()
{
return clang().isLoaded();
}
Error initialize()
{
// register diagnostics function
R_CallMethodDef methodDef ;
methodDef.name = "rs_isLibClangAvailable" ;
methodDef.fun = (DL_FUNC)rs_isLibClangAvailable;
methodDef.numArgs = 0;
r::routines::addCallMethod(methodDef);
// if we don't have a recent version of Rcpp (that can do dryRun with
// sourceCpp) then forget it
if (!haveRequiredRcpp())
return Success();
// attempt to load clang interface
if (!loadLibClang())
return Success();
// connect the source index to the compilation database
sourceIndex().initialize(
boost::bind(&CompilationDatabase::argsForSourceFile,
&compilationDatabase(), _1),
session::userSettings().clangVerbose()
);
// subscribe to source docs events for maintaining the unsaved files list
// main source index and the unsaved files list)
source_database::events().onDocUpdated.connect(onSourceDocUpdated);
source_database::events().onDocRemoved.connect(
boost::bind(&UnsavedFiles::remove, &unsavedFiles(), _1));
source_database::events().onRemoveAll.connect(
boost::bind(&UnsavedFiles::removeAll, &unsavedFiles()));
ExecBlock initBlock ;
using boost::bind;
using namespace module_context;
initBlock.addFunctions()
(bind(sourceModuleRFile, "SessionClang.R"))
(bind(registerRpcMethod, "print_cpp_completions", printCppCompletions));
return initBlock.execute();
}
} // namespace clang
} // namespace modules
} // namesapce session
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkFEMSolver.h"
#include "itkFEMSpatialObjectReader.h"
#include "itkFEMLinearSystemWrapperDenseVNL.h"
#include "itkFEMLinearSystemWrapperItpack.h"
typedef itk::fem::Solver<2> Solver2DType;
bool CheckDisplacements1(Solver2DType *S, int s, double *expectedResults, double tolerance);
void PrintF1(Solver2DType *S, int s);
void PrintNodalCoordinates1(Solver2DType *S, int w);
void PrintK1(Solver2DType *S, int s);
int itkFEMElement2DTest(int argc, char *argv[])
{
if(argc < 1)
{
std::cerr << "Missing Spatial Object Filename" << std::endl;
return EXIT_FAILURE;
}
//Need to register default FEM object types,
//and setup SpatialReader to recognize FEM types
//which is all currently done as a HACK in
//the initializaiton of the itk::FEMFactoryBase::GetFactory()
itk::FEMFactoryBase::GetFactory()->RegisterDefaultTypes();
// Solvers being tested
int numsolvers = 3;
typedef itk::FEMSpatialObjectReader<2> FEMSpatialObjectReaderType;
typedef FEMSpatialObjectReaderType::Pointer FEMSpatialObjectReaderPointer;
FEMSpatialObjectReaderPointer SpatialReader = FEMSpatialObjectReaderType::New();
SpatialReader->SetFileName( argv[1] );
SpatialReader->Update();
FEMSpatialObjectReaderType::ScenePointer myScene = SpatialReader->GetScene();
std::cout << "Scene Test: ";
if( !myScene )
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
// Testing the fe mesh validity
typedef itk::FEMObjectSpatialObject<2> FEMObjectSpatialObjectType;
typedef FEMObjectSpatialObjectType::Pointer FEMObjectSpatialObjectPointer;
FEMObjectSpatialObjectType::ChildrenListType* children = SpatialReader->GetGroup()->GetChildren();
std::cout << "FEM Spatial Object Test: ";
if( strcmp( (*(children->begin() ) )->GetTypeName(), "FEMObjectSpatialObject") )
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
FEMObjectSpatialObjectType::Pointer femSO =
dynamic_cast<FEMObjectSpatialObjectType *>( (*(children->begin() ) ).GetPointer() );
delete children;
femSO->GetFEMObject()->FinalizeMesh();
double * expectedSolution = NULL;
bool foundError = false;
std::string modelFile = itksys::SystemTools::GetFilenameName( argv[1] );
// Define all expected solutions here
double quad2smallExpectedSolution[8] =
{
0, 0,
2.97334e-07, -1.20555e-06,
1.944e-06, -1.32333e-06,
0, 0
};
double quad2strainExpectedSolution[8] =
{
0, 0,
2.56204e-07, -1.02482e-06,
1.67956e-06, -1.19562e-06,
0, 0
};
double quad4ExpectedSolution[8] =
{
0, 0,
0, 0,
0, 0,
0, 0
};
double quad6gravExpectedSolution[8] =
{
0, 0,
0, 0,
-5.32164e-08, 1.59649e-07,
5.32164e-08, 1.59649e-07
};
double quadlmExpectedSolution[8] =
{
0, 0,
-8.76093e-05, -0.0135944,
-0.00420457, 0.00477804,
-0.0163679, -0.0360446,
};
double trapezoidExpectedSolution[8] =
{
0, 0,
0, 0,
0, 0,
0, 0
};
double tri2ExpectedSolution[8] =
{
0, 0,
9.86667e-07, -2.028e-05,
-9.76e-06, -5.67867e-05,
-2.87733e-05, -9.68267e-05
};
double tri3ExpectedSolution[6] =
{
0, 0,
0, 0,
0, 0
};
double tri3eExpectedSolution[6] =
{
0, 0,
0, 0,
0, 0
};
double tri3qExpectedSolution[12] =
{
0, 0,
-3.315e-07, 1.57527e-06,
4.98323e-06, 7.36775e-07,
-5.3625e-08, 2.18676e-06,
8.32488e-07, 1.04065e-06,
5.22113e-07, 2.42889e-06
};
double trussExpectedSolution[11] =
{
0, 0, -0.179399,
0.00169764, -0.478397, 0,
0.00339527, 0, 0.179399,
0.392323, -0.505307
};
// Run the Solver using all of the available numeric solvers
try
{
// Declare the FEM solver & associated input stream and read the
// input file
// Declare and initialize linear system wrapper objects
itk::fem::LinearSystemWrapperDenseVNL lsw_dvnl;
itk::fem::LinearSystemWrapperItpack lsw_itpack;
itk::fem::LinearSystemWrapperVNL lsw_vnl;
for( int s = 0; s < numsolvers; s++ )
{
Solver2DType::Pointer solver = Solver2DType::New();
solver->SetInput( femSO->GetFEMObject() );
if( s == 2 )
{
// Itpack
std::cout << std::endl << ">>>>>Using LinearSystemWrapperItpack" << std::endl;
lsw_itpack.SetMaximumNonZeroValuesInMatrix(1000);
solver->SetLinearSystemWrapper(&lsw_itpack);
}
else if( s == 1 )
{
// Dense VNL
std::cout << std::endl << ">>>>>Using LinearSystemWrapperDenseVNL" << std::endl;
solver->SetLinearSystemWrapper(&lsw_dvnl);
}
else
{
// Sparse VNL - default
std::cout << std::endl << ">>>>>Using LinearSystemWrapperVNL" << std::endl;
solver->SetLinearSystemWrapper(&lsw_vnl);
}
solver->Update();
double tolerance;
if( modelFile == "quad2-small.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad2smallExpectedSolution[0]);
}
else if( modelFile == "quad2-strain.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad2strainExpectedSolution[0]);
}
else if( modelFile == "quad4.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad4ExpectedSolution[0]);
}
else if( modelFile == "quad6-grav.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad6gravExpectedSolution[0]);
}
else if( modelFile == "quad-lm.meta" )
{
tolerance = 10e-7;
expectedSolution = &(quadlmExpectedSolution[0]);
}
else if( modelFile == "trapezoid.meta" )
{
tolerance = 10e-10;
expectedSolution = &(trapezoidExpectedSolution[0]);
}
else if( modelFile == "tri2.meta" )
{
tolerance = 10e-6;
expectedSolution = &(tri2ExpectedSolution[0]);
}
else if( modelFile == "tri3.meta" )
{
tolerance = 10e-10;
expectedSolution = &(tri3ExpectedSolution[0]);
}
else if( modelFile == "tri3-e.meta" )
{
tolerance = 10e-10;
expectedSolution = &(tri3eExpectedSolution[0]);
}
else if( modelFile == "tri3-q.meta" )
{
tolerance = 10e-9;
expectedSolution = &(tri3qExpectedSolution[0]);
}
else if( modelFile == "truss.meta" )
{
tolerance = 10e-7;
expectedSolution = &(trussExpectedSolution[0]);
}
else
{
tolerance = 0.0;
std::cout << "WARNING: Unknown solution for this model, " << modelFile << std::endl;
}
PrintK1(solver, s);
PrintF1(solver, s);
PrintNodalCoordinates1(solver, s);
// itkpack and VNLDense solvers are sensitive to slight numerical
// instabilities on windows. Ignore results for this FE problem
if ( ( modelFile == "tri3-q.meta" ) && ((s == 2) || (s == 1)) )
{
/* itpack does not correctly solve this problem */
if (s== 1)
{
std::cout << "Ignore DenseVNL results for " << modelFile << std::endl;
}
else
{
std::cout << "Ignore itpack results for " << modelFile << std::endl;
}
}
else
{
if( expectedSolution != NULL )
{
bool testError = CheckDisplacements1(solver, s, expectedSolution, tolerance);
if( testError )
{
std::cout << "Displacement Test : [FAILED]" << std::endl;
}
else
{
std::cout << "Displacement Test : [PASSED]" << std::endl;
}
foundError |= testError;
}
}
}
}
catch( ::itk::ExceptionObject & err )
{
std::cerr << "ITK exception detected: " << err;
std::cout << "Test FAILED" << std::endl;
return EXIT_FAILURE;
}
std::cout << std::endl << ">>>>>" << std::endl;
if( foundError )
{
std::cout << "Overall Test : [FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Overall Test : [PASSED]" << std::endl;
return EXIT_SUCCESS;
}
void PrintK1(Solver2DType *S, int s)
{
itk::fem::LinearSystemWrapper::Pointer lsw = S->GetLinearSystemWrapper();
std::cout << std::endl << "k" << s << "=[";
for( unsigned int j = 0; j < lsw->GetSystemOrder(); j++ )
{
std::cout << " [";
for( unsigned int k = 0; k < lsw->GetSystemOrder(); k++ )
{
std::cout << lsw->GetMatrixValue(j, k);
if( (k + 1) < lsw->GetSystemOrder() )
{
std::cout << ", ";
}
}
if( j < lsw->GetSystemOrder() - 1 )
{
std::cout << " ]," << std::endl;
}
else
{
std::cout << "]";
}
}
std::cout << "];" << std::endl;
}
void PrintF1(Solver2DType *S, int s)
// Print F - the global load vector
{
itk::fem::LinearSystemWrapper::Pointer lsw = S->GetLinearSystemWrapper();
std::cout << std::endl << "f" << s << "=[";
for( unsigned int j = 0; j < lsw->GetSystemOrder(); j++ )
{
if( j > 0 )
{
std::cout << ", ";
}
std::cout << lsw->GetVectorValue(j);
}
std::cout << "];" << std::endl;
}
void PrintNodalCoordinates1(Solver2DType *S, int w)
// Print the nodal coordinates
{
std::cout << std::endl << "Nodal coordinates: " << std::endl;
std::cout << "xyz" << w << "=[";
int numberOfNodes = S->GetInput()->GetNumberOfNodes();
for( int i = 0; i < numberOfNodes; i++ )
{
std::cout << " [";
std::cout << S->GetInput()->GetNode(i)->GetCoordinates();
std::cout << "]";
}
std::cout << "];" << std::endl;
}
bool CheckDisplacements1(Solver2DType *S, int s, double *expectedResults, double tolerance)
// Prints the components of the problem for debugging/reporting purposes
{
// std::cout << std::endl << "Check Displacements: " << std::endl;
int numDOF = S->GetInput()->GetNumberOfDegreesOfFreedom();
// std::cout << "Degrees of Freedom : " << numDOF << std::endl;
bool foundError = false;
for( int i = 0; i < numDOF; i++ )
{
double result = S->GetSolution(i);
// std::cout << result << " " << expectedResults[i] << " " << tolerance << std::endl;
if( vcl_fabs(expectedResults[i] - result) > tolerance )
{
std::cout << "ERROR: Solver " << s << " Index " << i << ". Expected " << expectedResults[i] << " Solution "
<< result << std::endl;
foundError = true;
}
}
return foundError;
}
<commit_msg>BUG: Increase tolerance for itkFEMC0TriangularElement-NodalLoads-BCs<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkFEMSolver.h"
#include "itkFEMSpatialObjectReader.h"
#include "itkFEMLinearSystemWrapperDenseVNL.h"
#include "itkFEMLinearSystemWrapperItpack.h"
typedef itk::fem::Solver<2> Solver2DType;
bool CheckDisplacements1(Solver2DType *S, int s, double *expectedResults, double tolerance);
void PrintF1(Solver2DType *S, int s);
void PrintNodalCoordinates1(Solver2DType *S, int w);
void PrintK1(Solver2DType *S, int s);
int itkFEMElement2DTest(int argc, char *argv[])
{
if(argc < 1)
{
std::cerr << "Missing Spatial Object Filename" << std::endl;
return EXIT_FAILURE;
}
//Need to register default FEM object types,
//and setup SpatialReader to recognize FEM types
//which is all currently done as a HACK in
//the initializaiton of the itk::FEMFactoryBase::GetFactory()
itk::FEMFactoryBase::GetFactory()->RegisterDefaultTypes();
// Solvers being tested
int numsolvers = 3;
typedef itk::FEMSpatialObjectReader<2> FEMSpatialObjectReaderType;
typedef FEMSpatialObjectReaderType::Pointer FEMSpatialObjectReaderPointer;
FEMSpatialObjectReaderPointer SpatialReader = FEMSpatialObjectReaderType::New();
SpatialReader->SetFileName( argv[1] );
SpatialReader->Update();
FEMSpatialObjectReaderType::ScenePointer myScene = SpatialReader->GetScene();
std::cout << "Scene Test: ";
if( !myScene )
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
// Testing the fe mesh validity
typedef itk::FEMObjectSpatialObject<2> FEMObjectSpatialObjectType;
typedef FEMObjectSpatialObjectType::Pointer FEMObjectSpatialObjectPointer;
FEMObjectSpatialObjectType::ChildrenListType* children = SpatialReader->GetGroup()->GetChildren();
std::cout << "FEM Spatial Object Test: ";
if( strcmp( (*(children->begin() ) )->GetTypeName(), "FEMObjectSpatialObject") )
{
std::cout << "[FAILED]" << std::endl;
return EXIT_FAILURE;
}
else
{
std::cout << "[PASSED]" << std::endl;
}
FEMObjectSpatialObjectType::Pointer femSO =
dynamic_cast<FEMObjectSpatialObjectType *>( (*(children->begin() ) ).GetPointer() );
delete children;
femSO->GetFEMObject()->FinalizeMesh();
double * expectedSolution = NULL;
bool foundError = false;
std::string modelFile = itksys::SystemTools::GetFilenameName( argv[1] );
// Define all expected solutions here
double quad2smallExpectedSolution[8] =
{
0, 0,
2.97334e-07, -1.20555e-06,
1.944e-06, -1.32333e-06,
0, 0
};
double quad2strainExpectedSolution[8] =
{
0, 0,
2.56204e-07, -1.02482e-06,
1.67956e-06, -1.19562e-06,
0, 0
};
double quad4ExpectedSolution[8] =
{
0, 0,
0, 0,
0, 0,
0, 0
};
double quad6gravExpectedSolution[8] =
{
0, 0,
0, 0,
-5.32164e-08, 1.59649e-07,
5.32164e-08, 1.59649e-07
};
double quadlmExpectedSolution[8] =
{
0, 0,
-8.76093e-05, -0.0135944,
-0.00420457, 0.00477804,
-0.0163679, -0.0360446,
};
double trapezoidExpectedSolution[8] =
{
0, 0,
0, 0,
0, 0,
0, 0
};
double tri2ExpectedSolution[8] =
{
0, 0,
9.86667e-07, -2.028e-05,
-9.76e-06, -5.67867e-05,
-2.87733e-05, -9.68267e-05
};
double tri3ExpectedSolution[6] =
{
0, 0,
0, 0,
0, 0
};
double tri3eExpectedSolution[6] =
{
0, 0,
0, 0,
0, 0
};
double tri3qExpectedSolution[12] =
{
0, 0,
-3.315e-07, 1.57527e-06,
4.98323e-06, 7.36775e-07,
-5.3625e-08, 2.18676e-06,
8.32488e-07, 1.04065e-06,
5.22113e-07, 2.42889e-06
};
double trussExpectedSolution[11] =
{
0, 0, -0.179399,
0.00169764, -0.478397, 0,
0.00339527, 0, 0.179399,
0.392323, -0.505307
};
// Run the Solver using all of the available numeric solvers
try
{
// Declare the FEM solver & associated input stream and read the
// input file
// Declare and initialize linear system wrapper objects
itk::fem::LinearSystemWrapperDenseVNL lsw_dvnl;
itk::fem::LinearSystemWrapperItpack lsw_itpack;
itk::fem::LinearSystemWrapperVNL lsw_vnl;
for( int s = 0; s < numsolvers; s++ )
{
Solver2DType::Pointer solver = Solver2DType::New();
solver->SetInput( femSO->GetFEMObject() );
if( s == 2 )
{
// Itpack
std::cout << std::endl << ">>>>>Using LinearSystemWrapperItpack" << std::endl;
lsw_itpack.SetMaximumNonZeroValuesInMatrix(1000);
solver->SetLinearSystemWrapper(&lsw_itpack);
}
else if( s == 1 )
{
// Dense VNL
std::cout << std::endl << ">>>>>Using LinearSystemWrapperDenseVNL" << std::endl;
solver->SetLinearSystemWrapper(&lsw_dvnl);
}
else
{
// Sparse VNL - default
std::cout << std::endl << ">>>>>Using LinearSystemWrapperVNL" << std::endl;
solver->SetLinearSystemWrapper(&lsw_vnl);
}
solver->Update();
double tolerance;
if( modelFile == "quad2-small.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad2smallExpectedSolution[0]);
}
else if( modelFile == "quad2-strain.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad2strainExpectedSolution[0]);
}
else if( modelFile == "quad4.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad4ExpectedSolution[0]);
}
else if( modelFile == "quad6-grav.meta" )
{
tolerance = 10e-10;
expectedSolution = &(quad6gravExpectedSolution[0]);
}
else if( modelFile == "quad-lm.meta" )
{
tolerance = 10e-7;
expectedSolution = &(quadlmExpectedSolution[0]);
}
else if( modelFile == "trapezoid.meta" )
{
tolerance = 10e-10;
expectedSolution = &(trapezoidExpectedSolution[0]);
}
else if( modelFile == "tri2.meta" )
{
tolerance = 10e-5;
expectedSolution = &(tri2ExpectedSolution[0]);
}
else if( modelFile == "tri3.meta" )
{
tolerance = 10e-10;
expectedSolution = &(tri3ExpectedSolution[0]);
}
else if( modelFile == "tri3-e.meta" )
{
tolerance = 10e-10;
expectedSolution = &(tri3eExpectedSolution[0]);
}
else if( modelFile == "tri3-q.meta" )
{
tolerance = 10e-9;
expectedSolution = &(tri3qExpectedSolution[0]);
}
else if( modelFile == "truss.meta" )
{
tolerance = 10e-7;
expectedSolution = &(trussExpectedSolution[0]);
}
else
{
tolerance = 0.0;
std::cout << "WARNING: Unknown solution for this model, " << modelFile << std::endl;
}
PrintK1(solver, s);
PrintF1(solver, s);
PrintNodalCoordinates1(solver, s);
// itkpack and VNLDense solvers are sensitive to slight numerical
// instabilities on windows. Ignore results for this FE problem
if ( ( modelFile == "tri3-q.meta" ) && ((s == 2) || (s == 1)) )
{
/* itpack does not correctly solve this problem */
if (s== 1)
{
std::cout << "Ignore DenseVNL results for " << modelFile << std::endl;
}
else
{
std::cout << "Ignore itpack results for " << modelFile << std::endl;
}
}
else
{
if( expectedSolution != NULL )
{
bool testError = CheckDisplacements1(solver, s, expectedSolution, tolerance);
if( testError )
{
std::cout << "Displacement Test : [FAILED]" << std::endl;
}
else
{
std::cout << "Displacement Test : [PASSED]" << std::endl;
}
foundError |= testError;
}
}
}
}
catch( ::itk::ExceptionObject & err )
{
std::cerr << "ITK exception detected: " << err;
std::cout << "Test FAILED" << std::endl;
return EXIT_FAILURE;
}
std::cout << std::endl << ">>>>>" << std::endl;
if( foundError )
{
std::cout << "Overall Test : [FAILED]" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Overall Test : [PASSED]" << std::endl;
return EXIT_SUCCESS;
}
void PrintK1(Solver2DType *S, int s)
{
itk::fem::LinearSystemWrapper::Pointer lsw = S->GetLinearSystemWrapper();
std::cout << std::endl << "k" << s << "=[";
for( unsigned int j = 0; j < lsw->GetSystemOrder(); j++ )
{
std::cout << " [";
for( unsigned int k = 0; k < lsw->GetSystemOrder(); k++ )
{
std::cout << lsw->GetMatrixValue(j, k);
if( (k + 1) < lsw->GetSystemOrder() )
{
std::cout << ", ";
}
}
if( j < lsw->GetSystemOrder() - 1 )
{
std::cout << " ]," << std::endl;
}
else
{
std::cout << "]";
}
}
std::cout << "];" << std::endl;
}
void PrintF1(Solver2DType *S, int s)
// Print F - the global load vector
{
itk::fem::LinearSystemWrapper::Pointer lsw = S->GetLinearSystemWrapper();
std::cout << std::endl << "f" << s << "=[";
for( unsigned int j = 0; j < lsw->GetSystemOrder(); j++ )
{
if( j > 0 )
{
std::cout << ", ";
}
std::cout << lsw->GetVectorValue(j);
}
std::cout << "];" << std::endl;
}
void PrintNodalCoordinates1(Solver2DType *S, int w)
// Print the nodal coordinates
{
std::cout << std::endl << "Nodal coordinates: " << std::endl;
std::cout << "xyz" << w << "=[";
int numberOfNodes = S->GetInput()->GetNumberOfNodes();
for( int i = 0; i < numberOfNodes; i++ )
{
std::cout << " [";
std::cout << S->GetInput()->GetNode(i)->GetCoordinates();
std::cout << "]";
}
std::cout << "];" << std::endl;
}
bool CheckDisplacements1(Solver2DType *S, int s, double *expectedResults, double tolerance)
// Prints the components of the problem for debugging/reporting purposes
{
// std::cout << std::endl << "Check Displacements: " << std::endl;
int numDOF = S->GetInput()->GetNumberOfDegreesOfFreedom();
// std::cout << "Degrees of Freedom : " << numDOF << std::endl;
bool foundError = false;
for( int i = 0; i < numDOF; i++ )
{
double result = S->GetSolution(i);
// std::cout << result << " " << expectedResults[i] << " " << tolerance << std::endl;
if( vcl_fabs(expectedResults[i] - result) > tolerance )
{
std::cout << "ERROR: Solver " << s << " Index " << i << ". Expected " << expectedResults[i] << " Solution "
<< result << std::endl;
foundError = true;
}
}
return foundError;
}
<|endoftext|> |
<commit_before>#include <lug/Window/Android/WindowImplAndroid.hpp>
namespace lug {
namespace Window {
namespace priv {
std::queue<lug::Window::Event> WindowImpl::events;
AInputQueue* WindowImpl::inputQueue = nullptr;
ANativeWindow* WindowImpl::nativeWindow = nullptr;
ANativeActivity* WindowImpl::activity = nullptr;
WindowImpl::WindowImpl(Window* win) : _parent{win} {}
bool WindowImpl::init(const Window::InitInfo&) {
_parent->_mode.width = ANativeWindow_getWidth(nativeWindow);
_parent->_mode.height = ANativeWindow_getHeight(nativeWindow);
return true;
}
void WindowImpl::close() {}
ANativeWindow* WindowImpl::getWindow() {
return nativeWindow;
}
bool WindowImpl::pollEvent(lug::Window::Event& event) {
if (inputQueue != nullptr) {
AInputEvent* androidEvent = nullptr;
while (AInputQueue_getEvent(inputQueue, &androidEvent) >= 0) {
if (AInputQueue_preDispatchEvent(inputQueue, androidEvent)) {
continue;
}
AInputQueue_finishEvent(inputQueue, androidEvent, 0);
}
}
if (!events.empty()) {
event = events.front();
events.pop();
return true;
}
return false;
}
void WindowImpl::setKeyRepeat(bool state) {
(void)state;
// TODO
}
void WindowImpl::setMouseCursorVisible(bool visible) {
(void)visible;
// TODO
}
void WindowImpl::setMousePos(const Math::Vec2i& mousePosition) {
(void)mousePosition;
// TODO
}
} // namespace priv
} // namespace Window
} // namespace lug
<commit_msg>added touch event<commit_after>#include <lug/Window/Android/WindowImplAndroid.hpp>
namespace lug {
namespace Window {
namespace priv {
std::queue<lug::Window::Event> WindowImpl::events;
AInputQueue* WindowImpl::inputQueue = nullptr;
ANativeWindow* WindowImpl::nativeWindow = nullptr;
ANativeActivity* WindowImpl::activity = nullptr;
WindowImpl::WindowImpl(Window* win) : _parent{win} {}
bool WindowImpl::init(const Window::InitInfo&) {
_parent->_mode.width = ANativeWindow_getWidth(nativeWindow);
_parent->_mode.height = ANativeWindow_getHeight(nativeWindow);
return true;
}
void WindowImpl::close() {}
ANativeWindow* WindowImpl::getWindow() {
return nativeWindow;
}
bool WindowImpl::pollEvent(lug::Window::Event& event) {
if (inputQueue != nullptr) {
AInputEvent* androidEvent = nullptr;
while (AInputQueue_getEvent(inputQueue, &androidEvent) >= 0) {
if (AInputQueue_preDispatchEvent(inputQueue, androidEvent)) {
continue;
}
switch (AInputEvent_getType(androidEvent) ) {
case AINPUT_EVENT_TYPE_MOTION:
event.mouse.code = Mouse::Button::Left;
event.mouse.coord.x = AMotionEvent_getX(androidEvent, 0);
event.mouse.coord.y = AMotionEvent_getY(androidEvent, 0);
switch (AKeyEvent_getAction(androidEvent)) {
case AKEY_EVENT_ACTION_DOWN:
event.type = Event::Type::ButtonPressed;
break;
case AKEY_EVENT_ACTION_UP:
event.type = Event::Type::ButtonReleased;
break;
default:
break;
}
break;
default:
break;
}
AInputQueue_finishEvent(inputQueue, androidEvent, 0);
}
}
if (!events.empty()) {
event = events.front();
events.pop();
return true;
}
return false;
}
void WindowImpl::setKeyRepeat(bool state) {
(void)state;
// TODO
}
void WindowImpl::setMouseCursorVisible(bool visible) {
(void)visible;
// TODO
}
void WindowImpl::setMousePos(const Math::Vec2i& mousePosition) {
(void)mousePosition;
// TODO
}
} // namespace priv
} // namespace Window
} // namespace lug
<|endoftext|> |
<commit_before>//Written by Steven An
//Apache Licence
//implementation of complex long long integer object
#include "complex-llong.h"
#include<iostream>
//Constructors
Complex_llong::Complex_llong(void){
real = imag = 0LL;
are_squared = false;
}
Complex_llong::Complex_llong(long long real, long long imag){
this->real = real;
this->imag = imag;
are_squared = false;
}
Complex_llong::Complex_llong(const Complex_llong op){
real = op.real;
imag = op.imag;
are_squared = op.are_squared;
}
//Member functions
void Complex_llong::set(long long real, long long imag);
this->real = real;
this->imag = imag;
are_squared = false;
}
Complex_llong& Complex_llong::operator=(const Complex_llong& op){
if(&op == this)
return *this;
real = op.real;
imag = op.imag
are_squared = op.are_squared;
}
Complex_llong& Complex_llong::operator+=(const Complex_llong& op){
real = real + op.real;
imag = imag + op.imag;
return *this;
}
Complex_llong& Complex_llong::operator-=(const Complex_llong& op){
real = real - op.real;
imag = imag - op.imag;
return *this;
}
Complex_llong& Complex_llong::operator*=(const Complex_llong& op){
long long real_tmp, imag_tmp;
real_tmp = real;
imag_tmp = imag;
real = real_tmp * op.real - imag_tmp * op.imag;
imag = real_tmp * op.imag + imag_tmp * op.real;
}
Complex_llong operator+(const Complex_llong& op1, const Complex_llong& op2){
Complex_llong tmp(op1.real, op1.imag);
return tmp += op2;
}
Complex_llong operator-(const Complex_llong& op1, const Complex_llong& op2){
Complex_llong tmp(op1.real, op1.imag);
return tmp -= op2;
}
Complex_llong operator*(const Complex_llong& op1, const Complex_llong& op2){
Complex_llong tmp(op1.real, op1.imag);
return tmp *= op2;
}
std::ostream& operator<<(std::ostream& os, const Complex_llong& op){
os << "real: " << op.real << " imag: " << op.imag << std::endl;
return os;
}
std::istream& operator>>(std::istream& is, Complex_llong& op){
long long re, im;
bool sq;
std::cin >> re >> im >> sq;
if (std::cin){
op.real = re;
op.imag = im;
op.are_squared = sq;
} else {
//throw an exception for bad input
}
return is;
}
<commit_msg>finish implementation (pre-testing)<commit_after>//Written by Steven An
//Apache Licence
//implementation of complex long long integer object
#include "complex-llong.h"
#include<iostream>
//Constructors
Complex_llong::Complex_llong(void){
real = imag = 0LL;
are_squared = false;
}
Complex_llong::Complex_llong(long long real, long long imag){
this->real = real;
this->imag = imag;
are_squared = false;
}
Complex_llong::Complex_llong(const Complex_llong op){
real = op.real;
imag = op.imag;
are_squared = op.are_squared;
}
//Member functions
void Complex_llong::set(long long real, long long imag);
this->real = real;
this->imag = imag;
are_squared = false;
}
Complex_llong& Complex_llong::operator=(const Complex_llong& op){
if(&op == this)
return *this;
real = op.real;
imag = op.imag
are_squared = op.are_squared;
}
Complex_llong& Complex_llong::operator+=(const Complex_llong& op){
real = real + op.real;
imag = imag + op.imag;
return *this;
}
Complex_llong& Complex_llong::operator-=(const Complex_llong& op){
real = real - op.real;
imag = imag - op.imag;
return *this;
}
Complex_llong& Complex_llong::operator*=(const Complex_llong& op){
long long real_tmp, imag_tmp;
real_tmp = real;
imag_tmp = imag;
real = real_tmp * op.real - imag_tmp * op.imag;
imag = real_tmp * op.imag + imag_tmp * op.real;
}
Complex_llong operator+(const Complex_llong& op1, const Complex_llong& op2){
Complex_llong tmp(op1.real, op1.imag);
return tmp += op2;
}
Complex_llong operator-(const Complex_llong& op1, const Complex_llong& op2){
Complex_llong tmp(op1.real, op1.imag);
return tmp -= op2;
}
Complex_llong operator*(const Complex_llong& op1, const Complex_llong& op2){
Complex_llong tmp(op1.real, op1.imag);
return tmp *= op2;
}
std::ostream& operator<<(std::ostream& os, const Complex_llong& op){
os << "real: " << op.real << " imag: " << op.imag << std::endl;
return os;
}
std::istream& operator>>(std::istream& is, Complex_llong& op){
long long re, im;
bool sq;
std::cin >> re >> im >> sq;
if (std::cin){
op.real = re;
op.imag = im;
op.are_squared = sq;
} else {
throw std::invalid_argument("invalid input");
}
return is;
}
void Complex_llong::conjugate(Complex_llong& op){
op.imag = -1 * imag;
}
void Complex_llong::norm2(Complex_llong& op){
op.real = op.real * op.real;
op.imag = op.imag * op.imag;
op.are_squared = true;
}
<|endoftext|> |
<commit_before>#include "search_index_builder.hpp"
#include "feature_utils.hpp"
#include "features_vector.hpp"
#include "search_delimiters.hpp"
#include "search_trie.hpp"
#include "search_string_utils.hpp"
#include "string_file.hpp"
#include "classificator.hpp"
#include "feature_visibility.hpp"
#include "../defines.hpp"
#include "../platform/platform.hpp"
#include "../coding/trie_builder.hpp"
#include "../coding/writer.hpp"
#include "../coding/reader_writer_ops.hpp"
#include "../base/string_utils.hpp"
#include "../base/logging.hpp"
#include "../std/algorithm.hpp"
#include "../std/vector.hpp"
namespace
{
struct FeatureNameInserter
{
StringsFile & m_names;
StringsFile::ValueT m_val;
FeatureNameInserter(StringsFile & names) : m_names(names) {}
void AddToken(signed char lang, strings::UniString const & s) const
{
m_names.AddString(StringsFile::StringT(s, lang, m_val));
}
bool operator()(signed char lang, string const & name) const
{
strings::UniString const uniName = search::NormalizeAndSimplifyString(name);
buffer_vector<strings::UniString, 32> tokens;
SplitUniString(uniName, MakeBackInsertFunctor(tokens), search::Delimiters());
/// @todo MAX_TOKENS = 32, in Query::Search we use 31 + prefix. Why 30 ???
if (tokens.size() > 30)
{
LOG(LWARNING, ("Name has too many tokens:", name));
tokens.resize(30);
}
for (size_t i = 0; i < tokens.size(); ++i)
AddToken(lang, tokens[i]);
return true;
}
};
class FeatureInserter
{
StringsFile & m_names;
typedef StringsFile::ValueT ValueT;
typedef search::trie::ValueReader SaverT;
SaverT m_valueSaver;
pair<int, int> m_scales;
class CalcPolyCenter
{
typedef m2::PointD P;
struct Value
{
Value(P const & p, double l) : m_p(p), m_len(l) {}
bool operator< (Value const & r) const { return (m_len < r.m_len); }
P m_p;
double m_len;
};
vector<Value> m_poly;
double m_length;
public:
CalcPolyCenter() : m_length(0.0) {}
void operator() (CoordPointT const & pt)
{
m2::PointD p(pt.first, pt.second);
m_length += (m_poly.empty() ? 0.0 : m_poly.back().m_p.Length(p));
m_poly.push_back(Value(p, m_length));
}
P GetCenter() const
{
typedef vector<Value>::const_iterator IterT;
double const l = m_length / 2.0;
IterT e = lower_bound(m_poly.begin(), m_poly.end(), Value(m2::PointD(0, 0), l));
if (e == m_poly.begin())
{
/// @todo It's very strange, but we have linear objects with zero length.
LOG(LWARNING, ("Zero length linear object"));
return e->m_p;
}
IterT b = e-1;
double const f = (l - b->m_len) / (e->m_len - b->m_len);
ASSERT ( 0.0 <= f && f <= 1.0, (f) );
return (b->m_p * (1-f) + e->m_p * f);
}
};
class CalcMassCenter
{
typedef m2::PointD P;
P m_center;
size_t m_count;
public:
CalcMassCenter() : m_count(0) {}
void operator() (P const & p1, P const & p2, P const & p3)
{
++m_count;
m_center += p1;
m_center += p2;
m_center += p3;
}
P GetCenter() const { return m_center / (3*m_count); }
};
m2::PointD GetCenter(FeatureType const & f) const
{
feature::EGeomType const type = f.GetFeatureType();
switch (type)
{
case feature::GEOM_POINT:
return f.GetCenter();
case feature::GEOM_LINE:
{
CalcPolyCenter doCalc;
f.ForEachPointRef(doCalc, -1);
return doCalc.GetCenter();
}
default:
{
ASSERT_EQUAL ( type, feature::GEOM_AREA, () );
CalcMassCenter doCalc;
f.ForEachTriangleRef(doCalc, -1);
return doCalc.GetCenter();
}
}
}
void MakeValue(FeatureType const & f, feature::TypesHolder const & types,
uint64_t pos, ValueT & value) const
{
SaverT::ValueType v;
v.m_featureId = static_cast<uint32_t>(pos);
// get BEST geometry rect of feature
v.m_pt = GetCenter(f);
v.m_rank = feature::GetSearchRank(types, v.m_pt, f.GetPopulation());
// write to buffer
PushBackByteSink<ValueT> sink(value);
m_valueSaver.Save(sink, v);
}
class AvoidEmptyName
{
vector<uint32_t> m_vec;
public:
AvoidEmptyName()
{
char const * arr[][3] = {
{ "place", "city", ""},
{ "place", "city", "capital"},
{ "place", "town", ""},
{ "place", "county", ""},
{ "place", "state", ""},
{ "place", "region", ""}
};
Classificator const & c = classif();
size_t const count = ARRAY_SIZE(arr);
m_vec.reserve(count);
for (size_t i = 0; i < count; ++i)
{
vector<string> v;
v.push_back(arr[i][0]);
v.push_back(arr[i][1]);
if (strlen(arr[i][2]) > 0)
v.push_back(arr[i][2]);
m_vec.push_back(c.GetTypeByPath(v));
}
}
bool IsExist(feature::TypesHolder const & types) const
{
for (size_t i = 0; i < m_vec.size(); ++i)
if (types.Has(m_vec[i]))
return true;
return false;
}
};
public:
FeatureInserter(StringsFile & names,
serial::CodingParams const & cp,
pair<int, int> const & scales)
: m_names(names), m_valueSaver(cp), m_scales(scales)
{
}
void operator() (FeatureType const & f, uint64_t pos) const
{
feature::TypesHolder types(f);
// init inserter with serialized value
FeatureNameInserter inserter(m_names);
MakeValue(f, types, pos, inserter.m_val);
// add names of the feature
if (!f.ForEachNameRef(inserter))
{
static AvoidEmptyName check;
if (check.IsExist(types))
{
// Do not add such features without names to suggestion list.
return;
}
}
// add names of categories of the feature
for (size_t i = 0; i < types.Size(); ++i)
{
// Do index only for visible types in mwm.
pair<int, int> const r = feature::DrawableScaleRangeForType(types[i]);
if (my::between_s(m_scales.first, m_scales.second, r.first) ||
my::between_s(m_scales.first, m_scales.second, r.second))
{
inserter.AddToken(search::CATEGORIES_LANG, search::FeatureTypeToString(types[i]));
}
}
}
};
} // unnamed namespace
void indexer::BuildSearchIndex(FeaturesVector const & featuresV, Writer & writer,
string const & tmpFilePath)
{
{
StringsFile names(tmpFilePath);
serial::CodingParams cp(search::GetCPForTrie(featuresV.GetCodingParams()));
featuresV.ForEachOffset(FeatureInserter(names, cp, featuresV.GetScaleRange()));
names.EndAdding();
names.OpenForRead();
trie::Build(writer, names.Begin(), names.End(), trie::builder::EmptyEdgeBuilder());
// at this point all readers of StringsFile should be dead
}
FileWriter::DeleteFileX(tmpFilePath);
}
bool indexer::BuildSearchIndexFromDatFile(string const & fName)
{
LOG(LINFO, ("Start building search index. Bits = ", search::POINT_CODING_BITS));
try
{
Platform & pl = GetPlatform();
string const datFile = pl.WritablePathForFile(fName);
string const tmpFile = pl.WritablePathForFile(fName + ".search_index_2.tmp");
{
FilesContainerR readCont(datFile);
feature::DataHeader header;
header.Load(readCont.GetReader(HEADER_FILE_TAG));
FeaturesVector featuresVector(readCont, header);
FileWriter writer(tmpFile);
BuildSearchIndex(featuresVector, writer, pl.WritablePathForFile(fName + ".search_index_1.tmp"));
LOG(LINFO, ("Search index size = ", writer.Size()));
}
{
// Write to container in reversed order.
FilesContainerW writeCont(datFile, FileWriter::OP_WRITE_EXISTING);
FileWriter writer = writeCont.GetWriter(SEARCH_INDEX_FILE_TAG);
rw_ops::Reverse(FileReader(tmpFile), writer);
}
FileWriter::DeleteFileX(tmpFile);
}
catch (Reader::Exception const & e)
{
LOG(LERROR, ("Error while reading file: ", e.what()));
return false;
}
catch (Writer::Exception const & e)
{
LOG(LERROR, ("Error writing index file: ", e.what()));
return false;
}
LOG(LINFO, ("End building search index."));
return true;
}
<commit_msg>[search] Do comparison instead of assert (for safety in floating point calculations).<commit_after>#include "search_index_builder.hpp"
#include "feature_utils.hpp"
#include "features_vector.hpp"
#include "search_delimiters.hpp"
#include "search_trie.hpp"
#include "search_string_utils.hpp"
#include "string_file.hpp"
#include "classificator.hpp"
#include "feature_visibility.hpp"
#include "../defines.hpp"
#include "../platform/platform.hpp"
#include "../coding/trie_builder.hpp"
#include "../coding/writer.hpp"
#include "../coding/reader_writer_ops.hpp"
#include "../base/string_utils.hpp"
#include "../base/logging.hpp"
#include "../std/algorithm.hpp"
#include "../std/vector.hpp"
namespace
{
struct FeatureNameInserter
{
StringsFile & m_names;
StringsFile::ValueT m_val;
FeatureNameInserter(StringsFile & names) : m_names(names) {}
void AddToken(signed char lang, strings::UniString const & s) const
{
m_names.AddString(StringsFile::StringT(s, lang, m_val));
}
bool operator()(signed char lang, string const & name) const
{
strings::UniString const uniName = search::NormalizeAndSimplifyString(name);
buffer_vector<strings::UniString, 32> tokens;
SplitUniString(uniName, MakeBackInsertFunctor(tokens), search::Delimiters());
/// @todo MAX_TOKENS = 32, in Query::Search we use 31 + prefix. Why 30 ???
if (tokens.size() > 30)
{
LOG(LWARNING, ("Name has too many tokens:", name));
tokens.resize(30);
}
for (size_t i = 0; i < tokens.size(); ++i)
AddToken(lang, tokens[i]);
return true;
}
};
class FeatureInserter
{
StringsFile & m_names;
typedef StringsFile::ValueT ValueT;
typedef search::trie::ValueReader SaverT;
SaverT m_valueSaver;
pair<int, int> m_scales;
class CalcPolyCenter
{
typedef m2::PointD P;
struct Value
{
Value(P const & p, double l) : m_p(p), m_len(l) {}
bool operator< (Value const & r) const { return (m_len < r.m_len); }
P m_p;
double m_len;
};
vector<Value> m_poly;
double m_length;
public:
CalcPolyCenter() : m_length(0.0) {}
void operator() (CoordPointT const & pt)
{
m2::PointD p(pt.first, pt.second);
m_length += (m_poly.empty() ? 0.0 : m_poly.back().m_p.Length(p));
m_poly.push_back(Value(p, m_length));
}
P GetCenter() const
{
typedef vector<Value>::const_iterator IterT;
double const l = m_length / 2.0;
IterT e = lower_bound(m_poly.begin(), m_poly.end(), Value(m2::PointD(0, 0), l));
if (e == m_poly.begin())
{
/// @todo It's very strange, but we have linear objects with zero length.
LOG(LWARNING, ("Zero length linear object"));
return e->m_p;
}
IterT b = e-1;
double const f = (l - b->m_len) / (e->m_len - b->m_len);
// For safety reasons (floating point calculations) do comparison instead of ASSERT.
if (0.0 <= f && f <= 1.0)
return (b->m_p * (1-f) + e->m_p * f);
else
return ((b->m_p + e->m_p) / 2.0);
}
};
class CalcMassCenter
{
typedef m2::PointD P;
P m_center;
size_t m_count;
public:
CalcMassCenter() : m_count(0) {}
void operator() (P const & p1, P const & p2, P const & p3)
{
++m_count;
m_center += p1;
m_center += p2;
m_center += p3;
}
P GetCenter() const { return m_center / (3*m_count); }
};
m2::PointD GetCenter(FeatureType const & f) const
{
feature::EGeomType const type = f.GetFeatureType();
switch (type)
{
case feature::GEOM_POINT:
return f.GetCenter();
case feature::GEOM_LINE:
{
CalcPolyCenter doCalc;
f.ForEachPointRef(doCalc, -1);
return doCalc.GetCenter();
}
default:
{
ASSERT_EQUAL ( type, feature::GEOM_AREA, () );
CalcMassCenter doCalc;
f.ForEachTriangleRef(doCalc, -1);
return doCalc.GetCenter();
}
}
}
void MakeValue(FeatureType const & f, feature::TypesHolder const & types,
uint64_t pos, ValueT & value) const
{
SaverT::ValueType v;
v.m_featureId = static_cast<uint32_t>(pos);
// get BEST geometry rect of feature
v.m_pt = GetCenter(f);
v.m_rank = feature::GetSearchRank(types, v.m_pt, f.GetPopulation());
// write to buffer
PushBackByteSink<ValueT> sink(value);
m_valueSaver.Save(sink, v);
}
class AvoidEmptyName
{
vector<uint32_t> m_vec;
public:
AvoidEmptyName()
{
char const * arr[][3] = {
{ "place", "city", ""},
{ "place", "city", "capital"},
{ "place", "town", ""},
{ "place", "county", ""},
{ "place", "state", ""},
{ "place", "region", ""}
};
Classificator const & c = classif();
size_t const count = ARRAY_SIZE(arr);
m_vec.reserve(count);
for (size_t i = 0; i < count; ++i)
{
vector<string> v;
v.push_back(arr[i][0]);
v.push_back(arr[i][1]);
if (strlen(arr[i][2]) > 0)
v.push_back(arr[i][2]);
m_vec.push_back(c.GetTypeByPath(v));
}
}
bool IsExist(feature::TypesHolder const & types) const
{
for (size_t i = 0; i < m_vec.size(); ++i)
if (types.Has(m_vec[i]))
return true;
return false;
}
};
public:
FeatureInserter(StringsFile & names,
serial::CodingParams const & cp,
pair<int, int> const & scales)
: m_names(names), m_valueSaver(cp), m_scales(scales)
{
}
void operator() (FeatureType const & f, uint64_t pos) const
{
feature::TypesHolder types(f);
// init inserter with serialized value
FeatureNameInserter inserter(m_names);
MakeValue(f, types, pos, inserter.m_val);
// add names of the feature
if (!f.ForEachNameRef(inserter))
{
static AvoidEmptyName check;
if (check.IsExist(types))
{
// Do not add such features without names to suggestion list.
return;
}
}
// add names of categories of the feature
for (size_t i = 0; i < types.Size(); ++i)
{
// Do index only for visible types in mwm.
pair<int, int> const r = feature::DrawableScaleRangeForType(types[i]);
if (my::between_s(m_scales.first, m_scales.second, r.first) ||
my::between_s(m_scales.first, m_scales.second, r.second))
{
inserter.AddToken(search::CATEGORIES_LANG, search::FeatureTypeToString(types[i]));
}
}
}
};
} // unnamed namespace
void indexer::BuildSearchIndex(FeaturesVector const & featuresV, Writer & writer,
string const & tmpFilePath)
{
{
StringsFile names(tmpFilePath);
serial::CodingParams cp(search::GetCPForTrie(featuresV.GetCodingParams()));
featuresV.ForEachOffset(FeatureInserter(names, cp, featuresV.GetScaleRange()));
names.EndAdding();
names.OpenForRead();
trie::Build(writer, names.Begin(), names.End(), trie::builder::EmptyEdgeBuilder());
// at this point all readers of StringsFile should be dead
}
FileWriter::DeleteFileX(tmpFilePath);
}
bool indexer::BuildSearchIndexFromDatFile(string const & fName)
{
LOG(LINFO, ("Start building search index. Bits = ", search::POINT_CODING_BITS));
try
{
Platform & pl = GetPlatform();
string const datFile = pl.WritablePathForFile(fName);
string const tmpFile = pl.WritablePathForFile(fName + ".search_index_2.tmp");
{
FilesContainerR readCont(datFile);
feature::DataHeader header;
header.Load(readCont.GetReader(HEADER_FILE_TAG));
FeaturesVector featuresVector(readCont, header);
FileWriter writer(tmpFile);
BuildSearchIndex(featuresVector, writer, pl.WritablePathForFile(fName + ".search_index_1.tmp"));
LOG(LINFO, ("Search index size = ", writer.Size()));
}
{
// Write to container in reversed order.
FilesContainerW writeCont(datFile, FileWriter::OP_WRITE_EXISTING);
FileWriter writer = writeCont.GetWriter(SEARCH_INDEX_FILE_TAG);
rw_ops::Reverse(FileReader(tmpFile), writer);
}
FileWriter::DeleteFileX(tmpFile);
}
catch (Reader::Exception const & e)
{
LOG(LERROR, ("Error while reading file: ", e.what()));
return false;
}
catch (Writer::Exception const & e)
{
LOG(LERROR, ("Error writing index file: ", e.what()));
return false;
}
LOG(LINFO, ("End building search index."));
return true;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include <QtGui/QPainter>
#include "texteditoroverlay.h"
#include <QDebug>
using namespace TextEditor;
using namespace TextEditor::Internal;
TextEditorOverlay::TextEditorOverlay(BaseTextEditor *editor)
:QObject(editor) {
m_visible = false;
m_borderWidth = 1;
m_dropShadowWidth = 2;
m_editor = editor;
m_alpha = true;
m_viewport = editor->viewport();
}
void TextEditorOverlay::update()
{
if (m_visible)
m_viewport->update();
}
void TextEditorOverlay::setVisible(bool b)
{
if (m_visible == b)
return;
m_visible = b;
update();
}
void TextEditorOverlay::clear()
{
if (m_selections.isEmpty())
return;
m_selections.clear();
update();
}
void TextEditorOverlay::addOverlaySelection(int begin, int end,
const QColor &fg, const QColor &bg,
bool lockSize,
bool dropShadow)
{
if (end < begin)
return;
QTextDocument *document = m_editor->document();
OverlaySelection selection;
selection.m_fg = fg;
selection.m_bg = bg;
selection.m_cursor_begin = QTextCursor(document->docHandle(), begin);
selection.m_cursor_end = QTextCursor(document->docHandle(), end);
if (lockSize)
selection.m_fixedLength = (end - begin);
selection.m_dropShadow = dropShadow;
if (dropShadow)
m_selections.append(selection);
else
m_selections.prepend(selection);
update();
}
void TextEditorOverlay::addOverlaySelection(const QTextCursor &cursor,
const QColor &fg, const QColor &bg, bool lockSize)
{
addOverlaySelection(cursor.selectionStart(), cursor.selectionEnd(), fg, bg, lockSize);
}
QRect TextEditorOverlay::rect() const
{
return m_viewport->rect();
}
QPainterPath TextEditorOverlay::createSelectionPath(const QTextCursor &begin, const QTextCursor &end,
const QRect &clip)
{
if (begin.isNull() || end.isNull() || begin.position() > end.position())
return QPainterPath();
QPointF offset = m_editor->contentOffset();
QRect viewportRect = rect();
QTextDocument *document = m_editor->document();
if (m_editor->blockBoundingGeometry(begin.block()).translated(offset).top() > clip.bottom() + 10
|| m_editor->blockBoundingGeometry(end.block()).translated(offset).bottom() < clip.top() - 10
)
return QPainterPath(); // nothing of the selection is visible
QTextBlock block = begin.block();
bool inSelection = false;
QVector<QRectF> selection;
if (begin.position() == end.position()) {
// special case empty selections
const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
QTextLayout *blockLayout = block.layout();
int pos = begin.position() - begin.block().position();
QTextLine line = blockLayout->lineForTextPosition(pos);
QRectF lineRect = line.naturalTextRect();
int x = line.cursorToX(pos);
lineRect.setLeft(x - m_borderWidth);
lineRect.setRight(x + m_borderWidth);
selection += lineRect.translated(blockGeometry.topLeft());
} else {
for (; block.isValid() && block.blockNumber() <= end.blockNumber(); block = block.next()) {
if (! block.isVisible())
continue;
const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
QTextLayout *blockLayout = block.layout();
QTextLine line = blockLayout->lineAt(0);
int beginChar = 0;
if (!inSelection) {
beginChar = begin.position() - begin.block().position();
line = blockLayout->lineForTextPosition(beginChar);
inSelection = true;
} else {
while (beginChar < block.length() && document->characterAt(block.position() + beginChar).isSpace())
++beginChar;
if (beginChar == block.length())
beginChar = 0;
}
int lastLine = blockLayout->lineCount()-1;
int endChar = -1;
if (block == end.block()) {
endChar = end.position() - end.block().position();
lastLine = blockLayout->lineForTextPosition(endChar).lineNumber();
inSelection = false;
} else {
endChar = block.length();
while (endChar > beginChar && document->characterAt(block.position() + endChar - 1).isSpace())
--endChar;
}
QRectF lineRect = line.naturalTextRect();
if (beginChar < endChar) {
lineRect.setLeft(line.cursorToX(beginChar));
if (line.lineNumber() == lastLine)
lineRect.setRight(line.cursorToX(endChar));
selection += lineRect.translated(blockGeometry.topLeft());
for (int lineIndex = line.lineNumber()+1; lineIndex <= lastLine; ++lineIndex) {
line = blockLayout->lineAt(lineIndex);
lineRect = line.naturalTextRect();
if (lineIndex == lastLine)
lineRect.setRight(line.cursorToX(endChar));
selection += lineRect.translated(blockGeometry.topLeft());
}
} else { // empty lines
if (!selection.isEmpty())
lineRect.setLeft(selection.last().left());
lineRect.setRight(lineRect.left() + 16);
selection += lineRect.translated(blockGeometry.topLeft());
}
if (!inSelection)
break;
if (blockGeometry.translated(offset).y() > 2*viewportRect.height())
break;
}
}
if (selection.isEmpty())
return QPainterPath();
QVector<QPointF> points;
const int margin = m_borderWidth/2;
const int extra = 0;
points += (selection.at(0).topLeft() + selection.at(0).topRight()) / 2 + QPointF(0, -margin);
points += selection.at(0).topRight() + QPointF(margin+1, -margin);
points += selection.at(0).bottomRight() + QPointF(margin+1, 0);
for(int i = 1; i < selection.count()-1; ++i) {
#define MAX3(a,b,c) qMax(a, qMax(b,c))
qreal x = MAX3(selection.at(i-1).right(),
selection.at(i).right(),
selection.at(i+1).right()) + margin;
points += QPointF(x+1, selection.at(i).top());
points += QPointF(x+1, selection.at(i).bottom());
}
points += selection.at(selection.count()-1).topRight() + QPointF(margin+1, 0);
points += selection.at(selection.count()-1).bottomRight() + QPointF(margin+1, margin+extra);
points += selection.at(selection.count()-1).bottomLeft() + QPointF(-margin, margin+extra);
points += selection.at(selection.count()-1).topLeft() + QPointF(-margin, 0);
for(int i = selection.count()-2; i > 0; --i) {
#define MIN3(a,b,c) qMin(a, qMin(b,c))
qreal x = MIN3(selection.at(i-1).left(),
selection.at(i).left(),
selection.at(i+1).left()) - margin;
points += QPointF(x, selection.at(i).bottom()+extra);
points += QPointF(x, selection.at(i).top());
}
points += selection.at(0).bottomLeft() + QPointF(-margin, extra);
points += selection.at(0).topLeft() + QPointF(-margin, -margin);
QPainterPath path;
const int corner = 4;
path.moveTo(points.at(0));
points += points.at(0);
QPointF previous = points.at(0);
for (int i = 1; i < points.size(); ++i) {
QPointF point = points.at(i);
if (point.y() == previous.y() && qAbs(point.x() - previous.x()) > 2*corner) {
QPointF tmp = QPointF(previous.x() + corner * ((point.x() > previous.x())?1:-1), previous.y());
path.quadTo(previous, tmp);
previous = tmp;
i--;
continue;
} else if (point.x() == previous.x() && qAbs(point.y() - previous.y()) > 2*corner) {
QPointF tmp = QPointF(previous.x(), previous.y() + corner * ((point.y() > previous.y())?1:-1));
path.quadTo(previous, tmp);
previous = tmp;
i--;
continue;
}
QPointF target = (previous + point) / 2;
path.quadTo(previous, target);
previous = points.at(i);
}
path.closeSubpath();
path.translate(offset);
return path;
}
void TextEditorOverlay::paintSelection(QPainter *painter,
const OverlaySelection &selection)
{
const QTextCursor &begin = selection.m_cursor_begin;
const QTextCursor &end= selection.m_cursor_end;
const QColor &fg = selection.m_fg;
const QColor &bg = selection.m_bg;
if (begin.isNull() || end.isNull() || begin.position() > end.position())
return;
QPainterPath path = createSelectionPath(begin, end, m_editor->viewport()->rect());
painter->save();
QColor penColor = fg;
if (m_alpha)
penColor.setAlpha(220);
QPen pen(penColor, m_borderWidth);
painter->translate(-.5, -.5);
QRectF pathRect = path.controlPointRect();
if (bg.isValid()) {
if (!m_alpha || begin.blockNumber() != end.blockNumber()) {
// gradients are too slow for larger selections :(
QColor col = bg;
if (m_alpha)
col.setAlpha(50);
painter->setBrush(col);
} else {
QLinearGradient linearGrad(pathRect.topLeft(), pathRect.bottomLeft());
QColor col1 = fg.lighter(150);
col1.setAlpha(20);
QColor col2 = fg;
col2.setAlpha(80);
linearGrad.setColorAt(0, col1);
linearGrad.setColorAt(1, col2);
painter->setBrush(QBrush(linearGrad));
}
} else {
painter->setBrush(QBrush());
}
painter->setRenderHint(QPainter::Antialiasing);
if (selection.m_dropShadow) {
painter->save();
QPainterPath shadow = path;
shadow.translate(m_dropShadowWidth, m_dropShadowWidth);
painter->setClipPath(shadow.intersected(path));
painter->fillPath(shadow, QColor(0, 0, 0, 100));
painter->restore();
}
pen.setJoinStyle(Qt::RoundJoin);
painter->setPen(pen);
painter->drawPath(path);
painter->restore();
}
void TextEditorOverlay::fillSelection(QPainter *painter,
const OverlaySelection &selection,
const QColor &color)
{
const QTextCursor &begin = selection.m_cursor_begin;
const QTextCursor &end= selection.m_cursor_end;
if (begin.isNull() || end.isNull() || begin.position() > end.position())
return;
QPainterPath path = createSelectionPath(begin, end, m_editor->viewport()->rect());
painter->save();
painter->translate(-.5, -.5);
painter->setRenderHint(QPainter::Antialiasing);
painter->fillPath(path, color);
painter->restore();
}
void TextEditorOverlay::paint(QPainter *painter, const QRect &clip)
{
Q_UNUSED(clip);
for (int i = 0; i < m_selections.size(); ++i) {
const OverlaySelection &selection = m_selections.at(i);
if (selection.m_fixedLength >= 0
&& selection.m_cursor_end.position() - selection.m_cursor_begin.position()
!= selection.m_fixedLength)
continue;
paintSelection(painter, selection);
}
}
void TextEditorOverlay::fill(QPainter *painter, const QColor &color, const QRect &clip)
{
Q_UNUSED(clip);
for (int i = 0; i < m_selections.size(); ++i) {
const OverlaySelection &selection = m_selections.at(i);
if (selection.m_fixedLength >= 0
&& selection.m_cursor_end.position() - selection.m_cursor_begin.position()
!= selection.m_fixedLength)
continue;
fillSelection(painter, selection, color);
}
}
<commit_msg>Fixed drop shadow<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include <QtGui/QPainter>
#include "texteditoroverlay.h"
#include <QDebug>
using namespace TextEditor;
using namespace TextEditor::Internal;
TextEditorOverlay::TextEditorOverlay(BaseTextEditor *editor)
:QObject(editor) {
m_visible = false;
m_borderWidth = 1;
m_dropShadowWidth = 2;
m_editor = editor;
m_alpha = true;
m_viewport = editor->viewport();
}
void TextEditorOverlay::update()
{
if (m_visible)
m_viewport->update();
}
void TextEditorOverlay::setVisible(bool b)
{
if (m_visible == b)
return;
m_visible = b;
update();
}
void TextEditorOverlay::clear()
{
if (m_selections.isEmpty())
return;
m_selections.clear();
update();
}
void TextEditorOverlay::addOverlaySelection(int begin, int end,
const QColor &fg, const QColor &bg,
bool lockSize,
bool dropShadow)
{
if (end < begin)
return;
QTextDocument *document = m_editor->document();
OverlaySelection selection;
selection.m_fg = fg;
selection.m_bg = bg;
selection.m_cursor_begin = QTextCursor(document->docHandle(), begin);
selection.m_cursor_end = QTextCursor(document->docHandle(), end);
if (lockSize)
selection.m_fixedLength = (end - begin);
selection.m_dropShadow = dropShadow;
if (dropShadow)
m_selections.append(selection);
else
m_selections.prepend(selection);
update();
}
void TextEditorOverlay::addOverlaySelection(const QTextCursor &cursor,
const QColor &fg, const QColor &bg, bool lockSize)
{
addOverlaySelection(cursor.selectionStart(), cursor.selectionEnd(), fg, bg, lockSize);
}
QRect TextEditorOverlay::rect() const
{
return m_viewport->rect();
}
QPainterPath TextEditorOverlay::createSelectionPath(const QTextCursor &begin, const QTextCursor &end,
const QRect &clip)
{
if (begin.isNull() || end.isNull() || begin.position() > end.position())
return QPainterPath();
QPointF offset = m_editor->contentOffset();
QRect viewportRect = rect();
QTextDocument *document = m_editor->document();
if (m_editor->blockBoundingGeometry(begin.block()).translated(offset).top() > clip.bottom() + 10
|| m_editor->blockBoundingGeometry(end.block()).translated(offset).bottom() < clip.top() - 10
)
return QPainterPath(); // nothing of the selection is visible
QTextBlock block = begin.block();
bool inSelection = false;
QVector<QRectF> selection;
if (begin.position() == end.position()) {
// special case empty selections
const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
QTextLayout *blockLayout = block.layout();
int pos = begin.position() - begin.block().position();
QTextLine line = blockLayout->lineForTextPosition(pos);
QRectF lineRect = line.naturalTextRect();
int x = line.cursorToX(pos);
lineRect.setLeft(x - m_borderWidth);
lineRect.setRight(x + m_borderWidth);
selection += lineRect.translated(blockGeometry.topLeft());
} else {
for (; block.isValid() && block.blockNumber() <= end.blockNumber(); block = block.next()) {
if (! block.isVisible())
continue;
const QRectF blockGeometry = m_editor->blockBoundingGeometry(block);
QTextLayout *blockLayout = block.layout();
QTextLine line = blockLayout->lineAt(0);
int beginChar = 0;
if (!inSelection) {
beginChar = begin.position() - begin.block().position();
line = blockLayout->lineForTextPosition(beginChar);
inSelection = true;
} else {
while (beginChar < block.length() && document->characterAt(block.position() + beginChar).isSpace())
++beginChar;
if (beginChar == block.length())
beginChar = 0;
}
int lastLine = blockLayout->lineCount()-1;
int endChar = -1;
if (block == end.block()) {
endChar = end.position() - end.block().position();
lastLine = blockLayout->lineForTextPosition(endChar).lineNumber();
inSelection = false;
} else {
endChar = block.length();
while (endChar > beginChar && document->characterAt(block.position() + endChar - 1).isSpace())
--endChar;
}
QRectF lineRect = line.naturalTextRect();
if (beginChar < endChar) {
lineRect.setLeft(line.cursorToX(beginChar));
if (line.lineNumber() == lastLine)
lineRect.setRight(line.cursorToX(endChar));
selection += lineRect.translated(blockGeometry.topLeft());
for (int lineIndex = line.lineNumber()+1; lineIndex <= lastLine; ++lineIndex) {
line = blockLayout->lineAt(lineIndex);
lineRect = line.naturalTextRect();
if (lineIndex == lastLine)
lineRect.setRight(line.cursorToX(endChar));
selection += lineRect.translated(blockGeometry.topLeft());
}
} else { // empty lines
if (!selection.isEmpty())
lineRect.setLeft(selection.last().left());
lineRect.setRight(lineRect.left() + 16);
selection += lineRect.translated(blockGeometry.topLeft());
}
if (!inSelection)
break;
if (blockGeometry.translated(offset).y() > 2*viewportRect.height())
break;
}
}
if (selection.isEmpty())
return QPainterPath();
QVector<QPointF> points;
const int margin = m_borderWidth/2;
const int extra = 0;
points += (selection.at(0).topLeft() + selection.at(0).topRight()) / 2 + QPointF(0, -margin);
points += selection.at(0).topRight() + QPointF(margin+1, -margin);
points += selection.at(0).bottomRight() + QPointF(margin+1, 0);
for(int i = 1; i < selection.count()-1; ++i) {
#define MAX3(a,b,c) qMax(a, qMax(b,c))
qreal x = MAX3(selection.at(i-1).right(),
selection.at(i).right(),
selection.at(i+1).right()) + margin;
points += QPointF(x+1, selection.at(i).top());
points += QPointF(x+1, selection.at(i).bottom());
}
points += selection.at(selection.count()-1).topRight() + QPointF(margin+1, 0);
points += selection.at(selection.count()-1).bottomRight() + QPointF(margin+1, margin+extra);
points += selection.at(selection.count()-1).bottomLeft() + QPointF(-margin, margin+extra);
points += selection.at(selection.count()-1).topLeft() + QPointF(-margin, 0);
for(int i = selection.count()-2; i > 0; --i) {
#define MIN3(a,b,c) qMin(a, qMin(b,c))
qreal x = MIN3(selection.at(i-1).left(),
selection.at(i).left(),
selection.at(i+1).left()) - margin;
points += QPointF(x, selection.at(i).bottom()+extra);
points += QPointF(x, selection.at(i).top());
}
points += selection.at(0).bottomLeft() + QPointF(-margin, extra);
points += selection.at(0).topLeft() + QPointF(-margin, -margin);
QPainterPath path;
const int corner = 4;
path.moveTo(points.at(0));
points += points.at(0);
QPointF previous = points.at(0);
for (int i = 1; i < points.size(); ++i) {
QPointF point = points.at(i);
if (point.y() == previous.y() && qAbs(point.x() - previous.x()) > 2*corner) {
QPointF tmp = QPointF(previous.x() + corner * ((point.x() > previous.x())?1:-1), previous.y());
path.quadTo(previous, tmp);
previous = tmp;
i--;
continue;
} else if (point.x() == previous.x() && qAbs(point.y() - previous.y()) > 2*corner) {
QPointF tmp = QPointF(previous.x(), previous.y() + corner * ((point.y() > previous.y())?1:-1));
path.quadTo(previous, tmp);
previous = tmp;
i--;
continue;
}
QPointF target = (previous + point) / 2;
path.quadTo(previous, target);
previous = points.at(i);
}
path.closeSubpath();
path.translate(offset);
return path;
}
void TextEditorOverlay::paintSelection(QPainter *painter,
const OverlaySelection &selection)
{
const QTextCursor &begin = selection.m_cursor_begin;
const QTextCursor &end= selection.m_cursor_end;
const QColor &fg = selection.m_fg;
const QColor &bg = selection.m_bg;
if (begin.isNull() || end.isNull() || begin.position() > end.position())
return;
QPainterPath path = createSelectionPath(begin, end, m_editor->viewport()->rect());
painter->save();
QColor penColor = fg;
if (m_alpha)
penColor.setAlpha(220);
QPen pen(penColor, m_borderWidth);
painter->translate(-.5, -.5);
QRectF pathRect = path.controlPointRect();
if (bg.isValid()) {
if (!m_alpha || begin.blockNumber() != end.blockNumber()) {
// gradients are too slow for larger selections :(
QColor col = bg;
if (m_alpha)
col.setAlpha(50);
painter->setBrush(col);
} else {
QLinearGradient linearGrad(pathRect.topLeft(), pathRect.bottomLeft());
QColor col1 = fg.lighter(150);
col1.setAlpha(20);
QColor col2 = fg;
col2.setAlpha(80);
linearGrad.setColorAt(0, col1);
linearGrad.setColorAt(1, col2);
painter->setBrush(QBrush(linearGrad));
}
} else {
painter->setBrush(QBrush());
}
painter->setRenderHint(QPainter::Antialiasing);
if (selection.m_dropShadow) {
painter->save();
QPainterPath shadow = path;
shadow.translate(m_dropShadowWidth, m_dropShadowWidth);
QPainterPath clip;
clip.addRect(m_editor->viewport()->rect());
painter->setClipPath(clip - path);
painter->fillPath(shadow, QColor(0, 0, 0, 100));
painter->restore();
}
pen.setJoinStyle(Qt::RoundJoin);
painter->setPen(pen);
painter->drawPath(path);
painter->restore();
}
void TextEditorOverlay::fillSelection(QPainter *painter,
const OverlaySelection &selection,
const QColor &color)
{
const QTextCursor &begin = selection.m_cursor_begin;
const QTextCursor &end= selection.m_cursor_end;
if (begin.isNull() || end.isNull() || begin.position() > end.position())
return;
QPainterPath path = createSelectionPath(begin, end, m_editor->viewport()->rect());
painter->save();
painter->translate(-.5, -.5);
painter->setRenderHint(QPainter::Antialiasing);
painter->fillPath(path, color);
painter->restore();
}
void TextEditorOverlay::paint(QPainter *painter, const QRect &clip)
{
Q_UNUSED(clip);
for (int i = 0; i < m_selections.size(); ++i) {
const OverlaySelection &selection = m_selections.at(i);
if (selection.m_fixedLength >= 0
&& selection.m_cursor_end.position() - selection.m_cursor_begin.position()
!= selection.m_fixedLength)
continue;
paintSelection(painter, selection);
}
}
void TextEditorOverlay::fill(QPainter *painter, const QColor &color, const QRect &clip)
{
Q_UNUSED(clip);
for (int i = 0; i < m_selections.size(); ++i) {
const OverlaySelection &selection = m_selections.at(i);
if (selection.m_fixedLength >= 0
&& selection.m_cursor_end.position() - selection.m_cursor_begin.position()
!= selection.m_fixedLength)
continue;
fillSelection(painter, selection, color);
}
}
<|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 SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace lexer {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
/*!
* \class SimpleLexer
* \brief The EDDI lexer.
*
* This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's
* used by the parser to parse a source file.
*/
template<typename L>
class SpiritLexer : public lex::lexer<L> {
public:
SpiritLexer() {
/* keywords */
for_ = "for";
while_ = "while";
do_ = "do";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
const_ = "const";
include = "include";
struct_ = "struct";
/* Raw values */
identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
float_ = "[0-9]+\".\"[0-9]+";
integer = "[0-9]+";
litteral = "\\\"[^\\\"]*\\\"";
/* Constructs */
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
/* Assignment operators */
swap = "<=>";
assign = '=';
/* compound assignment operators */
compound_add = "\\+=";
compound_sub = "-=";
compound_mul = "\\*=";
compound_div = "\\/=";
compound_mod = "%=";
/* Math operators */
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
/* Suffix and prefix math operators */
increment = "\\+\\+";
decrement = "--";
/* Logical operators */
and_ = "\\&\\&";
or_ = "\\|\\|";
/* Relational operators */
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += comma | stop;
this->self += assign | swap;
this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod;
this->self += addition | subtraction | multiplication | division | modulo;
this->self += increment | decrement;
this->self += and_ | or_;
this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include | struct_;
this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
this->self += float_ | integer | identifier | litteral;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
typedef lex::token_def<double> FloatToken;
StringToken identifier, litteral;
IntegerToken integer;
FloatToken float_;
CharToken addition, subtraction, multiplication, division, modulo;
StringToken increment, decrement;
StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
StringToken and_, or_;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma;
ConsumedToken assign, swap;
//Keywords
ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
ConsumedToken const_, include;
ConsumedToken struct_;
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
//Typedef for the parsers
typedef lexer::lexer_type::iterator_type Iterator;
typedef lexer::SpiritLexer<lexer::lexer_type> Lexer;
} //end of lexer
} //end of eddic
#endif
<commit_msg>Add support for the dot symbol<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 SPIRIT_LEXER_H
#define SPIRIT_LEXER_H
#include <fstream>
#include <string>
#include <utility>
#include <stack>
#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>
namespace eddic {
namespace lexer {
namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;
/*!
* \class SimpleLexer
* \brief The EDDI lexer.
*
* This class is used to do lexical analysis on an EDDI source file. This file is based on a Boost Spirit Lexer. It's
* used by the parser to parse a source file.
*/
template<typename L>
class SpiritLexer : public lex::lexer<L> {
public:
SpiritLexer() {
/* keywords */
for_ = "for";
while_ = "while";
do_ = "do";
if_ = "if";
else_ = "else";
false_ = "false";
true_ = "true";
from_ = "from";
to_ = "to";
foreach_ = "foreach";
in_ = "in";
return_ = "return";
const_ = "const";
include = "include";
struct_ = "struct";
/* Raw values */
identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
float_ = "[0-9]+\".\"[0-9]+";
integer = "[0-9]+";
litteral = "\\\"[^\\\"]*\\\"";
/* Constructs */
left_parenth = '(';
right_parenth = ')';
left_brace = '{';
right_brace = '}';
left_bracket = '[';
right_bracket = ']';
stop = ';';
comma = ',';
dot = '.';
/* Assignment operators */
swap = "<=>";
assign = '=';
/* compound assignment operators */
compound_add = "\\+=";
compound_sub = "-=";
compound_mul = "\\*=";
compound_div = "\\/=";
compound_mod = "%=";
/* Math operators */
addition = '+';
subtraction = '-';
multiplication = '*';
division = '/';
modulo = '%';
/* Suffix and prefix math operators */
increment = "\\+\\+";
decrement = "--";
/* Logical operators */
and_ = "\\&\\&";
or_ = "\\|\\|";
/* Relational operators */
equals = "==";
not_equals = "!=";
greater = ">";
less = "<";
greater_equals = ">=";
less_equals = "<=";
whitespaces = "[ \\t\\n]+";
multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
singleline_comment = "\\/\\/[^\n]*";
//Ignore whitespaces
this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];
this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
this->self += comma | stop;
this->self += assign | swap;
this->self += compound_add | compound_sub | compound_mul | compound_div | compound_mod;
this->self += addition | subtraction | multiplication | division | modulo;
this->self += increment | decrement;
this->self += and_ | or_;
this->self += for_ | do_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include | struct_;
this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
this->self += float_ | integer | identifier | litteral;
//Ignore comments
this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
}
typedef lex::token_def<lex::omit> ConsumedToken;
typedef lex::token_def<std::string> StringToken;
typedef lex::token_def<int> IntegerToken;
typedef lex::token_def<char> CharToken;
typedef lex::token_def<double> FloatToken;
StringToken identifier, litteral;
IntegerToken integer;
FloatToken float_;
CharToken addition, subtraction, multiplication, division, modulo;
StringToken increment, decrement;
StringToken compound_add, compound_sub, compound_mul, compound_div, compound_mod;
StringToken equals, not_equals, greater, less, greater_equals, less_equals;
StringToken and_, or_;
ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
ConsumedToken stop, comma, dot;
ConsumedToken assign, swap;
//Keywords
ConsumedToken if_, else_, for_, while_, do_, from_, in_, to_, foreach_, return_;
ConsumedToken true_, false_;
ConsumedToken const_, include;
ConsumedToken struct_;
//Ignored tokens
ConsumedToken whitespaces, singleline_comment, multiline_comment;
};
typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;
//Typedef for the parsers
typedef lexer::lexer_type::iterator_type Iterator;
typedef lexer::SpiritLexer<lexer::lexer_type> Lexer;
} //end of lexer
} //end of eddic
#endif
<|endoftext|> |
<commit_before>/*!
@file SetupHalo.cpp
HPCG routine
*/
#ifndef HPCG_NOMPI
#include <mpi.h>
#include <map>
#include <set>
#endif
/*
#ifndef HPCG_NOOPENMP
#include <omp.h>
#endif
*/
#ifdef HPCG_DETAILED_DEBUG
#include <fstream>
using std::endl;
#include "hpcg.hpp"
#include <cassert>
#endif
#include "SetupHalo.hpp"
#include "mytimer.hpp"
using Kokkos::create_mirror_view;
using Kokkos::deep_copy;
/*!
Prepares system matrix data structure and creates data necessary necessary
for communication of boundary values of this process.
@param[in] geom The description of the problem's geometry.
@param[inout] A The known system matrix
@see ExchangeHalo
*/
class NoMPIFunctor{
public:
typename globalStaticCrsGraphType::entries_type graph_entries;
local_index_type indexMap;
NoMPIFunctor(typename globalStaticCrsGraphType::entries_type &graph_entries_, local_index_type &indexMap_):
graph_entries(graph_entries_), indexMap(indexMap_)
{}
KOKKOS_INLINE_FUNCTION
void operator()(const int & i)const{
indexMap(i) = graph_entries(i);
}
};
void SetupHalo(SparseMatrix & A) {
// Extract Matrix pieces
//I'm not sure whether or not I'll need to mirror these...
char_1d_type nonzerosInRow = A.nonzerosInRow;
global_int_1d_type localToGlobalMap = A.localToGlobalMap;
#ifdef HPCG_NOMPI // In the non-MPI case we simply copy global indices to local index storage
local_int_t localNumberOfNonzeros = A.localNumberOfNonzeros;
// This may be redundant based on the changed setup in GenerateProblem
local_index_type indexMap("CrsMatrix: Local Index Map", A.globalMatrix.graph.entries.dimension_0());
Kokkos::parallel_for(localNumberOfNonzeros, NoMPIFunctor(A.globalMatrix.graph.entries, indexMap));
local_matrix_type localMatrix("Matrix: localMatrix", A.localNumberOfRows, A.localNumberOfRows, localNumberOfNonzeros, A.globalMatrix.values, A.globalMatrix.graph.row_map, indexMap);
A.localMatrix = localMatrix;
#else // Run this section if compiling for MPI
local_int_t localNumberOfRows = A.localNumberOfRows;
// Scan global IDs of the nonzeros in the matrix. Determine if the column ID matches a row ID. If not:
// 1) We call the ComputeRankOfMatrixRow function, which tells us the rank of the processor owning the row ID.
// We need to receive this value of the x vector during the halo exchange.
// 2) We record our row ID since we know that the other processor will need this value from us, due to symmetry.
std::map< int, std::set< global_int_t> > sendList, receiveList;
typedef std::map< int, std::set< global_int_t> >::iterator map_iter;
typedef std::set<global_int_t>::iterator set_iter;
// std::map< local_int_t, local_int_t > externalToLocalMap;
Kokkos::UnorderedMap<local_int_t, local_int_t> externalToLocalMap(A.localNumberOfRows); // This should be a worst case scenario amount of rows.
Kokkos::UnorderedMap<local_int_t, local_int_t>::HostMirror host_externalToLocalMap;
deep_copy(host_externalToLocalMap, externalToLocalMap);
// TODO: With proper critical and atomic regions, this loop could be threaded, but not attempting it at this time
// Mirror nonzerosInRow and mtxIndG and create a scope so they go away after we deep_copy them back.
host_char_1d_type host_nonzerosInRow = create_mirror_view(nonzerosInRow);
host_global_int_1d_type host_gMat_entries = create_mirror_view(A.globalMatrix.graph.entries);
host_global_int_1d_type host_localToGlobalMap = create_mirror_view(localToGlobalMap);
host_row_map_type host_row_map = create_mirror_view(A.globalMatrix.graph.row_map);
deep_copy(host_nonzerosInRow, nonzerosInRow);
deep_copy(host_gMat_entries, A.globalMatrix.graph.entries);
deep_copy(host_localToGlobalMap, localToGlobalMap);
deep_copy(host_row_map, A.globalMatrix.graph.row_map);
for (local_int_t i=0; i< localNumberOfRows; i++) {
global_int_t currentGlobalRow = host_localToGlobalMap(i);
int start = host_row_map(i);
int end = host_row_map(i+1);
for (int j=start; j< end; j++) {
global_int_t curIndex = host_gMat_entries(j);
int rankIdOfColumnEntry = ComputeRankOfMatrixRow(*A.geom, curIndex);
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << "rank, row , col, globalToLocalMap[col] = " << A.geom.rank << " " << currentGlobalRow << " "
<< curIndex << " " << A.globalToLocalMap.value_at(A.globalToLocalMap.find(curIndex)) << endl;
#endif
if (A.geom->rank!=rankIdOfColumnEntry) {// If column index is not a row index, then it comes from another processor
receiveList[rankIdOfColumnEntry].insert(curIndex);
sendList[rankIdOfColumnEntry].insert(currentGlobalRow); // Matrix symmetry means we know the neighbor process wants my value
}
}
}
// No need to deep_copy mirrors back since they are read only.
// Count number of matrix entries to send and receive
local_int_t totalToBeSent = 0;
for (map_iter curNeighbor = sendList.begin(); curNeighbor != sendList.end(); ++curNeighbor) {
totalToBeSent += (curNeighbor->second).size();
}
local_int_t totalToBeReceived = 0;
for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) {
totalToBeReceived += (curNeighbor->second).size();
}
#ifdef HPCG_DETAILED_DEBUG
// These are all attributes that should be true, due to symmetry
HPCG_fout << "totalToBeSent = " << totalToBeSent << " totalToBeReceived = " << totalToBeReceived << endl;
assert(totalToBeSent==totalToBeReceived); // Number of sent entry should equal number of received
assert(sendList.size()==receiveList.size()); // Number of send-to neighbors should equal number of receive-from
// Each receive-from neighbor should be a send-to neighbor, and send the same number of entries
for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) {
assert(sendList.find(curNeighbor->first)!=sendList.end());
assert(sendList[curNeighbor->first].size()==receiveList[curNeighbor->first].size());
}
#endif
// Build the arrays and lists needed by the ExchangeHalo function.
double * sendBuffer = new double[totalToBeSent];
local_int_1d_type elementsToSend = local_int_1d_type("Matrix: elementsToSend", totalToBeSent);
int_1d_type neighbors = int_1d_type("Matrix: neighbors", sendList.size());
local_int_1d_type receiveLength = local_int_1d_type("Matrix: receiveLength", receiveList.size());
local_int_1d_type sendLength = local_int_1d_type("Matrix: sendLength", sendList.size());
int neighborCount = 0;
local_int_t receiveEntryCount = 0;
local_int_t sendEntryCount = 0;
// Mirror the views used below. Create a scope so the mirrors automitically dealloacte after deep_copy
host_local_int_1d_type host_elementsToSend = create_mirror_view(elementsToSend);
host_int_1d_type host_neighbors = create_mirror_view(neighbors);
host_local_int_1d_type host_receiveLength = create_mirror_view(receiveLength);
host_local_int_1d_type host_sendLength = create_mirror_view(sendLength);
for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor, ++neighborCount) {
int neighborId = curNeighbor->first; // rank of current neighbor we are processing
host_neighbors(neighborCount) = neighborId; // store rank ID of current neighbor
host_receiveLength(neighborCount) = receiveList[neighborId].size();
host_sendLength(neighborCount) = sendList[neighborId].size(); // Get count if sends/receives
for (set_iter i = receiveList[neighborId].begin(); i != receiveList[neighborId].end(); ++i, ++receiveEntryCount) {
// externalToLocalMap[*i] = localNumberOfRows + receiveEntryCount; // The remote columns are indexed at end of internals
host_externalToLocalMap.insert(*i, localNumberOfRows + receiveEntryCount);
}
for (set_iter i = sendList[neighborId].begin(); i != sendList[neighborId].end(); ++i, ++sendEntryCount) {
//if (geom.rank==1) HPCG_fout << "*i, globalToLocalMap[*i], sendEntryCount = " << *i << " " << A.globalToLocalMap[*i] << " " << sendEntryCount << endl;
host_elementsToSend(sendEntryCount) = A.globalToLocalMap.value_at(A.globalToLocalMap.find(*i)); // store local ids of entry to send
}
}
// deep_copy the mirrors back.
deep_copy(externalToLocalMap, host_externalToLocalMap);
deep_copy(elementsToSend, host_elementsToSend);
deep_copy(neighbors, host_neighbors);
deep_copy(receiveLength, host_receiveLength);
deep_copy(sendLength, host_sendLength);
// Convert matrix indices to local IDs
local_index_type indexMap("CrsMatrix: Local Index Map", A.localNumberOfNonzeros);
//FIXME: Lambda capture list needs to be [=] Problem is A.globalToLocalMap (std::map) and externalToLocalMap (std::map)
Kokkos::parallel_for(localNumberOfRows, KOKKOS_LAMBDA(const int & i){ // This is going to have some issues due to some parts being on a different device.
int start = A.globalMatrix.graph.row_map(i);
int end = A.globalMatrix.graph.row_map(i+1);
for (int j = start; j < end; j++) {
global_int_t curIndex = A.globalMatrix.graph.entries(j);
int rankIdOfColumnEntry = ComputeRankOfMatrixRow(*A.geom, curIndex);
if (A.geom->rank == rankIdOfColumnEntry){
indexMap(j) = A.globalToLocalMap.value_at(A.globalToLocalMap.find(curIndex));
} else {
indexMap(j) = externalToLocalMap.value_at(externalToLocalMap.find(curIndex));
}
}
});
local_matrix_type localMatrix("Matrix: localMatrix", A.localNumberOfRows, A.localNumberOfRows, A.localNumberOfNonzeros, A.globalMatrix.values, A.globalMatrix.graph.row_map, indexMap);
A.localMatrix = localMatrix;
// Store contents in our matrix struct
A.numberOfExternalValues = externalToLocalMap.size();
A.localNumberOfColumns = A.localNumberOfRows + A.numberOfExternalValues;
A.numberOfSendNeighbors = sendList.size();
A.totalToBeSent = totalToBeSent;
A.elementsToSend = elementsToSend;
A.neighbors = neighbors;
A.receiveLength = receiveLength;
A.sendLength = sendLength;
A.sendBuffer = sendBuffer;
A.optimizationData = (void *) new double[A.numberOfExternalValues];
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << " For rank " << A.geom->rank << " of " << A.geom->size << ", number of neighbors = " << A.numberOfSendNeighbors << endl;
for (int i = 0; i < A.numberOfSendNeighbors; i++) {
HPCG_fout << " rank " << A.geom->rank << " neighbor " << host_neighbors(i) << " send/recv length = " << host_sendLength(i) << "/" << host_receiveLength(i) << endl;
for (local_int_t j = 0; j<host_sendLength(i); ++j)
HPCG_fout << " rank " << A.geom->rank << " elementsToSend[" << j << "] = " << host_elementsToSend(j) << endl;
}
#endif
#endif // ifndef HPCG_NOMPI
return;
}
<commit_msg>Replaced the lambda in setup halo with functor<commit_after>/*!
@file SetupHalo.cpp
HPCG routine
*/
#ifndef HPCG_NOMPI
#include <mpi.h>
#include <map>
#include <set>
#endif
/*
#ifndef HPCG_NOOPENMP
#include <omp.h>
#endif
*/
#ifdef HPCG_DETAILED_DEBUG
#include <fstream>
using std::endl;
#include "hpcg.hpp"
#include <cassert>
#endif
#include "SetupHalo.hpp"
#include "mytimer.hpp"
using Kokkos::create_mirror_view;
using Kokkos::deep_copy;
/*!
Prepares system matrix data structure and creates data necessary necessary
for communication of boundary values of this process.
@param[in] geom The description of the problem's geometry.
@param[inout] A The known system matrix
@see ExchangeHalo
*/
class NoMPIFunctor{
public:
typename globalStaticCrsGraphType::entries_type graph_entries;
local_index_type indexMap;
NoMPIFunctor(typename globalStaticCrsGraphType::entries_type &graph_entries_, local_index_type &indexMap_):
graph_entries(graph_entries_), indexMap(indexMap_)
{}
KOKKOS_INLINE_FUNCTION
void operator()(const int & i)const{
indexMap(i) = graph_entries(i);
}
};
class MPIFunctor{
public:
typename global_matrix_type::row_map_type row_map;
typename globalStaticCrsGraphType::entries_type graph_entries;
Geometry geom;
local_index_type indexMap;
map_type globalToLocalMap;
Kokkos::UnorderedMap<local_int_t, local_int_t> externalToLocalMap;
MPIFunctor(typename global_matrix_type::row_map_type& row_map_,
typename globalStaticCrsGraphType::entries_type& graph_entries_,
Geometry& geom_, local_index_type& indexMap_, map_type & globalToLocalMap_,
Kokkos::UnorderedMap<local_int_t, local_int_t>& externalToLocalMap_):
row_map(row_map_), graph_entries(graph_entries_), geom(geom_),
indexMap(indexMap_), globalToLocalMap(globalToLocalMap_),
externalToLocalMap(externalToLocalMap_){}
void operator()(const int & i) const{
int start = row_map(i);
int end = row_map(i+1);
for(int j = start; j < end; j++){
global_int_t curIndex = graph_entries(j);
int rankIdOfColumnEntry = ComputeRankOfMatrixRow(geom, curIndex);
if(geom.rank == rankIdOfColumnEntry){
indexMap(j) = globalToLocalMap.value_at(globalToLocalMap.find(curIndex));
} else {
indexMap(j) = externalToLocalMap.value_at(externalToLocalMap.find(curIndex));
}
}
}
};
void SetupHalo(SparseMatrix & A) {
// Extract Matrix pieces
//I'm not sure whether or not I'll need to mirror these...
char_1d_type nonzerosInRow = A.nonzerosInRow;
global_int_1d_type localToGlobalMap = A.localToGlobalMap;
#ifdef HPCG_NOMPI // In the non-MPI case we simply copy global indices to local index storage
local_int_t localNumberOfNonzeros = A.localNumberOfNonzeros;
// This may be redundant based on the changed setup in GenerateProblem
local_index_type indexMap("CrsMatrix: Local Index Map", A.globalMatrix.graph.entries.dimension_0());
Kokkos::parallel_for(localNumberOfNonzeros, NoMPIFunctor(A.globalMatrix.graph.entries, indexMap));
local_matrix_type localMatrix("Matrix: localMatrix", A.localNumberOfRows, A.localNumberOfRows, localNumberOfNonzeros, A.globalMatrix.values, A.globalMatrix.graph.row_map, indexMap);
A.localMatrix = localMatrix;
#else // Run this section if compiling for MPI
local_int_t localNumberOfRows = A.localNumberOfRows;
// Scan global IDs of the nonzeros in the matrix. Determine if the column ID matches a row ID. If not:
// 1) We call the ComputeRankOfMatrixRow function, which tells us the rank of the processor owning the row ID.
// We need to receive this value of the x vector during the halo exchange.
// 2) We record our row ID since we know that the other processor will need this value from us, due to symmetry.
std::map< int, std::set< global_int_t> > sendList, receiveList;
typedef std::map< int, std::set< global_int_t> >::iterator map_iter;
typedef std::set<global_int_t>::iterator set_iter;
// std::map< local_int_t, local_int_t > externalToLocalMap;
Kokkos::UnorderedMap<local_int_t, local_int_t> externalToLocalMap(A.localNumberOfRows); // This should be a worst case scenario amount of rows.
Kokkos::UnorderedMap<local_int_t, local_int_t>::HostMirror host_externalToLocalMap;
deep_copy(host_externalToLocalMap, externalToLocalMap);
// TODO: With proper critical and atomic regions, this loop could be threaded, but not attempting it at this time
// Mirror nonzerosInRow and mtxIndG and create a scope so they go away after we deep_copy them back.
host_char_1d_type host_nonzerosInRow = create_mirror_view(nonzerosInRow);
host_global_int_1d_type host_gMat_entries = create_mirror_view(A.globalMatrix.graph.entries);
host_global_int_1d_type host_localToGlobalMap = create_mirror_view(localToGlobalMap);
host_row_map_type host_row_map = create_mirror_view(A.globalMatrix.graph.row_map);
deep_copy(host_nonzerosInRow, nonzerosInRow);
deep_copy(host_gMat_entries, A.globalMatrix.graph.entries);
deep_copy(host_localToGlobalMap, localToGlobalMap);
deep_copy(host_row_map, A.globalMatrix.graph.row_map);
for (local_int_t i=0; i< localNumberOfRows; i++) {
global_int_t currentGlobalRow = host_localToGlobalMap(i);
int start = host_row_map(i);
int end = host_row_map(i+1);
for (int j=start; j< end; j++) {
global_int_t curIndex = host_gMat_entries(j);
int rankIdOfColumnEntry = ComputeRankOfMatrixRow(*A.geom, curIndex);
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << "rank, row , col, globalToLocalMap[col] = " << A.geom.rank << " " << currentGlobalRow << " "
<< curIndex << " " << A.globalToLocalMap.value_at(A.globalToLocalMap.find(curIndex)) << endl;
#endif
if (A.geom->rank!=rankIdOfColumnEntry) {// If column index is not a row index, then it comes from another processor
receiveList[rankIdOfColumnEntry].insert(curIndex);
sendList[rankIdOfColumnEntry].insert(currentGlobalRow); // Matrix symmetry means we know the neighbor process wants my value
}
}
}
// No need to deep_copy mirrors back since they are read only.
// Count number of matrix entries to send and receive
local_int_t totalToBeSent = 0;
for (map_iter curNeighbor = sendList.begin(); curNeighbor != sendList.end(); ++curNeighbor) {
totalToBeSent += (curNeighbor->second).size();
}
local_int_t totalToBeReceived = 0;
for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) {
totalToBeReceived += (curNeighbor->second).size();
}
#ifdef HPCG_DETAILED_DEBUG
// These are all attributes that should be true, due to symmetry
HPCG_fout << "totalToBeSent = " << totalToBeSent << " totalToBeReceived = " << totalToBeReceived << endl;
assert(totalToBeSent==totalToBeReceived); // Number of sent entry should equal number of received
assert(sendList.size()==receiveList.size()); // Number of send-to neighbors should equal number of receive-from
// Each receive-from neighbor should be a send-to neighbor, and send the same number of entries
for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor) {
assert(sendList.find(curNeighbor->first)!=sendList.end());
assert(sendList[curNeighbor->first].size()==receiveList[curNeighbor->first].size());
}
#endif
// Build the arrays and lists needed by the ExchangeHalo function.
double * sendBuffer = new double[totalToBeSent];
local_int_1d_type elementsToSend = local_int_1d_type("Matrix: elementsToSend", totalToBeSent);
int_1d_type neighbors = int_1d_type("Matrix: neighbors", sendList.size());
local_int_1d_type receiveLength = local_int_1d_type("Matrix: receiveLength", receiveList.size());
local_int_1d_type sendLength = local_int_1d_type("Matrix: sendLength", sendList.size());
int neighborCount = 0;
local_int_t receiveEntryCount = 0;
local_int_t sendEntryCount = 0;
// Mirror the views used below. Create a scope so the mirrors automitically dealloacte after deep_copy
host_local_int_1d_type host_elementsToSend = create_mirror_view(elementsToSend);
host_int_1d_type host_neighbors = create_mirror_view(neighbors);
host_local_int_1d_type host_receiveLength = create_mirror_view(receiveLength);
host_local_int_1d_type host_sendLength = create_mirror_view(sendLength);
for (map_iter curNeighbor = receiveList.begin(); curNeighbor != receiveList.end(); ++curNeighbor, ++neighborCount) {
int neighborId = curNeighbor->first; // rank of current neighbor we are processing
host_neighbors(neighborCount) = neighborId; // store rank ID of current neighbor
host_receiveLength(neighborCount) = receiveList[neighborId].size();
host_sendLength(neighborCount) = sendList[neighborId].size(); // Get count if sends/receives
for (set_iter i = receiveList[neighborId].begin(); i != receiveList[neighborId].end(); ++i, ++receiveEntryCount) {
// externalToLocalMap[*i] = localNumberOfRows + receiveEntryCount; // The remote columns are indexed at end of internals
host_externalToLocalMap.insert(*i, localNumberOfRows + receiveEntryCount);
}
for (set_iter i = sendList[neighborId].begin(); i != sendList[neighborId].end(); ++i, ++sendEntryCount) {
//if (geom.rank==1) HPCG_fout << "*i, globalToLocalMap[*i], sendEntryCount = " << *i << " " << A.globalToLocalMap[*i] << " " << sendEntryCount << endl;
host_elementsToSend(sendEntryCount) = A.globalToLocalMap.value_at(A.globalToLocalMap.find(*i)); // store local ids of entry to send
}
}
// deep_copy the mirrors back.
deep_copy(externalToLocalMap, host_externalToLocalMap);
deep_copy(elementsToSend, host_elementsToSend);
deep_copy(neighbors, host_neighbors);
deep_copy(receiveLength, host_receiveLength);
deep_copy(sendLength, host_sendLength);
// Convert matrix indices to local IDs
local_index_type indexMap("CrsMatrix: Local Index Map", A.localNumberOfNonzeros);
//FIXME: Lambda capture list needs to be [=] Problem is A.globalToLocalMap (std::map) and externalToLocalMap (std::map)
Kokkos::parallel_for(localNumberOfRows, MPIFunctor(A.globalMatrix.graph.row_map,
A.globalMatrix.graph.entries, *A.geom, indexMap, A.globalToLocalMap, externalToLocalMap));
local_matrix_type localMatrix("Matrix: localMatrix", A.localNumberOfRows, A.localNumberOfRows, A.localNumberOfNonzeros, A.globalMatrix.values, A.globalMatrix.graph.row_map, indexMap);
A.localMatrix = localMatrix;
// Store contents in our matrix struct
A.numberOfExternalValues = externalToLocalMap.size();
A.localNumberOfColumns = A.localNumberOfRows + A.numberOfExternalValues;
A.numberOfSendNeighbors = sendList.size();
A.totalToBeSent = totalToBeSent;
A.elementsToSend = elementsToSend;
A.neighbors = neighbors;
A.receiveLength = receiveLength;
A.sendLength = sendLength;
A.sendBuffer = sendBuffer;
A.optimizationData = (void *) new double[A.numberOfExternalValues];
#ifdef HPCG_DETAILED_DEBUG
HPCG_fout << " For rank " << A.geom->rank << " of " << A.geom->size << ", number of neighbors = " << A.numberOfSendNeighbors << endl;
for (int i = 0; i < A.numberOfSendNeighbors; i++) {
HPCG_fout << " rank " << A.geom->rank << " neighbor " << host_neighbors(i) << " send/recv length = " << host_sendLength(i) << "/" << host_receiveLength(i) << endl;
for (local_int_t j = 0; j<host_sendLength(i); ++j)
HPCG_fout << " rank " << A.geom->rank << " elementsToSend[" << j << "] = " << host_elementsToSend(j) << endl;
}
#endif
#endif // ifndef HPCG_NOMPI
return;
}
<|endoftext|> |
<commit_before>// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include "derivator_dictionary_encoder.h"
#include "morpho/morpho.h"
#include "morpho/morpho_ids.h"
#include "utils/binary_encoder.h"
#include "utils/compressor.h"
#include "utils/split.h"
namespace ufal {
namespace morphodita {
void derivator_dictionary_encoder::encode(istream& is, istream& dictionary, bool verbose, ostream& os) {
// Load the morphology
cerr << "Loading morphology: ";
auto dictionary_start = dictionary.tellg();
unique_ptr<morpho> morpho(morpho::load(dictionary));
if (!morpho) runtime_failure("Cannot load morpho model from given file!");
if (morpho->get_derivator()) runtime_failure("The given morpho model already has a derivator!");
auto dictionary_end = dictionary.tellg();
cerr << "done" << endl;
// Load the derivator
cerr << "Loading derivator data: ";
struct lemma_info {
string sense;
string comment;
string parent;
set<string> parents;
unsigned children;
lemma_info() : children(0) {}
lemma_info(const string& sense, const string& comment) : sense(sense), comment(comment), children(0) {}
};
map<string, lemma_info> derinet;
string line;
string part_lid, lemma_lid, lemma_comment;
vector<string> tokens;
vector<string> parts;
unordered_map<string, lemma_info> matched[2];
vector<tagged_lemma_forms> matched_lemmas_forms;
while (getline(is, line)) {
split(line, '\t', tokens);
if (tokens.size() != 2) runtime_failure("Expected two tab separated columns on derivator line '" << line << "'!");
// Generate all possible lemmas and parents
for (int i = 0; i < 2; i++) {
split(tokens[i], ' ', parts);
if (parts.size() > 2) runtime_failure("The derivator lemma desctiption '" << tokens[i] << "' contains two or more spaces!");
bool is_lemma_id = parts.size() == 1;
part_lid.assign(parts[0], 0, morpho->lemma_id_len(parts[0]));
morpho->generate(parts[0], is_lemma_id ? nullptr : parts[1].c_str(), morpho::NO_GUESSER, matched_lemmas_forms);
matched[i].clear();
for (auto&& lemma_forms : matched_lemmas_forms) {
lemma_lid.assign(lemma_forms.lemma, 0, morpho->lemma_id_len(lemma_forms.lemma));
if (!is_lemma_id || part_lid == lemma_lid) {
// Choose only the shortest lemma comment for the lemma id of lemma_form.lemma
lemma_comment.assign(lemma_forms.lemma, lemma_lid.size(), string::npos);
auto it = matched[i].emplace(lemma_lid, lemma_info(lemma_lid.substr(morpho->raw_lemma_len(lemma_lid)), lemma_comment));
if (!it.second &&
(lemma_comment.size() < it.first->second.comment.size() ||
(lemma_comment.size() == it.first->second.comment.size() && lemma_comment < it.first->second.comment)))
it.first->second.comment.assign(lemma_comment);
}
}
}
if (matched[0].empty() || matched[1].empty()) {
if (verbose)
cerr << "Could not match a lemma from line '" << line << "', skipping." << endl;
continue;
}
// Store the possible parents
derinet.insert(matched[0].begin(), matched[0].end());
derinet.insert(matched[1].begin(), matched[1].end());
for (auto&& lemma : matched[0])
for (auto&& parent : matched[1])
derinet[lemma.first].parents.insert(parent.first);
}
cerr << "done" << endl;
// Choose unique parent for every lemma
for (auto&& lemma : derinet)
if (!lemma.second.parents.empty()) {
// Try locating lexicographically smallest parent with the same sense
for (auto&& parent : lemma.second.parents)
if (derinet[parent].sense == lemma.second.sense) {
lemma.second.parent.assign(parent);
break;
}
// Otherwise, choose the lexicographically smallest parent
if (lemma.second.parent.empty())
lemma.second.parent.assign(*lemma.second.parents.begin());
// Add this edge also to the parent
derinet[lemma.second.parent].children++;
if (verbose)
cerr << lemma.first << lemma.second.comment << " -> " << lemma.second.parent << derinet[lemma.second.parent].comment << endl;
}
// Encode the derivator
cerr << "Encoding derivator: ";
os.put(morpho_ids::DERIVATOR_DICTIONARY);
binary_encoder enc;
vector<int> lengths;
for (auto&& lemma : derinet) {
if (lemma.first.size() >= lengths.size())
lengths.resize(lemma.first.size() + 1);
lengths[lemma.first.size()]++;
}
enc.add_1B(lengths.size());
for (auto&& length : lengths)
enc.add_4B(length);
enc.add_4B(derinet.size());
string prev = "";
for (auto&& lemma : derinet) {
int cpl = 0;
while (prev[cpl] && prev[cpl] == lemma.first[cpl]) cpl++;
enc.add_1B(prev.size() - cpl);
enc.add_1B(lemma.first.size() - cpl);
enc.add_data(lemma.first.c_str() + cpl);
enc.add_1B(lemma.second.comment.size());
enc.add_data(lemma.second.comment);
enc.add_2B(lemma.second.children);
if (lemma.second.parent.empty()) {
enc.add_1B(0);
} else {
unsigned best_lemma_from = 0, best_parent_from = 0, best_len = 0;
for (unsigned lemma_from = 0; lemma_from < lemma.first.size(); lemma_from++)
for (unsigned parent_from = 0; parent_from < lemma.second.parent.size(); parent_from++) {
unsigned len = 0;
while (lemma_from + len < lemma.first.size() &&
parent_from + len < lemma.second.parent.size() &&
lemma.first[lemma_from+len] == lemma.second.parent[parent_from+len])
len++;
if (len > best_len) best_lemma_from = lemma_from, best_parent_from = parent_from, best_len = len;
}
enum { REMOVE_START = 1, REMOVE_END = 2, ADD_START = 4, ADD_END = 8 };
enc.add_1B(REMOVE_START * (best_lemma_from>0) + REMOVE_END * (best_lemma_from+best_len<lemma.first.size()) +
ADD_START * (best_parent_from>0) + ADD_END * (best_parent_from+best_len<lemma.second.parent.size()));
if (best_lemma_from > 0) enc.add_1B(best_lemma_from);
if (best_lemma_from + best_len < lemma.first.size()) enc.add_1B(lemma.first.size() - best_lemma_from - best_len);
if (best_parent_from > 0) {
enc.add_1B(best_parent_from);
enc.add_data(string_piece(lemma.second.parent.c_str(), best_parent_from));
}
if (best_parent_from + best_len < lemma.second.parent.size()) {
enc.add_1B(lemma.second.parent.size() - best_parent_from - best_len);
enc.add_data(lemma.second.parent.c_str() + best_parent_from + best_len);
}
}
prev.assign(lemma.first);
}
compressor::save(os, enc);
// Append the morphology after the derivator dictionary model
if (!dictionary.seekg(dictionary_start, dictionary.beg)) runtime_failure("Cannot seek in the morpho model!");
for (auto length = dictionary_end - dictionary_start; length; length--)
os.put(dictionary.get());
cerr << "done" << endl;
}
} // namespace morphodita
} // namespace ufal
<commit_msg>Explicitly check that derivator data do not contain a cycle.<commit_after>// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// 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 <algorithm>
#include <set>
#include <map>
#include <unordered_map>
#include "derivator_dictionary_encoder.h"
#include "morpho/morpho.h"
#include "morpho/morpho_ids.h"
#include "utils/binary_encoder.h"
#include "utils/compressor.h"
#include "utils/split.h"
namespace ufal {
namespace morphodita {
void derivator_dictionary_encoder::encode(istream& is, istream& dictionary, bool verbose, ostream& os) {
// Load the morphology
cerr << "Loading morphology: ";
auto dictionary_start = dictionary.tellg();
unique_ptr<morpho> morpho(morpho::load(dictionary));
if (!morpho) runtime_failure("Cannot load morpho model from given file!");
if (morpho->get_derivator()) runtime_failure("The given morpho model already has a derivator!");
auto dictionary_end = dictionary.tellg();
cerr << "done" << endl;
// Load the derivator
cerr << "Loading derivator data: ";
struct lemma_info {
string sense;
string comment;
string parent;
set<string> parents;
unsigned children;
unsigned mark;
lemma_info(const string& sense = string(), const string& comment = string())
: sense(sense), comment(comment), children(0), mark(0) {}
};
map<string, lemma_info> derinet;
string line;
string part_lid, lemma_lid, lemma_comment;
vector<string> tokens;
vector<string> parts;
unordered_map<string, lemma_info> matched[2];
vector<tagged_lemma_forms> matched_lemmas_forms;
while (getline(is, line)) {
split(line, '\t', tokens);
if (tokens.size() != 2) runtime_failure("Expected two tab separated columns on derivator line '" << line << "'!");
// Generate all possible lemmas and parents
for (int i = 0; i < 2; i++) {
split(tokens[i], ' ', parts);
if (parts.size() > 2) runtime_failure("The derivator lemma desctiption '" << tokens[i] << "' contains two or more spaces!");
bool is_lemma_id = parts.size() == 1;
part_lid.assign(parts[0], 0, morpho->lemma_id_len(parts[0]));
morpho->generate(parts[0], is_lemma_id ? nullptr : parts[1].c_str(), morpho::NO_GUESSER, matched_lemmas_forms);
matched[i].clear();
for (auto&& lemma_forms : matched_lemmas_forms) {
lemma_lid.assign(lemma_forms.lemma, 0, morpho->lemma_id_len(lemma_forms.lemma));
if (!is_lemma_id || part_lid == lemma_lid) {
// Choose only the shortest lemma comment for the lemma id of lemma_form.lemma
lemma_comment.assign(lemma_forms.lemma, lemma_lid.size(), string::npos);
auto it = matched[i].emplace(lemma_lid, lemma_info(lemma_lid.substr(morpho->raw_lemma_len(lemma_lid)), lemma_comment));
if (!it.second &&
(lemma_comment.size() < it.first->second.comment.size() ||
(lemma_comment.size() == it.first->second.comment.size() && lemma_comment < it.first->second.comment)))
it.first->second.comment.assign(lemma_comment);
}
}
}
if (matched[0].empty() || matched[1].empty()) {
if (verbose)
cerr << "Could not match a lemma from line '" << line << "', skipping." << endl;
continue;
}
// Store the possible parents
derinet.insert(matched[0].begin(), matched[0].end());
derinet.insert(matched[1].begin(), matched[1].end());
for (auto&& lemma : matched[0])
for (auto&& parent : matched[1])
derinet[lemma.first].parents.insert(parent.first);
}
cerr << "done" << endl;
// Choose unique parent for every lemma
for (auto&& lemma : derinet)
if (!lemma.second.parents.empty()) {
// Try locating lexicographically smallest parent with the same sense
for (auto&& parent : lemma.second.parents)
if (derinet[parent].sense == lemma.second.sense) {
lemma.second.parent.assign(parent);
break;
}
// Otherwise, choose the lexicographically smallest parent
if (lemma.second.parent.empty())
lemma.second.parent.assign(*lemma.second.parents.begin());
// Add this edge also to the parent
derinet[lemma.second.parent].children++;
if (verbose)
cerr << lemma.first << lemma.second.comment << " -> " << lemma.second.parent << derinet[lemma.second.parent].comment << endl;
}
// Make sure the derinet contains no cycles
unsigned mark = 0;
for (auto&& lemma : derinet) {
lemma.second.mark = ++mark;
for (auto node = derinet.find(lemma.first); !node->second.parent.empty(); ) {
node = derinet.find(node->second.parent);
if (node->second.mark == mark)
runtime_failure("The given derivator forms a cycle containing lemma '" << lemma.first << "'!");
node->second.mark = mark;
}
}
// Encode the derivator
cerr << "Encoding derivator: ";
os.put(morpho_ids::DERIVATOR_DICTIONARY);
binary_encoder enc;
vector<int> lengths;
for (auto&& lemma : derinet) {
if (lemma.first.size() >= lengths.size())
lengths.resize(lemma.first.size() + 1);
lengths[lemma.first.size()]++;
}
enc.add_1B(lengths.size());
for (auto&& length : lengths)
enc.add_4B(length);
enc.add_4B(derinet.size());
string prev = "";
for (auto&& lemma : derinet) {
int cpl = 0;
while (prev[cpl] && prev[cpl] == lemma.first[cpl]) cpl++;
enc.add_1B(prev.size() - cpl);
enc.add_1B(lemma.first.size() - cpl);
enc.add_data(lemma.first.c_str() + cpl);
enc.add_1B(lemma.second.comment.size());
enc.add_data(lemma.second.comment);
enc.add_2B(lemma.second.children);
if (lemma.second.parent.empty()) {
enc.add_1B(0);
} else {
unsigned best_lemma_from = 0, best_parent_from = 0, best_len = 0;
for (unsigned lemma_from = 0; lemma_from < lemma.first.size(); lemma_from++)
for (unsigned parent_from = 0; parent_from < lemma.second.parent.size(); parent_from++) {
unsigned len = 0;
while (lemma_from + len < lemma.first.size() &&
parent_from + len < lemma.second.parent.size() &&
lemma.first[lemma_from+len] == lemma.second.parent[parent_from+len])
len++;
if (len > best_len) best_lemma_from = lemma_from, best_parent_from = parent_from, best_len = len;
}
enum { REMOVE_START = 1, REMOVE_END = 2, ADD_START = 4, ADD_END = 8 };
enc.add_1B(REMOVE_START * (best_lemma_from>0) + REMOVE_END * (best_lemma_from+best_len<lemma.first.size()) +
ADD_START * (best_parent_from>0) + ADD_END * (best_parent_from+best_len<lemma.second.parent.size()));
if (best_lemma_from > 0) enc.add_1B(best_lemma_from);
if (best_lemma_from + best_len < lemma.first.size()) enc.add_1B(lemma.first.size() - best_lemma_from - best_len);
if (best_parent_from > 0) {
enc.add_1B(best_parent_from);
enc.add_data(string_piece(lemma.second.parent.c_str(), best_parent_from));
}
if (best_parent_from + best_len < lemma.second.parent.size()) {
enc.add_1B(lemma.second.parent.size() - best_parent_from - best_len);
enc.add_data(lemma.second.parent.c_str() + best_parent_from + best_len);
}
}
prev.assign(lemma.first);
}
compressor::save(os, enc);
// Append the morphology after the derivator dictionary model
if (!dictionary.seekg(dictionary_start, dictionary.beg)) runtime_failure("Cannot seek in the morpho model!");
for (auto length = dictionary_end - dictionary_start; length; length--)
os.put(dictionary.get());
cerr << "done" << endl;
}
} // namespace morphodita
} // namespace ufal
<|endoftext|> |
<commit_before>#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// InputLayoutCache.cpp: Defines InputLayoutCache, a class that builds and caches
// D3D11 input layouts.
#include "libGLESv2/renderer/d3d11/InputLayoutCache.h"
#include "libGLESv2/renderer/d3d11/VertexBuffer11.h"
#include "libGLESv2/renderer/d3d11/BufferStorage11.h"
#include "libGLESv2/renderer/d3d11/ShaderExecutable11.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#include "libGLESv2/renderer/d3d11/formatutils11.h"
#include "third_party/murmurhash/MurmurHash3.h"
namespace rx
{
static void GetInputLayout(const TranslatedAttribute translatedAttributes[gl::MAX_VERTEX_ATTRIBS],
gl::VertexFormat inputLayout[gl::MAX_VERTEX_ATTRIBS])
{
for (unsigned int attributeIndex = 0; attributeIndex < gl::MAX_VERTEX_ATTRIBS; attributeIndex++)
{
const TranslatedAttribute &translatedAttribute = translatedAttributes[attributeIndex];
if (translatedAttributes[attributeIndex].active)
{
inputLayout[attributeIndex] = gl::VertexFormat(*translatedAttribute.attribute,
translatedAttribute.currentValueType);
}
}
}
const unsigned int InputLayoutCache::kMaxInputLayouts = 1024;
InputLayoutCache::InputLayoutCache() : mInputLayoutMap(kMaxInputLayouts, hashInputLayout, compareInputLayouts)
{
mCounter = 0;
mDevice = NULL;
mDeviceContext = NULL;
mCurrentIL = NULL;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mCurrentBuffers[i] = NULL;
mCurrentVertexStrides[i] = -1;
mCurrentVertexOffsets[i] = -1;
}
}
InputLayoutCache::~InputLayoutCache()
{
clear();
}
void InputLayoutCache::initialize(ID3D11Device *device, ID3D11DeviceContext *context)
{
clear();
mDevice = device;
mDeviceContext = context;
}
void InputLayoutCache::clear()
{
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
SafeRelease(i->second.inputLayout);
}
mInputLayoutMap.clear();
markDirty();
}
void InputLayoutCache::markDirty()
{
mCurrentIL = NULL;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mCurrentBuffers[i] = NULL;
mCurrentVertexStrides[i] = -1;
mCurrentVertexOffsets[i] = -1;
}
}
GLenum InputLayoutCache::applyVertexBuffers(TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS],
gl::ProgramBinary *programBinary)
{
int sortedSemanticIndices[gl::MAX_VERTEX_ATTRIBS];
programBinary->sortAttributesByLayout(attributes, sortedSemanticIndices);
if (!mDevice || !mDeviceContext)
{
ERR("InputLayoutCache is not initialized.");
return GL_INVALID_OPERATION;
}
InputLayoutKey ilKey = { 0 };
static const char* semanticName = "TEXCOORD";
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
D3D11_INPUT_CLASSIFICATION inputClass = attributes[i].divisor > 0 ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA;
gl::VertexFormat vertexFormat(*attributes[i].attribute, attributes[i].currentValueType);
DXGI_FORMAT dxgiFormat = gl_d3d11::GetNativeVertexFormat(vertexFormat);
// Record the type of the associated vertex shader vector in our key
// This will prevent mismatched vertex shaders from using the same input layout
GLint attributeSize;
programBinary->getActiveAttribute(ilKey.elementCount, 0, NULL, &attributeSize, &ilKey.elements[ilKey.elementCount].glslElementType, NULL);
ilKey.elements[ilKey.elementCount].desc.SemanticName = semanticName;
ilKey.elements[ilKey.elementCount].desc.SemanticIndex = sortedSemanticIndices[i];
ilKey.elements[ilKey.elementCount].desc.Format = dxgiFormat;
ilKey.elements[ilKey.elementCount].desc.InputSlot = i;
ilKey.elements[ilKey.elementCount].desc.AlignedByteOffset = 0;
ilKey.elements[ilKey.elementCount].desc.InputSlotClass = inputClass;
ilKey.elements[ilKey.elementCount].desc.InstanceDataStepRate = attributes[i].divisor;
ilKey.elementCount++;
}
}
ID3D11InputLayout *inputLayout = NULL;
InputLayoutMap::iterator keyIter = mInputLayoutMap.find(ilKey);
if (keyIter != mInputLayoutMap.end())
{
inputLayout = keyIter->second.inputLayout;
keyIter->second.lastUsedTime = mCounter++;
}
else
{
gl::VertexFormat shaderInputLayout[gl::MAX_VERTEX_ATTRIBS];
GetInputLayout(attributes, shaderInputLayout);
ShaderExecutable11 *shader = ShaderExecutable11::makeShaderExecutable11(programBinary->getVertexExecutableForInputLayout(shaderInputLayout));
D3D11_INPUT_ELEMENT_DESC descs[gl::MAX_VERTEX_ATTRIBS];
for (unsigned int j = 0; j < ilKey.elementCount; ++j)
{
descs[j] = ilKey.elements[j].desc;
}
HRESULT result = mDevice->CreateInputLayout(descs, ilKey.elementCount, shader->getFunction(), shader->getLength(), &inputLayout);
if (FAILED(result))
{
ERR("Failed to crate input layout, result: 0x%08x", result);
return GL_INVALID_OPERATION;
}
if (mInputLayoutMap.size() >= kMaxInputLayouts)
{
TRACE("Overflowed the limit of %u input layouts, removing the least recently used "
"to make room.", kMaxInputLayouts);
InputLayoutMap::iterator leastRecentlyUsed = mInputLayoutMap.begin();
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
if (i->second.lastUsedTime < leastRecentlyUsed->second.lastUsedTime)
{
leastRecentlyUsed = i;
}
}
SafeRelease(leastRecentlyUsed->second.inputLayout);
mInputLayoutMap.erase(leastRecentlyUsed);
}
InputLayoutCounterPair inputCounterPair;
inputCounterPair.inputLayout = inputLayout;
inputCounterPair.lastUsedTime = mCounter++;
mInputLayoutMap.insert(std::make_pair(ilKey, inputCounterPair));
}
if (inputLayout != mCurrentIL)
{
mDeviceContext->IASetInputLayout(inputLayout);
mCurrentIL = inputLayout;
}
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
ID3D11Buffer *buffer = NULL;
if (attributes[i].active)
{
VertexBuffer11 *vertexBuffer = VertexBuffer11::makeVertexBuffer11(attributes[i].vertexBuffer);
BufferStorage11 *bufferStorage = attributes[i].storage ? BufferStorage11::makeBufferStorage11(attributes[i].storage) : NULL;
buffer = bufferStorage ? bufferStorage->getBuffer(BUFFER_USAGE_VERTEX_OR_TRANSFORM_FEEDBACK)
: vertexBuffer->getBuffer();
}
UINT vertexStride = attributes[i].stride;
UINT vertexOffset = attributes[i].offset;
if (buffer != mCurrentBuffers[i] || vertexStride != mCurrentVertexStrides[i] ||
vertexOffset != mCurrentVertexOffsets[i])
{
mDeviceContext->IASetVertexBuffers(i, 1, &buffer, &vertexStride, &vertexOffset);
mCurrentBuffers[i] = buffer;
mCurrentVertexStrides[i] = vertexStride;
mCurrentVertexOffsets[i] = vertexOffset;
}
}
return GL_NO_ERROR;
}
std::size_t InputLayoutCache::hashInputLayout(const InputLayoutKey &inputLayout)
{
static const unsigned int seed = 0xDEADBEEF;
std::size_t hash = 0;
MurmurHash3_x86_32(inputLayout.begin(), inputLayout.end() - inputLayout.begin(), seed, &hash);
return hash;
}
bool InputLayoutCache::compareInputLayouts(const InputLayoutKey &a, const InputLayoutKey &b)
{
if (a.elementCount != b.elementCount)
{
return false;
}
return std::equal(a.begin(), a.end(), b.begin());
}
}
<commit_msg>Minimize the API calls done by InputLayoutCache::applyVertexBuffers.<commit_after>#include "precompiled.h"
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// InputLayoutCache.cpp: Defines InputLayoutCache, a class that builds and caches
// D3D11 input layouts.
#include "libGLESv2/renderer/d3d11/InputLayoutCache.h"
#include "libGLESv2/renderer/d3d11/VertexBuffer11.h"
#include "libGLESv2/renderer/d3d11/BufferStorage11.h"
#include "libGLESv2/renderer/d3d11/ShaderExecutable11.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/VertexAttribute.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#include "libGLESv2/renderer/d3d11/formatutils11.h"
#include "third_party/murmurhash/MurmurHash3.h"
namespace rx
{
static void GetInputLayout(const TranslatedAttribute translatedAttributes[gl::MAX_VERTEX_ATTRIBS],
gl::VertexFormat inputLayout[gl::MAX_VERTEX_ATTRIBS])
{
for (unsigned int attributeIndex = 0; attributeIndex < gl::MAX_VERTEX_ATTRIBS; attributeIndex++)
{
const TranslatedAttribute &translatedAttribute = translatedAttributes[attributeIndex];
if (translatedAttributes[attributeIndex].active)
{
inputLayout[attributeIndex] = gl::VertexFormat(*translatedAttribute.attribute,
translatedAttribute.currentValueType);
}
}
}
const unsigned int InputLayoutCache::kMaxInputLayouts = 1024;
InputLayoutCache::InputLayoutCache() : mInputLayoutMap(kMaxInputLayouts, hashInputLayout, compareInputLayouts)
{
mCounter = 0;
mDevice = NULL;
mDeviceContext = NULL;
mCurrentIL = NULL;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mCurrentBuffers[i] = NULL;
mCurrentVertexStrides[i] = -1;
mCurrentVertexOffsets[i] = -1;
}
}
InputLayoutCache::~InputLayoutCache()
{
clear();
}
void InputLayoutCache::initialize(ID3D11Device *device, ID3D11DeviceContext *context)
{
clear();
mDevice = device;
mDeviceContext = context;
}
void InputLayoutCache::clear()
{
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
SafeRelease(i->second.inputLayout);
}
mInputLayoutMap.clear();
markDirty();
}
void InputLayoutCache::markDirty()
{
mCurrentIL = NULL;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
mCurrentBuffers[i] = NULL;
mCurrentVertexStrides[i] = -1;
mCurrentVertexOffsets[i] = -1;
}
}
GLenum InputLayoutCache::applyVertexBuffers(TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS],
gl::ProgramBinary *programBinary)
{
int sortedSemanticIndices[gl::MAX_VERTEX_ATTRIBS];
programBinary->sortAttributesByLayout(attributes, sortedSemanticIndices);
if (!mDevice || !mDeviceContext)
{
ERR("InputLayoutCache is not initialized.");
return GL_INVALID_OPERATION;
}
InputLayoutKey ilKey = { 0 };
static const char* semanticName = "TEXCOORD";
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
if (attributes[i].active)
{
D3D11_INPUT_CLASSIFICATION inputClass = attributes[i].divisor > 0 ? D3D11_INPUT_PER_INSTANCE_DATA : D3D11_INPUT_PER_VERTEX_DATA;
gl::VertexFormat vertexFormat(*attributes[i].attribute, attributes[i].currentValueType);
DXGI_FORMAT dxgiFormat = gl_d3d11::GetNativeVertexFormat(vertexFormat);
// Record the type of the associated vertex shader vector in our key
// This will prevent mismatched vertex shaders from using the same input layout
GLint attributeSize;
programBinary->getActiveAttribute(ilKey.elementCount, 0, NULL, &attributeSize, &ilKey.elements[ilKey.elementCount].glslElementType, NULL);
ilKey.elements[ilKey.elementCount].desc.SemanticName = semanticName;
ilKey.elements[ilKey.elementCount].desc.SemanticIndex = sortedSemanticIndices[i];
ilKey.elements[ilKey.elementCount].desc.Format = dxgiFormat;
ilKey.elements[ilKey.elementCount].desc.InputSlot = i;
ilKey.elements[ilKey.elementCount].desc.AlignedByteOffset = 0;
ilKey.elements[ilKey.elementCount].desc.InputSlotClass = inputClass;
ilKey.elements[ilKey.elementCount].desc.InstanceDataStepRate = attributes[i].divisor;
ilKey.elementCount++;
}
}
ID3D11InputLayout *inputLayout = NULL;
InputLayoutMap::iterator keyIter = mInputLayoutMap.find(ilKey);
if (keyIter != mInputLayoutMap.end())
{
inputLayout = keyIter->second.inputLayout;
keyIter->second.lastUsedTime = mCounter++;
}
else
{
gl::VertexFormat shaderInputLayout[gl::MAX_VERTEX_ATTRIBS];
GetInputLayout(attributes, shaderInputLayout);
ShaderExecutable11 *shader = ShaderExecutable11::makeShaderExecutable11(programBinary->getVertexExecutableForInputLayout(shaderInputLayout));
D3D11_INPUT_ELEMENT_DESC descs[gl::MAX_VERTEX_ATTRIBS];
for (unsigned int j = 0; j < ilKey.elementCount; ++j)
{
descs[j] = ilKey.elements[j].desc;
}
HRESULT result = mDevice->CreateInputLayout(descs, ilKey.elementCount, shader->getFunction(), shader->getLength(), &inputLayout);
if (FAILED(result))
{
ERR("Failed to crate input layout, result: 0x%08x", result);
return GL_INVALID_OPERATION;
}
if (mInputLayoutMap.size() >= kMaxInputLayouts)
{
TRACE("Overflowed the limit of %u input layouts, removing the least recently used "
"to make room.", kMaxInputLayouts);
InputLayoutMap::iterator leastRecentlyUsed = mInputLayoutMap.begin();
for (InputLayoutMap::iterator i = mInputLayoutMap.begin(); i != mInputLayoutMap.end(); i++)
{
if (i->second.lastUsedTime < leastRecentlyUsed->second.lastUsedTime)
{
leastRecentlyUsed = i;
}
}
SafeRelease(leastRecentlyUsed->second.inputLayout);
mInputLayoutMap.erase(leastRecentlyUsed);
}
InputLayoutCounterPair inputCounterPair;
inputCounterPair.inputLayout = inputLayout;
inputCounterPair.lastUsedTime = mCounter++;
mInputLayoutMap.insert(std::make_pair(ilKey, inputCounterPair));
}
if (inputLayout != mCurrentIL)
{
mDeviceContext->IASetInputLayout(inputLayout);
mCurrentIL = inputLayout;
}
bool dirtyBuffers = false;
size_t minDiff = gl::MAX_VERTEX_ATTRIBS;
size_t maxDiff = 0;
for (unsigned int i = 0; i < gl::MAX_VERTEX_ATTRIBS; i++)
{
ID3D11Buffer *buffer = NULL;
if (attributes[i].active)
{
VertexBuffer11 *vertexBuffer = VertexBuffer11::makeVertexBuffer11(attributes[i].vertexBuffer);
BufferStorage11 *bufferStorage = attributes[i].storage ? BufferStorage11::makeBufferStorage11(attributes[i].storage) : NULL;
buffer = bufferStorage ? bufferStorage->getBuffer(BUFFER_USAGE_VERTEX_OR_TRANSFORM_FEEDBACK)
: vertexBuffer->getBuffer();
}
UINT vertexStride = attributes[i].stride;
UINT vertexOffset = attributes[i].offset;
if (buffer != mCurrentBuffers[i] || vertexStride != mCurrentVertexStrides[i] ||
vertexOffset != mCurrentVertexOffsets[i])
{
dirtyBuffers = true;
minDiff = std::min(minDiff, i);
maxDiff = std::max(maxDiff, i);
mCurrentBuffers[i] = buffer;
mCurrentVertexStrides[i] = vertexStride;
mCurrentVertexOffsets[i] = vertexOffset;
}
}
if (dirtyBuffers)
{
ASSERT(minDiff <= maxDiff && maxDiff < gl::MAX_VERTEX_ATTRIBS);
mDeviceContext->IASetVertexBuffers(minDiff, maxDiff - minDiff + 1, mCurrentBuffers + minDiff,
mCurrentVertexStrides + minDiff, mCurrentVertexOffsets + minDiff);
}
return GL_NO_ERROR;
}
std::size_t InputLayoutCache::hashInputLayout(const InputLayoutKey &inputLayout)
{
static const unsigned int seed = 0xDEADBEEF;
std::size_t hash = 0;
MurmurHash3_x86_32(inputLayout.begin(), inputLayout.end() - inputLayout.begin(), seed, &hash);
return hash;
}
bool InputLayoutCache::compareInputLayouts(const InputLayoutKey &a, const InputLayoutKey &b)
{
if (a.elementCount != b.elementCount)
{
return false;
}
return std::equal(a.begin(), a.end(), b.begin());
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#if defined(__GNUC__)
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
#else
#define TORRENT_DEPRECATED
#endif
#if defined(__GNUC__) && __GNUC__ >= 4
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<commit_msg>deprecated fix for gcc (requires 4.0+)<commit_after>/*
Copyright (c) 2005, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED
#include <boost/config.hpp>
#if defined(__GNUC__) && __GNUC__ >= 4
#define TORRENT_DEPRECATED __attribute__ ((deprecated))
# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __attribute__ ((visibility("default")))
# else
# define TORRENT_EXPORT
# endif
#elif defined(__GNUC__)
# define TORRENT_EXPORT
#elif defined(BOOST_MSVC)
# if defined(TORRENT_BUILDING_SHARED)
# define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
# define TORRENT_EXPORT __declspec(dllimport)
# else
# define TORRENT_EXPORT
# endif
#else
# define TORRENT_EXPORT
#endif
#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif
#endif // TORRENT_CONFIG_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_HASHER_HPP_INCLUDED
#define TORRENT_HASHER_HPP_INCLUDED
#include <boost/cstdint.hpp>
#include "libtorrent/peer_id.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#ifdef TORRENT_USE_GCRYPT
#include <gcrypt.h>
#elif defined TORRENT_USE_OPENSSL
extern "C"
{
#include <openssl/sha.h>
}
#else
// from sha1.cpp
namespace libtorrent
{
struct TORRENT_EXTRA_EXPORT sha_ctx
{
boost::uint32_t state[5];
boost::uint32_t count[2];
boost::uint8_t buffer[64];
};
TORRENT_EXTRA_EXPORT void SHA1_init(sha_ctx* context);
TORRENT_EXTRA_EXPORT void SHA1_update(sha_ctx* context, boost::uint8_t const* data, boost::uint32_t len);
TORRENT_EXTRA_EXPORT void SHA1_final(boost::uint8_t* digest, sha_ctx* context);
} // namespace libtorrent
#endif
namespace libtorrent
{
class hasher
{
public:
hasher()
{
#ifdef TORRENT_USE_GCRYPT
gcry_md_open(&m_context, GCRY_MD_SHA1, 0);
#else
SHA1_init(&m_context);
#endif
}
hasher(const char* data, int len)
{
TORRENT_ASSERT(data != 0);
TORRENT_ASSERT(len > 0);
#ifdef TORRENT_USE_GCRYPT
gcry_md_open(&m_context, GCRY_MD_SHA1, 0);
gcry_md_write(m_context, data, len);
#else
SHA1_init(&m_context);
SHA1_update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#endif
}
#ifdef TORRENT_USE_GCRYPT
hasher(hasher const& h)
{
gcry_md_copy(&m_context, h.m_context);
}
hasher& operator=(hasher const& h)
{
gcry_md_close(m_context);
gcry_md_copy(&m_context, h.m_context);
return *this;
}
#endif
void update(std::string const& data) { update(data.c_str(), data.size()); }
void update(const char* data, int len)
{
TORRENT_ASSERT(data != 0);
TORRENT_ASSERT(len > 0);
#ifdef TORRENT_USE_GCRYPT
gcry_md_write(m_context, data, len);
#else
SHA1_update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#endif
}
sha1_hash final()
{
sha1_hash digest;
#ifdef TORRENT_USE_GCRYPT
gcry_md_final(m_context);
digest.assign((const char*)gcry_md_read(m_context, 0));
#else
SHA1_final(digest.begin(), &m_context);
#endif
return digest;
}
void reset()
{
#ifdef TORRENT_USE_GCRYPT
gcry_md_reset(m_context);
#else
SHA1_init(&m_context);
#endif
}
#ifdef TORRENT_USE_GCRYPT
~hasher()
{
gcry_md_close(m_context);
}
#endif
private:
#ifdef TORRENT_USE_GCRYPT
gcry_md_hd_t m_context;
#else
sha_ctx m_context;
#endif
};
}
#endif // TORRENT_HASHER_HPP_INCLUDED
<commit_msg>fix openssl build<commit_after>/*
Copyright (c) 2003-2012, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_HASHER_HPP_INCLUDED
#define TORRENT_HASHER_HPP_INCLUDED
#include <boost/cstdint.hpp>
#include "libtorrent/peer_id.hpp"
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"
#ifdef TORRENT_USE_GCRYPT
#include <gcrypt.h>
#elif defined TORRENT_USE_OPENSSL
extern "C"
{
#include <openssl/sha.h>
}
#else
// from sha1.cpp
namespace libtorrent
{
struct TORRENT_EXTRA_EXPORT sha_ctx
{
boost::uint32_t state[5];
boost::uint32_t count[2];
boost::uint8_t buffer[64];
};
TORRENT_EXTRA_EXPORT void SHA1_init(sha_ctx* context);
TORRENT_EXTRA_EXPORT void SHA1_update(sha_ctx* context, boost::uint8_t const* data, boost::uint32_t len);
TORRENT_EXTRA_EXPORT void SHA1_final(boost::uint8_t* digest, sha_ctx* context);
} // namespace libtorrent
#endif
namespace libtorrent
{
class hasher
{
public:
hasher()
{
#ifdef TORRENT_USE_GCRYPT
gcry_md_open(&m_context, GCRY_MD_SHA1, 0);
#elif defined TORRENT_USE_OPENSSL
SHA1_Init(&m_context);
#else
SHA1_init(&m_context);
#endif
}
hasher(const char* data, int len)
{
TORRENT_ASSERT(data != 0);
TORRENT_ASSERT(len > 0);
#ifdef TORRENT_USE_GCRYPT
gcry_md_open(&m_context, GCRY_MD_SHA1, 0);
gcry_md_write(m_context, data, len);
#elif defined TORRENT_USE_OPENSSL
SHA1_Init(&m_context);
SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#else
SHA1_init(&m_context);
SHA1_update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#endif
}
#ifdef TORRENT_USE_GCRYPT
hasher(hasher const& h)
{
gcry_md_copy(&m_context, h.m_context);
}
hasher& operator=(hasher const& h)
{
gcry_md_close(m_context);
gcry_md_copy(&m_context, h.m_context);
return *this;
}
#endif
void update(std::string const& data) { update(data.c_str(), data.size()); }
void update(const char* data, int len)
{
TORRENT_ASSERT(data != 0);
TORRENT_ASSERT(len > 0);
#ifdef TORRENT_USE_GCRYPT
gcry_md_write(m_context, data, len);
#elif defined TORRENT_USE_OPENSSL
SHA1_Update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#else
SHA1_update(&m_context, reinterpret_cast<unsigned char const*>(data), len);
#endif
}
sha1_hash final()
{
sha1_hash digest;
#ifdef TORRENT_USE_GCRYPT
gcry_md_final(m_context);
digest.assign((const char*)gcry_md_read(m_context, 0));
#elif defined TORRENT_USE_OPENSSL
SHA1_Final(digest.begin(), &m_context);
#else
SHA1_final(digest.begin(), &m_context);
#endif
return digest;
}
void reset()
{
#ifdef TORRENT_USE_GCRYPT
gcry_md_reset(m_context);
#elif defined TORRENT_USE_OPENSSL
SHA1_Init(&m_context);
#else
SHA1_init(&m_context);
#endif
}
#ifdef TORRENT_USE_GCRYPT
~hasher()
{
gcry_md_close(m_context);
}
#endif
private:
#ifdef TORRENT_USE_GCRYPT
gcry_md_hd_t m_context;
#elif defined TORRENT_USE_OPENSSL
SHA_CTX m_context;
#else
sha_ctx m_context;
#endif
};
}
#endif // TORRENT_HASHER_HPP_INCLUDED
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_SOCKET_WIN_HPP_INCLUDED
#define TORRENT_SOCKET_WIN_HPP_INCLUDED
// TODO: remove the dependency of
// platform specific headers here.
// sockaddr_in is hard to get rid of in a nice way
#if defined(_WIN32)
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
#include <arpa/inet.h>
#endif
#include <boost/smart_ptr.hpp>
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <vector>
#include <exception>
#include <string>
namespace libtorrent
{
class network_error : public std::exception
{
public:
network_error(int error_code): m_error_code(error_code) {}
virtual const char* what() const throw();
private:
int m_error_code;
};
class socket;
class address
{
friend class socket;
public:
address();
address(unsigned char a, unsigned char b, unsigned char c, unsigned char d, unsigned short port);
address(unsigned int addr, unsigned short port);
address(const std::string& addr, unsigned short port);
address(const address& a);
~address();
std::string as_string() const;
unsigned int ip() const { return m_sockaddr.sin_addr.s_addr; }
unsigned short port() const { return htons(m_sockaddr.sin_port); }
bool operator<(const address& a) const { if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); }
bool operator!=(const address& a) const { return (ip() != a.ip()) || port() != a.port(); }
bool operator==(const address& a) const { return (ip() == a.ip()) && port() == a.port(); }
private:
sockaddr_in m_sockaddr;
};
class socket: public boost::noncopyable
{
friend class address;
friend class selector;
public:
enum type
{
tcp = 0,
udp
};
socket(type t, bool blocking = true, unsigned short receive_port = 0);
virtual ~socket();
void connect(const address& addr);
void close();
void set_blocking(bool blocking);
bool is_blocking() { return m_blocking; }
const address& sender() const { return m_sender; }
address name() const;
void listen(unsigned short port, int queue);
boost::shared_ptr<libtorrent::socket> accept();
template<class T> int send(const T& buffer);
template<class T> int send_to(const address& addr, const T& buffer);
template<class T> int receive(T& buf);
int send(const char* buffer, int size);
int send_to(const address& addr, const char* buffer, int size);
int receive(char* buffer, int size);
void set_receive_bufsize(int size);
void set_send_bufsize(int size);
bool is_readable() const;
bool is_writable() const;
enum error_code
{
netdown,
fault,
access,
address_in_use,
address_not_available,
in_progress,
interrupted,
invalid,
net_reset,
not_connected,
no_buffers,
operation_not_supported,
not_socket,
shutdown,
would_block,
connection_reset,
timed_out,
connection_aborted,
message_size,
not_ready,
no_support,
connection_refused,
is_connected,
net_unreachable,
not_initialized,
unknown_error
};
error_code last_error() const;
private:
socket(int sock, const address& sender);
int m_socket;
address m_sender;
bool m_blocking;
#ifndef NDEBUG
bool m_connected; // indicates that this socket has been connected
type m_type;
#endif
};
template<class T>
inline int socket::send(const T& buf)
{
return send(reinterpret_cast<const char*>(&buf), sizeof(buf));
}
template<class T>
inline int socket::send_to(const address& addr, const T& buf)
{
return send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf));
}
template<class T>
inline int socket::receive(T& buf)
{
return receive(reinterpret_cast<char*>(&buf), sizeof(T));
}
// timeout is given in microseconds
// modified is cleared and filled with the sockets that is ready for reading or writing
// or have had an error
class selector
{
public:
void monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); }
void monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); }
void monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); }
/*
void clear_readable() { m_readable.clear(); }
void clear_writable() { m_writable.clear(); }
*/
void remove(boost::shared_ptr<socket> s);
void remove_writable(boost::shared_ptr<socket> s)
{ m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); }
bool is_writability_monitored(boost::shared_ptr<socket> s)
{
return std::find(m_writable.begin(), m_writable.end(), s)
!= m_writable.end();
}
void wait(int timeout
, std::vector<boost::shared_ptr<socket> >& readable
, std::vector<boost::shared_ptr<socket> >& writable
, std::vector<boost::shared_ptr<socket> >& error);
int count_read_monitors() const { return m_readable.size(); }
private:
std::vector<boost::shared_ptr<socket> > m_readable;
std::vector<boost::shared_ptr<socket> > m_writable;
std::vector<boost::shared_ptr<socket> > m_error;
};
}
#endif // TORRENT_SOCKET_WIN_HPP_INCLUDED
<commit_msg>Made the socket.hpp platform independent<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_SOCKET_HPP_INCLUDED
#define TORRENT_SOCKET_HPP_INCLUDED
// TODO: remove the dependency of
// platform specific headers here.
// sockaddr_in is hard to get rid of in a nice way
#if defined(_WIN32)
#include <winsock2.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
#include <arpa/inet.h>
#endif
#include <boost/smart_ptr.hpp>
#include <boost/function.hpp>
#include <boost/noncopyable.hpp>
#include <vector>
#include <exception>
#include <string>
namespace libtorrent
{
class network_error : public std::exception
{
public:
network_error(int error_code): m_error_code(error_code) {}
virtual const char* what() const throw();
private:
int m_error_code;
};
class socket;
class address
{
friend class socket;
public:
address();
address(
unsigned char a
, unsigned char b
, unsigned char c
, unsigned char d
, unsigned short port);
address(unsigned int addr, unsigned short port);
address(const std::string& addr, unsigned short port);
address(const address& a);
~address();
std::string as_string() const;
unsigned int ip() const { return m_ip; }
unsigned short port() const { return m_port; }
bool operator<(const address& a) const
{ if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); }
bool operator!=(const address& a) const
{ return (ip() != a.ip()) || port() != a.port(); }
bool operator==(const address& a) const
{ return (ip() == a.ip()) && port() == a.port(); }
private:
unsigned int m_ip;
unsigned short m_port;
};
class socket: public boost::noncopyable
{
friend class address;
friend class selector;
public:
enum type
{
tcp = 0,
udp
};
socket(type t, bool blocking = true, unsigned short receive_port = 0);
virtual ~socket();
void connect(const address& addr);
void close();
void set_blocking(bool blocking);
bool is_blocking() { return m_blocking; }
const address& sender() const { return m_sender; }
address name() const;
void listen(unsigned short port, int queue);
boost::shared_ptr<libtorrent::socket> accept();
template<class T> int send(const T& buffer);
template<class T> int send_to(const address& addr, const T& buffer);
template<class T> int receive(T& buf);
int send(const char* buffer, int size);
int send_to(const address& addr, const char* buffer, int size);
int receive(char* buffer, int size);
void set_receive_bufsize(int size);
void set_send_bufsize(int size);
bool is_readable() const;
bool is_writable() const;
enum error_code
{
netdown,
fault,
access,
address_in_use,
address_not_available,
in_progress,
interrupted,
invalid,
net_reset,
not_connected,
no_buffers,
operation_not_supported,
not_socket,
shutdown,
would_block,
connection_reset,
timed_out,
connection_aborted,
message_size,
not_ready,
no_support,
connection_refused,
is_connected,
net_unreachable,
not_initialized,
unknown_error
};
error_code last_error() const;
private:
socket(int sock, const address& sender);
int m_socket;
address m_sender;
bool m_blocking;
#ifndef NDEBUG
bool m_connected; // indicates that this socket has been connected
type m_type;
#endif
};
template<class T>
inline int socket::send(const T& buf)
{
return send(reinterpret_cast<const char*>(&buf), sizeof(buf));
}
template<class T>
inline int socket::send_to(const address& addr, const T& buf)
{
return send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf));
}
template<class T>
inline int socket::receive(T& buf)
{
return receive(reinterpret_cast<char*>(&buf), sizeof(T));
}
// timeout is given in microseconds
// modified is cleared and filled with the sockets that is ready for reading or writing
// or have had an error
class selector
{
public:
void monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); }
void monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); }
void monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); }
/*
void clear_readable() { m_readable.clear(); }
void clear_writable() { m_writable.clear(); }
*/
void remove(boost::shared_ptr<socket> s);
void remove_writable(boost::shared_ptr<socket> s)
{ m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); }
bool is_writability_monitored(boost::shared_ptr<socket> s)
{
return std::find(m_writable.begin(), m_writable.end(), s)
!= m_writable.end();
}
void wait(int timeout
, std::vector<boost::shared_ptr<socket> >& readable
, std::vector<boost::shared_ptr<socket> >& writable
, std::vector<boost::shared_ptr<socket> >& error);
int count_read_monitors() const { return m_readable.size(); }
private:
std::vector<boost::shared_ptr<socket> > m_readable;
std::vector<boost::shared_ptr<socket> > m_writable;
std::vector<boost::shared_ptr<socket> > m_error;
};
}
#endif // TORRENT_SOCKET_WIN_INCLUDED
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkottiePriv.h"
#include "SkJSON.h"
#include "SkottieJson.h"
#include "SkSGColor.h"
#include "SkSGColorFilter.h"
namespace skottie {
namespace internal {
namespace {
sk_sp<sksg::RenderNode> AttachFillLayerEffect(const skjson::ArrayValue* jeffect_props,
const AnimationBuilder* abuilder,
AnimatorScope* ascope,
sk_sp<sksg::RenderNode> layer) {
if (!jeffect_props) return layer;
sk_sp<sksg::Color> color_node;
for (const skjson::ObjectValue* jprop : *jeffect_props) {
if (!jprop) continue;
switch (const auto ty = ParseDefault<int>((*jprop)["ty"], -1)) {
case 2: // color
color_node = abuilder->attachColor(*jprop, ascope, "v");
break;
default:
abuilder->log(Logger::Level::kWarning, nullptr,
"Ignoring unsupported fill effect poperty type: %d.", ty);
break;
}
}
return color_node
? sksg::ColorModeFilter::Make(std::move(layer), std::move(color_node), SkBlendMode::kSrcIn)
: nullptr;
}
} // namespace
sk_sp<sksg::RenderNode> AnimationBuilder::attachLayerEffects(const skjson::ArrayValue& jeffects,
AnimatorScope* ascope,
sk_sp<sksg::RenderNode> layer) const {
for (const skjson::ObjectValue* jeffect : jeffects) {
if (!jeffect) continue;
switch (const auto ty = ParseDefault<int>((*jeffect)["ty"], -1)) {
case 21: // Fill
layer = AttachFillLayerEffect((*jeffect)["ef"], this, ascope, std::move(layer));
break;
default:
this->log(Logger::Level::kWarning, nullptr, "Unsupported layer effect type: %d.", ty);
break;
}
}
return layer;
}
} // namespace internal
} // namespace skottie
<commit_msg>[skottie] Add support for fill effect opacity<commit_after>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkottiePriv.h"
#include "SkJSON.h"
#include "SkottieJson.h"
#include "SkottieValue.h"
#include "SkSGColor.h"
#include "SkSGColorFilter.h"
namespace skottie {
namespace internal {
namespace {
sk_sp<sksg::RenderNode> AttachFillLayerEffect(const skjson::ArrayValue* jeffect_props,
const AnimationBuilder* abuilder,
AnimatorScope* ascope,
sk_sp<sksg::RenderNode> layer) {
if (!jeffect_props) return nullptr;
// Effect properties are index-based.
enum {
kFillMask_Index = 0,
kAllMasks_Index = 1,
kColor_Index = 2,
kInvert_Index = 3,
kHFeather_Index = 4,
kVFeather_Index = 5,
kOpacity_Index = 6,
kMax_Index = kOpacity_Index,
};
if (jeffect_props->size() <= kMax_Index) {
return nullptr;
}
const skjson::ObjectValue* color_prop = (*jeffect_props)[ kColor_Index];
const skjson::ObjectValue* opacity_prop = (*jeffect_props)[kOpacity_Index];
if (!color_prop || !opacity_prop) {
return nullptr;
}
sk_sp<sksg::Color> color_node = abuilder->attachColor(*color_prop, ascope, "v");
if (!color_node) {
return nullptr;
}
abuilder->bindProperty<ScalarValue>((*opacity_prop)["v"], ascope,
[color_node](const ScalarValue& o) {
const auto c = color_node->getColor();
const auto a = sk_float_round2int_no_saturate(SkTPin(o, 0.0f, 1.0f) * 255);
color_node->setColor(SkColorSetA(c, a));
});
return sksg::ColorModeFilter::Make(std::move(layer),
std::move(color_node),
SkBlendMode::kSrcIn);
}
} // namespace
sk_sp<sksg::RenderNode> AnimationBuilder::attachLayerEffects(const skjson::ArrayValue& jeffects,
AnimatorScope* ascope,
sk_sp<sksg::RenderNode> layer) const {
for (const skjson::ObjectValue* jeffect : jeffects) {
if (!jeffect) continue;
switch (const auto ty = ParseDefault<int>((*jeffect)["ty"], -1)) {
case 21: // Fill
layer = AttachFillLayerEffect((*jeffect)["ef"], this, ascope, std::move(layer));
break;
default:
this->log(Logger::Level::kWarning, nullptr, "Unsupported layer effect type: %d.", ty);
break;
}
if (!layer) {
this->log(Logger::Level::kError, jeffect, "Invalid layer effect.");
return nullptr;
}
}
return layer;
}
} // namespace internal
} // namespace skottie
<|endoftext|> |
<commit_before>/*
* Copyright 2020 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/skshaper/include/SkShaper.h"
#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
#ifdef SK_BUILD_FOR_MAC
#import <ApplicationServices/ApplicationServices.h>
#endif
#ifdef SK_BUILD_FOR_IOS
#include <CoreText/CoreText.h>
#include <CoreText/CTFontManager.h>
#include <CoreGraphics/CoreGraphics.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#include "include/ports/SkTypeface_mac.h"
#include "src/core/SkArenaAlloc.h"
#include <vector>
class SkShaper_CoreText : public SkShaper {
public:
SkShaper_CoreText() {}
private:
void shape(const char* utf8, size_t utf8Bytes,
const SkFont& srcFont,
bool leftToRight,
SkScalar width,
RunHandler*) const override;
void shape(const char* utf8, size_t utf8Bytes,
FontRunIterator&,
BiDiRunIterator&,
ScriptRunIterator&,
LanguageRunIterator&,
SkScalar width,
RunHandler*) const override;
void shape(const char* utf8, size_t utf8Bytes,
FontRunIterator&,
BiDiRunIterator&,
ScriptRunIterator&,
LanguageRunIterator&,
const Feature*, size_t featureSize,
SkScalar width,
RunHandler*) const override;
};
std::unique_ptr<SkShaper> SkShaper::MakeCoreText() {
return std::make_unique<SkShaper_CoreText>();
}
void SkShaper_CoreText::shape(const char* utf8, size_t utf8Bytes,
FontRunIterator& font,
BiDiRunIterator& bidi,
ScriptRunIterator&,
LanguageRunIterator&,
SkScalar width,
RunHandler* handler) const
{
SkFont skfont;
if (!font.atEnd()) {
font.consume();
skfont = font.currentFont();
} else {
skfont.setTypeface(sk_ref_sp(skfont.getTypefaceOrDefault()));
}
SkASSERT(skfont.getTypeface());
bool skbidi = 0;
if (!bidi.atEnd()) {
bidi.consume();
skbidi = (bidi.currentLevel() % 2) == 0;
}
return this->shape(utf8, utf8Bytes, skfont, skbidi, width, handler);
}
void SkShaper_CoreText::shape(const char* utf8, size_t utf8Bytes,
FontRunIterator& font,
BiDiRunIterator& bidi,
ScriptRunIterator&,
LanguageRunIterator&,
const Feature*, size_t,
SkScalar width,
RunHandler* handler) const {
font.consume();
SkASSERT(font.currentFont().getTypeface());
bidi.consume();
return this->shape(utf8, utf8Bytes, font.currentFont(), (bidi.currentLevel() % 2) == 0,
width, handler);
}
template <typename T> class AutoCF {
T fObj;
public:
AutoCF(T obj) : fObj(obj) {}
~AutoCF() { CFRelease(fObj); }
T get() const { return fObj; }
};
// CTFramesetter/CTFrame can do this, but require version 10.14
class LineBreakIter {
CTTypesetterRef fTypesetter;
double fWidth;
CFIndex fStart;
public:
LineBreakIter(CTTypesetterRef ts, SkScalar width) : fTypesetter(ts), fWidth(width) {
fStart = 0;
}
CTLineRef nextLine() {
CFIndex count = CTTypesetterSuggestLineBreak(fTypesetter, fStart, fWidth);
if (count == 0) {
return nullptr;
}
auto line = CTTypesetterCreateLine(fTypesetter, {fStart, count});
fStart += count;
return line;
}
};
static void dict_add_double(CFMutableDictionaryRef d, const void* name, double value) {
AutoCF<CFNumberRef> number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value);
CFDictionaryAddValue(d, name, number.get());
}
static void dump(CFDictionaryRef d) {
CFIndex count = CFDictionaryGetCount(d);
std::vector<const void*> keys(count);
std::vector<const void*> vals(count);
CFDictionaryGetKeysAndValues(d, keys.data(), vals.data());
for (CFIndex i = 0; i < count; ++i) {
CFStringRef kstr = (CFStringRef)keys[i];
const char* ckstr = CFStringGetCStringPtr(kstr, kCFStringEncodingUTF8);
SkDebugf("dict[%d] %s %p\n", i, ckstr, vals[i]);
}
}
static CTFontRef create_ctfont_from_font(const SkFont& font) {
auto typeface = font.getTypefaceOrDefault();
auto ctfont = SkTypeface_GetCTFontRef(typeface);
return CTFontCreateCopyWithAttributes(ctfont, font.getSize(), nullptr, nullptr);
}
static SkFont run_to_font(CTRunRef run, const SkFont& orig) {
CFDictionaryRef attr = CTRunGetAttributes(run);
CTFontRef ct = (CTFontRef)CFDictionaryGetValue(attr, kCTFontAttributeName);
if (!ct) {
SkDebugf("no ctfont in Run Attributes\n");
dump(attr);
return orig;
}
// Do I need to add a local cache, or allow the caller to manage this lookup?
SkFont font(orig);
font.setTypeface(SkMakeTypefaceFromCTFont(ct));
return font;
}
// kCTTrackingAttributeName not available until 10.12
const CFStringRef kCTTracking_AttributeName = CFSTR("CTTracking");
void SkShaper_CoreText::shape(const char* utf8, size_t utf8Bytes,
const SkFont& font,
bool /* leftToRight */,
SkScalar width,
RunHandler* handler) const {
auto cgfloat_to_scalar = [](CGFloat x) {
SkScalar s;
if (sizeof(CGFloat) == sizeof(double)) {
s = SkDoubleToScalar(x);
} else {
s = x;
}
return s;
};
AutoCF<CFStringRef> textString = CFStringCreateWithBytes(nullptr, (const uint8_t*)utf8, utf8Bytes,
kCFStringEncodingUTF8, false);
AutoCF<CTFontRef> ctfont = create_ctfont_from_font(font);
AutoCF<CFMutableDictionaryRef> attr =
CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(attr.get(), kCTFontAttributeName, ctfont.get());
if (false) {
// trying to see what these affect
dict_add_double(attr.get(), kCTTracking_AttributeName, 1);
dict_add_double(attr.get(), kCTKernAttributeName, 0.0);
}
AutoCF<CFAttributedStringRef> attrString =
CFAttributedStringCreate(nullptr, textString.get(), attr.get());
AutoCF<CTTypesetterRef> typesetter =
CTTypesetterCreateWithAttributedStringAndOptions(attrString.get(), nullptr);
SkSTArenaAlloc<4096> arena;
// We have to compute RunInfos in a loop, and then reuse them in a 2nd loop,
// so we store them in an array (we reuse the array's storage for each line).
std::vector<SkShaper::RunHandler::RunInfo> infos;
LineBreakIter iter(typesetter.get(), width);
while (CTLineRef line = iter.nextLine()) {
CFArrayRef run_array = CTLineGetGlyphRuns(line);
CFIndex runCount = CFArrayGetCount(run_array);
if (runCount == 0) {
continue;
}
handler->beginLine();
infos.clear();
for (CFIndex j = 0; j < runCount; ++j) {
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(run_array, j);
CFIndex runGlyphs = CTRunGetGlyphCount(run);
SkASSERT(sizeof(CGGlyph) == sizeof(uint16_t));
CGSize* advances = arena.makeArrayDefault<CGSize>(runGlyphs);
CTRunGetAdvances(run, {0, runGlyphs}, advances);
SkScalar adv = 0;
for (CFIndex k = 0; k < runGlyphs; ++k) {
adv += advances[k].width;
}
arena.reset();
CFRange range = CTRunGetStringRange(run);
SkFont run_font = run_to_font(run, font);
infos.push_back({
run_font,
0, // need fBidiLevel
{adv, 0},
(size_t)runGlyphs,
{(size_t)range.location, (size_t)range.length},
});
handler->runInfo(infos.back());
}
handler->commitRunInfo();
// Now loop through again and fill in the buffers
for (CFIndex j = 0; j < runCount; ++j) {
const auto& info = infos[j];
auto buffer = handler->runBuffer(info);
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(run_array, j);
CFIndex runGlyphs = info.glyphCount;
SkASSERT(CTRunGetGlyphCount(run) == (CFIndex)info.glyphCount);
CTRunGetGlyphs(run, {0, runGlyphs}, buffer.glyphs);
CGPoint* positions = arena.makeArrayDefault<CGPoint>(runGlyphs);
CTRunGetPositions(run, {0, runGlyphs}, positions);
CFIndex* indices = nullptr;
if (buffer.clusters) {
indices = arena.makeArrayDefault<CFIndex>(runGlyphs);
CTRunGetStringIndices(run, {0, runGlyphs}, indices);
}
for (CFIndex k = 0; k < runGlyphs; ++k) {
buffer.positions[k] = {
buffer.point.fX + cgfloat_to_scalar(positions[k].x),
buffer.point.fY,
};
if (buffer.offsets) {
buffer.offsets[k] = {0, 0}; // offset relative to the origin for this glyph
}
if (buffer.clusters) {
buffer.clusters[k] = indices[k];
}
}
arena.reset();
handler->commitRunBuffer(info);
}
handler->commitLine();
}
}
#else
std::unique_ptr<SkShaper> SkShaper::MakeCoreText() {
return nullptr;
}
#endif
<commit_msg>be sure to keep the fonts alive for the two loops<commit_after>/*
* Copyright 2020 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "modules/skshaper/include/SkShaper.h"
#if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
#ifdef SK_BUILD_FOR_MAC
#import <ApplicationServices/ApplicationServices.h>
#endif
#ifdef SK_BUILD_FOR_IOS
#include <CoreText/CoreText.h>
#include <CoreText/CTFontManager.h>
#include <CoreGraphics/CoreGraphics.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#include "include/ports/SkTypeface_mac.h"
#include "src/core/SkArenaAlloc.h"
#include <vector>
class SkShaper_CoreText : public SkShaper {
public:
SkShaper_CoreText() {}
private:
void shape(const char* utf8, size_t utf8Bytes,
const SkFont& srcFont,
bool leftToRight,
SkScalar width,
RunHandler*) const override;
void shape(const char* utf8, size_t utf8Bytes,
FontRunIterator&,
BiDiRunIterator&,
ScriptRunIterator&,
LanguageRunIterator&,
SkScalar width,
RunHandler*) const override;
void shape(const char* utf8, size_t utf8Bytes,
FontRunIterator&,
BiDiRunIterator&,
ScriptRunIterator&,
LanguageRunIterator&,
const Feature*, size_t featureSize,
SkScalar width,
RunHandler*) const override;
};
std::unique_ptr<SkShaper> SkShaper::MakeCoreText() {
return std::make_unique<SkShaper_CoreText>();
}
void SkShaper_CoreText::shape(const char* utf8, size_t utf8Bytes,
FontRunIterator& font,
BiDiRunIterator& bidi,
ScriptRunIterator&,
LanguageRunIterator&,
SkScalar width,
RunHandler* handler) const
{
SkFont skfont;
if (!font.atEnd()) {
font.consume();
skfont = font.currentFont();
} else {
skfont.setTypeface(sk_ref_sp(skfont.getTypefaceOrDefault()));
}
SkASSERT(skfont.getTypeface());
bool skbidi = 0;
if (!bidi.atEnd()) {
bidi.consume();
skbidi = (bidi.currentLevel() % 2) == 0;
}
return this->shape(utf8, utf8Bytes, skfont, skbidi, width, handler);
}
void SkShaper_CoreText::shape(const char* utf8, size_t utf8Bytes,
FontRunIterator& font,
BiDiRunIterator& bidi,
ScriptRunIterator&,
LanguageRunIterator&,
const Feature*, size_t,
SkScalar width,
RunHandler* handler) const {
font.consume();
SkASSERT(font.currentFont().getTypeface());
bidi.consume();
return this->shape(utf8, utf8Bytes, font.currentFont(), (bidi.currentLevel() % 2) == 0,
width, handler);
}
template <typename T> class AutoCF {
T fObj;
public:
AutoCF(T obj) : fObj(obj) {}
~AutoCF() { CFRelease(fObj); }
T get() const { return fObj; }
};
// CTFramesetter/CTFrame can do this, but require version 10.14
class LineBreakIter {
CTTypesetterRef fTypesetter;
double fWidth;
CFIndex fStart;
public:
LineBreakIter(CTTypesetterRef ts, SkScalar width) : fTypesetter(ts), fWidth(width) {
fStart = 0;
}
CTLineRef nextLine() {
CFIndex count = CTTypesetterSuggestLineBreak(fTypesetter, fStart, fWidth);
if (count == 0) {
return nullptr;
}
auto line = CTTypesetterCreateLine(fTypesetter, {fStart, count});
fStart += count;
return line;
}
};
static void dict_add_double(CFMutableDictionaryRef d, const void* name, double value) {
AutoCF<CFNumberRef> number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &value);
CFDictionaryAddValue(d, name, number.get());
}
static void dump(CFDictionaryRef d) {
CFIndex count = CFDictionaryGetCount(d);
std::vector<const void*> keys(count);
std::vector<const void*> vals(count);
CFDictionaryGetKeysAndValues(d, keys.data(), vals.data());
for (CFIndex i = 0; i < count; ++i) {
CFStringRef kstr = (CFStringRef)keys[i];
const char* ckstr = CFStringGetCStringPtr(kstr, kCFStringEncodingUTF8);
SkDebugf("dict[%d] %s %p\n", i, ckstr, vals[i]);
}
}
static CTFontRef create_ctfont_from_font(const SkFont& font) {
auto typeface = font.getTypefaceOrDefault();
auto ctfont = SkTypeface_GetCTFontRef(typeface);
return CTFontCreateCopyWithAttributes(ctfont, font.getSize(), nullptr, nullptr);
}
static SkFont run_to_font(CTRunRef run, const SkFont& orig) {
CFDictionaryRef attr = CTRunGetAttributes(run);
CTFontRef ct = (CTFontRef)CFDictionaryGetValue(attr, kCTFontAttributeName);
if (!ct) {
SkDebugf("no ctfont in Run Attributes\n");
dump(attr);
return orig;
}
// Do I need to add a local cache, or allow the caller to manage this lookup?
SkFont font(orig);
font.setTypeface(SkMakeTypefaceFromCTFont(ct));
return font;
}
// kCTTrackingAttributeName not available until 10.12
const CFStringRef kCTTracking_AttributeName = CFSTR("CTTracking");
void SkShaper_CoreText::shape(const char* utf8, size_t utf8Bytes,
const SkFont& font,
bool /* leftToRight */,
SkScalar width,
RunHandler* handler) const {
auto cgfloat_to_scalar = [](CGFloat x) {
SkScalar s;
if (sizeof(CGFloat) == sizeof(double)) {
s = SkDoubleToScalar(x);
} else {
s = x;
}
return s;
};
AutoCF<CFStringRef> textString = CFStringCreateWithBytes(nullptr, (const uint8_t*)utf8, utf8Bytes,
kCFStringEncodingUTF8, false);
AutoCF<CTFontRef> ctfont = create_ctfont_from_font(font);
AutoCF<CFMutableDictionaryRef> attr =
CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionaryAddValue(attr.get(), kCTFontAttributeName, ctfont.get());
if (false) {
// trying to see what these affect
dict_add_double(attr.get(), kCTTracking_AttributeName, 1);
dict_add_double(attr.get(), kCTKernAttributeName, 0.0);
}
AutoCF<CFAttributedStringRef> attrString =
CFAttributedStringCreate(nullptr, textString.get(), attr.get());
AutoCF<CTTypesetterRef> typesetter =
CTTypesetterCreateWithAttributedStringAndOptions(attrString.get(), nullptr);
SkSTArenaAlloc<4096> arena;
// We have to compute RunInfos in a loop, and then reuse them in a 2nd loop,
// so we store them in an array (we reuse the array's storage for each line).
std::vector<SkFont> fontStorage;
std::vector<SkShaper::RunHandler::RunInfo> infos;
LineBreakIter iter(typesetter.get(), width);
while (CTLineRef line = iter.nextLine()) {
CFArrayRef run_array = CTLineGetGlyphRuns(line);
CFIndex runCount = CFArrayGetCount(run_array);
if (runCount == 0) {
continue;
}
handler->beginLine();
fontStorage.clear();
infos.clear();
for (CFIndex j = 0; j < runCount; ++j) {
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(run_array, j);
CFIndex runGlyphs = CTRunGetGlyphCount(run);
SkASSERT(sizeof(CGGlyph) == sizeof(uint16_t));
CGSize* advances = arena.makeArrayDefault<CGSize>(runGlyphs);
CTRunGetAdvances(run, {0, runGlyphs}, advances);
SkScalar adv = 0;
for (CFIndex k = 0; k < runGlyphs; ++k) {
adv += advances[k].width;
}
arena.reset();
CFRange range = CTRunGetStringRange(run);
fontStorage.push_back(run_to_font(run, font));
infos.push_back({
fontStorage.back(), // info just stores a ref to the font
0, // need fBidiLevel
{adv, 0},
(size_t)runGlyphs,
{(size_t)range.location, (size_t)range.length},
});
handler->runInfo(infos.back());
}
handler->commitRunInfo();
// Now loop through again and fill in the buffers
for (CFIndex j = 0; j < runCount; ++j) {
const auto& info = infos[j];
auto buffer = handler->runBuffer(info);
CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(run_array, j);
CFIndex runGlyphs = info.glyphCount;
SkASSERT(CTRunGetGlyphCount(run) == (CFIndex)info.glyphCount);
CTRunGetGlyphs(run, {0, runGlyphs}, buffer.glyphs);
CGPoint* positions = arena.makeArrayDefault<CGPoint>(runGlyphs);
CTRunGetPositions(run, {0, runGlyphs}, positions);
CFIndex* indices = nullptr;
if (buffer.clusters) {
indices = arena.makeArrayDefault<CFIndex>(runGlyphs);
CTRunGetStringIndices(run, {0, runGlyphs}, indices);
}
for (CFIndex k = 0; k < runGlyphs; ++k) {
buffer.positions[k] = {
buffer.point.fX + cgfloat_to_scalar(positions[k].x),
buffer.point.fY,
};
if (buffer.offsets) {
buffer.offsets[k] = {0, 0}; // offset relative to the origin for this glyph
}
if (buffer.clusters) {
buffer.clusters[k] = indices[k];
}
}
arena.reset();
handler->commitRunBuffer(info);
}
handler->commitLine();
}
}
#else
std::unique_ptr<SkShaper> SkShaper::MakeCoreText() {
return nullptr;
}
#endif
<|endoftext|> |
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005, 2006, 2007 Roman Schindlauer
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
* Copyright (C) 2009, 2010 Peter Schüller
* Copyright (C) 2011, 2012, 2013 Christoph Redl
*
* This file is part of dlvhex.
*
* dlvhex 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.1 of
* the License, or (at your option) any later version.
*
* dlvhex 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 dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file Term.cpp
* @author Christoph Redl
*
* @brief Implementation of Term.h
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include "dlvhex2/Term.h"
#include "dlvhex2/Logger.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Interpretation.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/PluginInterface.h"
#include "dlvhex2/OrdinaryAtomTable.h"
#include <boost/foreach.hpp>
#include <map>
DLVHEX_NAMESPACE_BEGIN
Term::Term(IDKind kind, const std::vector<ID>& arguments, RegistryPtr reg): kind(kind), arguments(arguments) {
assert(ID(kind,0).isTerm());
assert(arguments.size() > 0);
updateSymbolOfNestedTerm(reg.get());
}
void Term::updateSymbolOfNestedTerm(Registry* reg){
std::stringstream ss;
ss << reg->terms.getByID(arguments[0]).symbol;
if (arguments.size() > 1){
ss << "(";
for (uint32_t i = 1; i < arguments.size(); ++i){
ss << (i > 1 ? "," : "");
if (arguments[i].isIntegerTerm()){
ss << arguments[i].address;
}else{
ss << reg->terms.getByID(arguments[i]).symbol;
}
}
ss << ")";
}
symbol = ss.str();
}
// restores the hierarchical structure of a term from a string representation
void Term::analyzeTerm(RegistryPtr reg){
// get token: function name and arguments
bool quoted = false;
bool primitive = true;
int nestedcount = 0;
int start = 0;
int end = symbol.length();
std::vector<std::string> tuple;
//DBGLOG(DBG,"Analyzing Term '" << symbol << "'");
for (int pos = 0; pos < end; ++pos){
if (symbol[pos] == '\"' &&
(pos == 0 || symbol[pos-1] != '\\')) quoted = !quoted;
if (symbol[pos] == '(' && !quoted ) {
if (nestedcount == 0) {
primitive = false;
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
// eliminate closing bracket
assert(symbol[end-1] == ')');
end--;
}
nestedcount++;
}
if (symbol[pos] == ')' && !quoted){
nestedcount--;
}
if (symbol[pos] == ',' && !quoted && nestedcount == 1){
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
}
if (pos == end - 1){
tuple.push_back(symbol.substr(start, pos - start + 1));
}
}
// we did not find a ( -> it is primitive, or
// we came into (, increased by one, and eliminated the closing )
// therefore if it is not primitive we must leave the loop at 1
assert(primitive || nestedcount == 1);
#ifndef NDEBUG
{
std::stringstream ss;
ss << "Term tuple: ";
bool first = true;
BOOST_FOREACH (std::string str, tuple){
if (!first) ss << ", ";
first = false;
ss << str;
}
DBGLOG(DBG, ss.str());
}
#endif
// convert tuple of strings to terms
arguments.clear();
if (primitive){
arguments.push_back(ID_FAIL);
if (islower(symbol[0]) || symbol[0] == '\"') kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(symbol[0])) kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
BOOST_FOREACH (std::string str, tuple){
Term t(ID::MAINKIND_TERM, str);
t.analyzeTerm(reg);
if (t.arguments[0] == ID_FAIL){
if (islower(t.symbol[0]) || t.symbol[0] == '\"') t.kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(t.symbol[0])) t.kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
t.kind |= ID::SUBKIND_TERM_NESTED;
}
ID tid = reg->terms.getIDByString(t.symbol);
if (tid == ID_FAIL) tid = reg->terms.storeAndGetID(t);
arguments.push_back(tid);
}
kind |= ID::SUBKIND_TERM_NESTED;
}
}
DLVHEX_NAMESPACE_END
<commit_msg>store subterms with help of registry<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces.
* Copyright (C) 2005, 2006, 2007 Roman Schindlauer
* Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner
* Copyright (C) 2009, 2010 Peter Schüller
* Copyright (C) 2011, 2012, 2013 Christoph Redl
*
* This file is part of dlvhex.
*
* dlvhex 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.1 of
* the License, or (at your option) any later version.
*
* dlvhex 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 dlvhex; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
/**
* @file Term.cpp
* @author Christoph Redl
*
* @brief Implementation of Term.h
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif // HAVE_CONFIG_H
#include "dlvhex2/Term.h"
#include "dlvhex2/Logger.h"
#include "dlvhex2/Printhelpers.h"
#include "dlvhex2/Interpretation.h"
#include "dlvhex2/Registry.h"
#include "dlvhex2/Printer.h"
#include "dlvhex2/PluginInterface.h"
#include "dlvhex2/OrdinaryAtomTable.h"
#include <boost/foreach.hpp>
#include <map>
DLVHEX_NAMESPACE_BEGIN
Term::Term(IDKind kind, const std::vector<ID>& arguments, RegistryPtr reg): kind(kind), arguments(arguments) {
assert(ID(kind,0).isTerm());
assert(arguments.size() > 0);
updateSymbolOfNestedTerm(reg.get());
}
void Term::updateSymbolOfNestedTerm(Registry* reg){
std::stringstream ss;
ss << reg->terms.getByID(arguments[0]).symbol;
if (arguments.size() > 1){
ss << "(";
for (uint32_t i = 1; i < arguments.size(); ++i){
ss << (i > 1 ? "," : "");
if (arguments[i].isIntegerTerm()){
ss << arguments[i].address;
}else{
ss << reg->terms.getByID(arguments[i]).symbol;
}
}
ss << ")";
}
symbol = ss.str();
}
// restores the hierarchical structure of a term from a string representation
void Term::analyzeTerm(RegistryPtr reg){
// get token: function name and arguments
bool quoted = false;
bool primitive = true;
int nestedcount = 0;
int start = 0;
int end = symbol.length();
std::vector<std::string> tuple;
//DBGLOG(DBG,"Analyzing Term '" << symbol << "'");
for (int pos = 0; pos < end; ++pos){
if (symbol[pos] == '\"' &&
(pos == 0 || symbol[pos-1] != '\\')) quoted = !quoted;
if (symbol[pos] == '(' && !quoted ) {
if (nestedcount == 0) {
primitive = false;
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
// eliminate closing bracket
assert(symbol[end-1] == ')');
end--;
}
nestedcount++;
}
if (symbol[pos] == ')' && !quoted){
nestedcount--;
}
if (symbol[pos] == ',' && !quoted && nestedcount == 1){
tuple.push_back(symbol.substr(start, pos - start));
start = pos + 1;
}
if (pos == end - 1){
tuple.push_back(symbol.substr(start, pos - start + 1));
}
}
// we did not find a ( -> it is primitive, or
// we came into (, increased by one, and eliminated the closing )
// therefore if it is not primitive we must leave the loop at 1
assert(primitive || nestedcount == 1);
#ifndef NDEBUG
{
std::stringstream ss;
ss << "Term tuple: ";
bool first = true;
BOOST_FOREACH (std::string str, tuple){
if (!first) ss << ", ";
first = false;
ss << str;
}
DBGLOG(DBG, ss.str());
}
#endif
// convert tuple of strings to terms
arguments.clear();
if (primitive){
arguments.push_back(ID_FAIL);
if (islower(symbol[0]) || symbol[0] == '\"') kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(symbol[0])) kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
BOOST_FOREACH (std::string str, tuple){
Term t(ID::MAINKIND_TERM, str);
t.analyzeTerm(reg);
if (t.arguments[0] == ID_FAIL){
if (islower(t.symbol[0]) || t.symbol[0] == '\"') t.kind |= ID::SUBKIND_TERM_CONSTANT;
if (isupper(t.symbol[0])) t.kind |= ID::SUBKIND_TERM_VARIABLE;
}else{
t.kind |= ID::SUBKIND_TERM_NESTED;
}
ID tid = reg->storeTerm(t);
arguments.push_back(tid);
}
kind |= ID::SUBKIND_TERM_NESTED;
}
}
DLVHEX_NAMESPACE_END
<|endoftext|> |
<commit_before>/******************************************************************************
* File: cube.cpp
*
* Purpose: Implements the Rubik's cube at the cubie level, and provides
* translation to the coordinates required for the two-phase Kociemba
* algorithm to run.
*******************************************************************************
/******************************************************************************
* Includes
******************************************************************************/
#include <algorithm>
#include <vector>
#include <cube.h>
/******************************************************************************
* Cube class implementation
******************************************************************************/
/******************************************************************************
* Function: Cube::Cube
*
* Purpose: Instantiates a representation of a Rubik's cube at the cubie level
*
* Params: None
*
* Returns: Nothing
*
* Operation: Initialises the cube in the solved state.
******************************************************************************/
Cube::Cube()
{
corner_permutation = {0, 1, 2, 3, 4, 5, 6, 7};
corner_orientation = {0, 0, 0, 0, 0, 0, 0, 0};
edge_permutation = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
edge_orientation = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
}
/******************************************************************************
* Function: Cube::perform_move
*
* Purpose: Performs a move on this CUbe object
*
* Params: face - which face is being rotated
* turn_dir - is this turn cw, ccw or 180 degrees?
*
* Returns: Nothing
*
* Operation: Update the permutation and orientation of all the pieces according
* to the particular move being performed.
******************************************************************************/
void Cube::perform_move(cube_face_t face, cube_turn_t turn_dir)
{
// Local variables
std::vector<int> corners_moved;
std::vector<int> edges_moved;
std::vector<int> corner_twist;
std::vector<int> edge_flip;
// Set up new vectors in which to hold the result of the move having been
// performed
std::vector<int> new_corner_permutation = corner_permutation;
std::vector<int> new_corner_orientation = corner_orientation;
std::vector<int> new_edge_permutation = edge_permutation;
std::vector<int> new_edge_orientation = edge_orientation;
// Switch based on the face being turned to determine which corners and
// edges are permuted by this move and how the orientations of the pieces
// are affected.
switch (face)
{
case FACE_U:
corners_moved = {CORNER_URF, CORNER_UFL, CORNER_ULB, CORNER_UBR};
edges_moved = {EDGE_UF, EDGE_UL, EDGE_UB, EDGE_UR};
corner_twist = {TWIST_NONE, TWIST_NONE, TWIST_NONE, TWIST_NONE};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
case FACE_L:
corners_moved = {CORNER_UFL, CORNER_DLF, CORNER_DBL, CORNER_ULB};
edges_moved = {EDGE_UL, EDGE_FL, EDGE_DL, EDGE_BL};
corner_twist = {TWIST_CCW, TWIST_CW, TWIST_CCW, TWIST_CW};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
case FACE_F:
corners_moved = {CORNER_URF, CORNER_DFR, CORNER_DLF, CORNER_UFL};
edges_moved = {EDGE_UF, EDGE_FR, EDGE_DF, EDGE_FL};
corner_twist = {TWIST_CCW, TWIST_CW, TWIST_CCW, TWIST_CW};
edge_flip = {FLIP_FLIP, FLIP_FLIP, FLIP_FLIP, FLIP_FLIP};
break;
case FACE_R:
corners_moved = {CORNER_URF, CORNER_UBR, CORNER_DRB, CORNER_DFR};
edges_moved = {EDGE_UR, EDGE_BR, EDGE_DR, EDGE_FR};
corner_twist = {TWIST_CW, TWIST_CCW, TWIST_CW, TWIST_CCW};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
case FACE_B:
corners_moved = {CORNER_UBR, CORNER_ULB, CORNER_DBL, CORNER_DRB};
edges_moved = {EDGE_UB, EDGE_BL, EDGE_DB, EDGE_BR};
corner_twist = {TWIST_CW, TWIST_CCW, TWIST_CW, TWIST_CCW};
edge_flip = {FLIP_FLIP, FLIP_FLIP, FLIP_FLIP, FLIP_FLIP};
break;
case FACE_D:
corners_moved = {CORNER_DFR, CORNER_DRB, CORNER_DBL, CORNER_DLF};
edges_moved = {EDGE_DF, EDGE_DR, EDGE_DB, EDGE_DL};
corner_twist = {TWIST_NONE, TWIST_NONE, TWIST_NONE, TWIST_NONE};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
}
// Update the corner permutation and orientation
for (int ii = 0; ii < corners_moved.size(); ++ii)
{
// Permute the corners according to how far we turned the face
int from = corners_moved[ii];
int to = corners_moved[(ii + turn_dir) % corners_moved.size()];
new_corner_permutation[to] = corner_permutation[from];
// Calculate the total twist for this corner piece and update it
int twist = 0;
for (int jj = 0; jj < turn_dir; ++jj)
{
twist += corner_twist[(ii + jj) % corners_moved.size()];
}
new_corner_orientation[to] = (corner_orientation[from] + twist) % 3;
}
// Update the edge permutation and orientation
for (int ii = 0; ii < edges_moved.size(); ++ii)
{
// Permute the edges according to how far we turned the face
int from = edges_moved[ii];
int to = edges_moved[(ii + turn_dir) % edges_moved.size()];
new_edge_permutation[to] = from;
// Calculate the total flip for this edge piece and update it
int flip = 0;
for (int jj = 0; jj < turn_dir; ++jj)
{
flip += edge_flip[(ii + jj) % edges_moved.size()];
}
new_edge_orientation[to] = (edge_orientation[from] + flip) % 2;
}
// Replace the old permutations and orientations with the new ones
corner_permutation = new_corner_permutation;
corner_orientation = new_corner_orientation;
edge_permutation = new_edge_permutation;
edge_orientation = new_edge_orientation;
}
/******************************************************************************
* Function: Cube::coord_corner_orientation
*
* Purpose: Extract the corner orientation coordinate from the current cube
* position.
*
* Params: None
*
* Returns: The value of the corner orientation coordinate.
*
* Operation: Calculates the value of the corner orientation coordinate by
* combining the twist of each individual corner piece into a single
* integer result using a ternary encoding.
******************************************************************************/
int Cube::coord_corner_orientation()
{
// Interpret the corner orientation vector as a base-3 number to get the
// value of this coordinate
int ret = 0;
for (int ii = 0; ii < corner_orientation.size(); ++ii)
{
ret = (3 * ret + corner_orientation[ii]);
}
return ret;
}
/******************************************************************************
* Function: Cube::coord_edge_orientation
*
* Purpose: Extract the edge orientation coordinate from the current cube
* position.
*
* Params: None
*
* Returns: The value of the edge orientation coordinate.
*
* Operation: Calculates the value of the edge orientation coordinate by
* combining the flip of each individual corner piece into a single
* integer result using a binary encoding.
******************************************************************************/
int Cube::coord_edge_orientation()
{
// Interpret the edge orientation vector as a base-2 number to get the
// value of this coordinate
int ret = 0;
for (int ii = 0; ii < edge_orientation.size(); ++ii)
{
ret = (2 * ret + edge_orientation[ii]);
}
return ret;
}
/******************************************************************************
* Function: Cube::coord_corner_permutation
*
* Purpose: Extract the corner permutation coordinate from the current cube
* position.
*
* Params: None.
*
* Returns: The value of the corner permutation coordinate.
*
* Operation: Calculates the value of the corner permutation coordinate by
* working out the lexicographic position of the vector which
* represents the corner permutation.
******************************************************************************/
int Cube::coord_corner_permutation()
{
// Local variable to keep track of value of factorials
int factorial = 1;
// Calculate the lexicographic position of the permutation represented by
// the vector corner_permutation - for each element of the permutation,
// work out how many elements following it have a lower value, and use
// these numbers as the coefficients of some factorials.
int ret = 0;
for (int ii = corner_permutation.size() - 1; ii >= 0; --ii)
{
int low_count = 0;
for (int jj = ii + 1; jj < corner_permutation.size(); ++jj)
{
if (corner_permutation[jj] < corner_permutation[ii])
{
++low_count;
}
}
ret += low_count * factorial;
factorial *= corner_permutation.size() - ii;
}
return ret;
}
/******************************************************************************
* Function: Cube::coord_slice_sorted
*
* Purpose: Given a particular slice of edges, extract the associated sorted
* slice coordinate from the current cube position.
*
* Params: None.
*
* Returns: The value of the sorted slice coordinate.
*
* Operation: Calculates the lexicographic position x of the set of 4 positions
* occupied by the four slice edges, and also the lexicographic
* position y of the permutation of these 4 edges among themselves,
* and calculates the coordinate as 24x + y.
******************************************************************************/
int Cube::coord_slice_sorted(std::vector<int> edges)
{
// Local variables n, k.
int n = edge_permutation.size() - 1;
int k = edges.size();
// Local variable binom which represents the value of (n choose k), and
// which will be updated alongside n and k as we progress.
int binom = 1;
for (int ii = 1; ii <= k; ++ii)
{
binom *= (n - ii + 1);
binom /= ii;
}
// The order in which the edges making up this slice appear in the current
// cube position.
std::vector<int> order = {};
// Calculate the lexicographic position of the four positions occupied by
// the slice edges.
int pos = 0;
while (k >= 0)
{
int curr_edge = edge_permutation[n];
if (std::find(edges.begin(), edges.end(), curr_edge) != edges.end())
{
// We've found one of the edges, so update the values of k and of
// the binomial coefficient
binom *= k--;
binom /= (n - k);
// Store the edge so we know the order in which they appear in the
// cube.
order.push_back(curr_edge);
}
else
{
// Add on the current binomial coeffcient to the value
pos += binom;
}
// Update the values of n and the binomial coeffcient
binom *= (n - k);
binom /= n--;
}
// Now calculate the lexicographic position of the permutation of the four
// edges among themselves
int perm = 0; int factorial = 1;
for (int ii = order.size() - 1; ii >= 0; --ii)
{
int high_count = 0;
for (int jj = ii + 1; jj < order.size(); ++jj)
{
if (order[jj] > order[ii])
{
++high_count;
}
}
perm += high_count * factorial;
factorial *= (order.size() - ii);
}
// Return the combination of these two data which makes the coordinate
return 24 * pos + perm;
}
/******************************************************************************
* Function: Cube::coord_ud_sorted
*
* Purpose: Extracts the value of the sorted UD-slice coordinate fromt the
* current cube position.
*
* Params: None.
*
* Returns: The value of the sorted UD-slice coordinate.
*
* Operation: Calls into coord_slice_sorted with a specific set of edges for
* the UD-slice.
******************************************************************************/
int Cube::coord_ud_sorted()
{
std::vector<int> edges = {EDGE_FR, EDGE_FL, EDGE_BL, EDGE_BR};
return coord_slice_sorted(edges);
}
/******************************************************************************
* Function: Cube::coord_rl_sorted
*
* Purpose: Extracts the value of the sorted RL-slice coordinate fromt the
* current cube position.
*
* Params: None.
*
* Returns: The value of the sorted RL-slice coordinate.
*
* Operation: Calls into coord_slice_sorted with a specific set of edges for
* the RL-slice.
******************************************************************************/
int Cube::coord_rl_sorted()
{
std::vector<int> edges = {EDGE_UF, EDGE_UB, EDGE_DB, EDGE_DF};
return coord_slice_sorted(edges);
}
/******************************************************************************
* Function: Cube::coord_fb_sorted
*
* Purpose: Extracts the value of the sorted FB-slice coordinate fromt the
* current cube position.
*
* Params: None.
*
* Returns: The value of the sorted FB-slice coordinate.
*
* Operation: Calls into coord_slice_sorted with a specific set of edges for
* the -slice.
******************************************************************************/
int Cube::coord_fb_sorted()
{
std::vector<int> edges = {EDGE_UR, EDGE_UL, EDGE_DL, EDGE_DR};
return coord_slice_sorted(edges);
}
int main()
{
return 0;
}<commit_msg>Remove code that should never have been committed<commit_after>/******************************************************************************
* File: cube.cpp
*
* Purpose: Implements the Rubik's cube at the cubie level, and provides
* translation to the coordinates required for the two-phase Kociemba
* algorithm to run.
*******************************************************************************
/******************************************************************************
* Includes
******************************************************************************/
#include <algorithm>
#include <vector>
#include <cube.h>
/******************************************************************************
* Cube class implementation
******************************************************************************/
/******************************************************************************
* Function: Cube::Cube
*
* Purpose: Instantiates a representation of a Rubik's cube at the cubie level
*
* Params: None
*
* Returns: Nothing
*
* Operation: Initialises the cube in the solved state.
******************************************************************************/
Cube::Cube()
{
corner_permutation = {0, 1, 2, 3, 4, 5, 6, 7};
corner_orientation = {0, 0, 0, 0, 0, 0, 0, 0};
edge_permutation = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
edge_orientation = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
}
/******************************************************************************
* Function: Cube::perform_move
*
* Purpose: Performs a move on this CUbe object
*
* Params: face - which face is being rotated
* turn_dir - is this turn cw, ccw or 180 degrees?
*
* Returns: Nothing
*
* Operation: Update the permutation and orientation of all the pieces according
* to the particular move being performed.
******************************************************************************/
void Cube::perform_move(cube_face_t face, cube_turn_t turn_dir)
{
// Local variables
std::vector<int> corners_moved;
std::vector<int> edges_moved;
std::vector<int> corner_twist;
std::vector<int> edge_flip;
// Set up new vectors in which to hold the result of the move having been
// performed
std::vector<int> new_corner_permutation = corner_permutation;
std::vector<int> new_corner_orientation = corner_orientation;
std::vector<int> new_edge_permutation = edge_permutation;
std::vector<int> new_edge_orientation = edge_orientation;
// Switch based on the face being turned to determine which corners and
// edges are permuted by this move and how the orientations of the pieces
// are affected.
switch (face)
{
case FACE_U:
corners_moved = {CORNER_URF, CORNER_UFL, CORNER_ULB, CORNER_UBR};
edges_moved = {EDGE_UF, EDGE_UL, EDGE_UB, EDGE_UR};
corner_twist = {TWIST_NONE, TWIST_NONE, TWIST_NONE, TWIST_NONE};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
case FACE_L:
corners_moved = {CORNER_UFL, CORNER_DLF, CORNER_DBL, CORNER_ULB};
edges_moved = {EDGE_UL, EDGE_FL, EDGE_DL, EDGE_BL};
corner_twist = {TWIST_CCW, TWIST_CW, TWIST_CCW, TWIST_CW};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
case FACE_F:
corners_moved = {CORNER_URF, CORNER_DFR, CORNER_DLF, CORNER_UFL};
edges_moved = {EDGE_UF, EDGE_FR, EDGE_DF, EDGE_FL};
corner_twist = {TWIST_CCW, TWIST_CW, TWIST_CCW, TWIST_CW};
edge_flip = {FLIP_FLIP, FLIP_FLIP, FLIP_FLIP, FLIP_FLIP};
break;
case FACE_R:
corners_moved = {CORNER_URF, CORNER_UBR, CORNER_DRB, CORNER_DFR};
edges_moved = {EDGE_UR, EDGE_BR, EDGE_DR, EDGE_FR};
corner_twist = {TWIST_CW, TWIST_CCW, TWIST_CW, TWIST_CCW};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
case FACE_B:
corners_moved = {CORNER_UBR, CORNER_ULB, CORNER_DBL, CORNER_DRB};
edges_moved = {EDGE_UB, EDGE_BL, EDGE_DB, EDGE_BR};
corner_twist = {TWIST_CW, TWIST_CCW, TWIST_CW, TWIST_CCW};
edge_flip = {FLIP_FLIP, FLIP_FLIP, FLIP_FLIP, FLIP_FLIP};
break;
case FACE_D:
corners_moved = {CORNER_DFR, CORNER_DRB, CORNER_DBL, CORNER_DLF};
edges_moved = {EDGE_DF, EDGE_DR, EDGE_DB, EDGE_DL};
corner_twist = {TWIST_NONE, TWIST_NONE, TWIST_NONE, TWIST_NONE};
edge_flip = {FLIP_NONE, FLIP_NONE, FLIP_NONE, FLIP_NONE};
break;
}
// Update the corner permutation and orientation
for (int ii = 0; ii < corners_moved.size(); ++ii)
{
// Permute the corners according to how far we turned the face
int from = corners_moved[ii];
int to = corners_moved[(ii + turn_dir) % corners_moved.size()];
new_corner_permutation[to] = corner_permutation[from];
// Calculate the total twist for this corner piece and update it
int twist = 0;
for (int jj = 0; jj < turn_dir; ++jj)
{
twist += corner_twist[(ii + jj) % corners_moved.size()];
}
new_corner_orientation[to] = (corner_orientation[from] + twist) % 3;
}
// Update the edge permutation and orientation
for (int ii = 0; ii < edges_moved.size(); ++ii)
{
// Permute the edges according to how far we turned the face
int from = edges_moved[ii];
int to = edges_moved[(ii + turn_dir) % edges_moved.size()];
new_edge_permutation[to] = from;
// Calculate the total flip for this edge piece and update it
int flip = 0;
for (int jj = 0; jj < turn_dir; ++jj)
{
flip += edge_flip[(ii + jj) % edges_moved.size()];
}
new_edge_orientation[to] = (edge_orientation[from] + flip) % 2;
}
// Replace the old permutations and orientations with the new ones
corner_permutation = new_corner_permutation;
corner_orientation = new_corner_orientation;
edge_permutation = new_edge_permutation;
edge_orientation = new_edge_orientation;
}
/******************************************************************************
* Function: Cube::coord_corner_orientation
*
* Purpose: Extract the corner orientation coordinate from the current cube
* position.
*
* Params: None
*
* Returns: The value of the corner orientation coordinate.
*
* Operation: Calculates the value of the corner orientation coordinate by
* combining the twist of each individual corner piece into a single
* integer result using a ternary encoding.
******************************************************************************/
int Cube::coord_corner_orientation()
{
// Interpret the corner orientation vector as a base-3 number to get the
// value of this coordinate
int ret = 0;
for (int ii = 0; ii < corner_orientation.size(); ++ii)
{
ret = (3 * ret + corner_orientation[ii]);
}
return ret;
}
/******************************************************************************
* Function: Cube::coord_edge_orientation
*
* Purpose: Extract the edge orientation coordinate from the current cube
* position.
*
* Params: None
*
* Returns: The value of the edge orientation coordinate.
*
* Operation: Calculates the value of the edge orientation coordinate by
* combining the flip of each individual corner piece into a single
* integer result using a binary encoding.
******************************************************************************/
int Cube::coord_edge_orientation()
{
// Interpret the edge orientation vector as a base-2 number to get the
// value of this coordinate
int ret = 0;
for (int ii = 0; ii < edge_orientation.size(); ++ii)
{
ret = (2 * ret + edge_orientation[ii]);
}
return ret;
}
/******************************************************************************
* Function: Cube::coord_corner_permutation
*
* Purpose: Extract the corner permutation coordinate from the current cube
* position.
*
* Params: None.
*
* Returns: The value of the corner permutation coordinate.
*
* Operation: Calculates the value of the corner permutation coordinate by
* working out the lexicographic position of the vector which
* represents the corner permutation.
******************************************************************************/
int Cube::coord_corner_permutation()
{
// Local variable to keep track of value of factorials
int factorial = 1;
// Calculate the lexicographic position of the permutation represented by
// the vector corner_permutation - for each element of the permutation,
// work out how many elements following it have a lower value, and use
// these numbers as the coefficients of some factorials.
int ret = 0;
for (int ii = corner_permutation.size() - 1; ii >= 0; --ii)
{
int low_count = 0;
for (int jj = ii + 1; jj < corner_permutation.size(); ++jj)
{
if (corner_permutation[jj] < corner_permutation[ii])
{
++low_count;
}
}
ret += low_count * factorial;
factorial *= corner_permutation.size() - ii;
}
return ret;
}
/******************************************************************************
* Function: Cube::coord_slice_sorted
*
* Purpose: Given a particular slice of edges, extract the associated sorted
* slice coordinate from the current cube position.
*
* Params: None.
*
* Returns: The value of the sorted slice coordinate.
*
* Operation: Calculates the lexicographic position x of the set of 4 positions
* occupied by the four slice edges, and also the lexicographic
* position y of the permutation of these 4 edges among themselves,
* and calculates the coordinate as 24x + y.
******************************************************************************/
int Cube::coord_slice_sorted(std::vector<int> edges)
{
// Local variables n, k.
int n = edge_permutation.size() - 1;
int k = edges.size();
// Local variable binom which represents the value of (n choose k), and
// which will be updated alongside n and k as we progress.
int binom = 1;
for (int ii = 1; ii <= k; ++ii)
{
binom *= (n - ii + 1);
binom /= ii;
}
// The order in which the edges making up this slice appear in the current
// cube position.
std::vector<int> order = {};
// Calculate the lexicographic position of the four positions occupied by
// the slice edges.
int pos = 0;
while (k >= 0)
{
int curr_edge = edge_permutation[n];
if (std::find(edges.begin(), edges.end(), curr_edge) != edges.end())
{
// We've found one of the edges, so update the values of k and of
// the binomial coefficient
binom *= k--;
binom /= (n - k);
// Store the edge so we know the order in which they appear in the
// cube.
order.push_back(curr_edge);
}
else
{
// Add on the current binomial coeffcient to the value
pos += binom;
}
// Update the values of n and the binomial coeffcient
binom *= (n - k);
binom /= n--;
}
// Now calculate the lexicographic position of the permutation of the four
// edges among themselves
int perm = 0; int factorial = 1;
for (int ii = order.size() - 1; ii >= 0; --ii)
{
int high_count = 0;
for (int jj = ii + 1; jj < order.size(); ++jj)
{
if (order[jj] > order[ii])
{
++high_count;
}
}
perm += high_count * factorial;
factorial *= (order.size() - ii);
}
// Return the combination of these two data which makes the coordinate
return 24 * pos + perm;
}
/******************************************************************************
* Function: Cube::coord_ud_sorted
*
* Purpose: Extracts the value of the sorted UD-slice coordinate fromt the
* current cube position.
*
* Params: None.
*
* Returns: The value of the sorted UD-slice coordinate.
*
* Operation: Calls into coord_slice_sorted with a specific set of edges for
* the UD-slice.
******************************************************************************/
int Cube::coord_ud_sorted()
{
std::vector<int> edges = {EDGE_FR, EDGE_FL, EDGE_BL, EDGE_BR};
return coord_slice_sorted(edges);
}
/******************************************************************************
* Function: Cube::coord_rl_sorted
*
* Purpose: Extracts the value of the sorted RL-slice coordinate fromt the
* current cube position.
*
* Params: None.
*
* Returns: The value of the sorted RL-slice coordinate.
*
* Operation: Calls into coord_slice_sorted with a specific set of edges for
* the RL-slice.
******************************************************************************/
int Cube::coord_rl_sorted()
{
std::vector<int> edges = {EDGE_UF, EDGE_UB, EDGE_DB, EDGE_DF};
return coord_slice_sorted(edges);
}
/******************************************************************************
* Function: Cube::coord_fb_sorted
*
* Purpose: Extracts the value of the sorted FB-slice coordinate fromt the
* current cube position.
*
* Params: None.
*
* Returns: The value of the sorted FB-slice coordinate.
*
* Operation: Calls into coord_slice_sorted with a specific set of edges for
* the -slice.
******************************************************************************/
int Cube::coord_fb_sorted()
{
std::vector<int> edges = {EDGE_UR, EDGE_UL, EDGE_DL, EDGE_DR};
return coord_slice_sorted(edges);
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_core_server.hpp>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <algorithm>
#include <srs_core_log.hpp>
#include <srs_core_error.hpp>
#include <srs_core_client.hpp>
#include <srs_core_config.hpp>
#define SERVER_LISTEN_BACKLOG 10
#define SRS_TIME_RESOLUTION_MS 500
SrsListener::SrsListener(SrsServer* _server, SrsListenerType _type)
{
fd = -1;
stfd = NULL;
port = 0;
server = _server;
type = _type;
pthread = new SrsThread(this, 0);
}
SrsListener::~SrsListener()
{
srs_close_stfd(stfd);
pthread->stop();
srs_freep(pthread);
// st does not close it sometimes,
// close it manually.
close(fd);
}
int SrsListener::listen(int _port)
{
int ret = ERROR_SUCCESS;
port = _port;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
ret = ERROR_SOCKET_CREATE;
srs_error("create linux socket error. ret=%d", ret);
return ret;
}
srs_verbose("create linux socket success. fd=%d", fd);
int reuse_socket = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_socket, sizeof(int)) == -1) {
ret = ERROR_SOCKET_SETREUSE;
srs_error("setsockopt reuse-addr error. ret=%d", ret);
return ret;
}
srs_verbose("setsockopt reuse-addr success. fd=%d", fd);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(fd, (const sockaddr*)&addr, sizeof(sockaddr_in)) == -1) {
ret = ERROR_SOCKET_BIND;
srs_error("bind socket error. ret=%d", ret);
return ret;
}
srs_verbose("bind socket success. fd=%d", fd);
if (::listen(fd, SERVER_LISTEN_BACKLOG) == -1) {
ret = ERROR_SOCKET_LISTEN;
srs_error("listen socket error. ret=%d", ret);
return ret;
}
srs_verbose("listen socket success. fd=%d", fd);
if ((stfd = st_netfd_open_socket(fd)) == NULL){
ret = ERROR_ST_OPEN_SOCKET;
srs_error("st_netfd_open_socket open socket failed. ret=%d", ret);
return ret;
}
srs_verbose("st open socket success. fd=%d", fd);
if ((ret = pthread->start()) != ERROR_SUCCESS) {
srs_error("st_thread_create listen thread error. ret=%d", ret);
return ret;
}
srs_verbose("create st listen thread success.");
srs_trace("server started, listen at port=%d, fd=%d", port, fd);
return ret;
}
void SrsListener::on_enter_loop()
{
srs_trace("listen cycle start, port=%d, type=%d, fd=%d", port, type, fd);
}
int SrsListener::cycle()
{
int ret = ERROR_SUCCESS;
st_netfd_t client_stfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT);
if(client_stfd == NULL){
// ignore error.
srs_warn("ignore accept thread stoppped for accept client error");
return ret;
}
srs_verbose("get a client. fd=%d", st_netfd_fileno(client_stfd));
if ((ret = server->accept_client(type, client_stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
return ret;
}
SrsServer::SrsServer()
{
signal_reload = false;
srs_assert(config);
config->subscribe(this);
}
SrsServer::~SrsServer()
{
config->unsubscribe(this);
if (true) {
std::vector<SrsConnection*>::iterator it;
for (it = conns.begin(); it != conns.end(); ++it) {
SrsConnection* conn = *it;
srs_freep(conn);
}
conns.clear();
}
close_listeners();
}
int SrsServer::initialize()
{
int ret = ERROR_SUCCESS;
// use linux epoll.
if (st_set_eventsys(ST_EVENTSYS_ALT) == -1) {
ret = ERROR_ST_SET_EPOLL;
srs_error("st_set_eventsys use linux epoll failed. ret=%d", ret);
return ret;
}
srs_verbose("st_set_eventsys use linux epoll success");
if(st_init() != 0){
ret = ERROR_ST_INITIALIZE;
srs_error("st_init failed. ret=%d", ret);
return ret;
}
srs_verbose("st_init success");
// set current log id.
log_context->generate_id();
srs_info("log set id success");
return ret;
}
int SrsServer::listen()
{
int ret = ERROR_SUCCESS;
SrsConfDirective* conf = NULL;
// stream service port.
conf = config->get_listen();
srs_assert(conf);
close_listeners();
for (int i = 0; i < (int)conf->args.size(); i++) {
SrsListener* listener = new SrsListener(this, SrsListenerStream);
listeners.push_back(listener);
int port = ::atoi(conf->args.at(i).c_str());
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
return ret;
}
int SrsServer::cycle()
{
int ret = ERROR_SUCCESS;
// the deamon thread, update the time cache
while (true) {
st_usleep(SRS_TIME_RESOLUTION_MS * 1000);
srs_update_system_time_ms();
if (signal_reload) {
signal_reload = false;
srs_info("get signal reload, to reload the config.");
if ((ret = config->reload()) != ERROR_SUCCESS) {
srs_error("reload config failed. ret=%d", ret);
return ret;
}
srs_trace("reload config success.");
}
}
return ret;
}
void SrsServer::remove(SrsConnection* conn)
{
std::vector<SrsConnection*>::iterator it = std::find(conns.begin(), conns.end(), conn);
if (it != conns.end()) {
conns.erase(it);
}
srs_info("conn removed. conns=%d", (int)conns.size());
// all connections are created by server,
// so we free it here.
srs_freep(conn);
}
void SrsServer::on_signal(int signo)
{
if (signo == SIGNAL_RELOAD) {
signal_reload = true;
}
// TODO: handle the SIGINT, SIGTERM.
}
void SrsServer::close_listeners()
{
std::vector<SrsListener*>::iterator it;
for (it = listeners.begin(); it != listeners.end(); ++it) {
SrsListener* listener = *it;
srs_freep(listener);
}
listeners.clear();
}
int SrsServer::accept_client(SrsListenerType type, st_netfd_t client_stfd)
{
int ret = ERROR_SUCCESS;
int max_connections = config->get_max_connections();
if ((int)conns.size() >= max_connections) {
int fd = st_netfd_fileno(client_stfd);
srs_error("exceed the max connections, drop client: "
"clients=%d, max=%d, fd=%d", (int)conns.size(), max_connections, fd);
srs_close_stfd(client_stfd);
return ret;
}
SrsConnection* conn = NULL;
if (type == SrsListenerStream) {
conn = new SrsClient(this, client_stfd);
} else {
// handler others
}
srs_assert(conn);
// directly enqueue, the cycle thread will remove the client.
conns.push_back(conn);
srs_verbose("add conn from port %d to vector. conns=%d", port, (int)conns.size());
// cycle will start process thread and when finished remove the client.
if ((ret = conn->start()) != ERROR_SUCCESS) {
return ret;
}
srs_verbose("conn start finished. ret=%d", ret);
return ret;
}
int SrsServer::on_reload_listen()
{
return listen();
}
SrsServer* _server()
{
static SrsServer server;
return &server;
}
<commit_msg>fix the listen backlog bug, change from 10 to 512<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_core_server.hpp>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <algorithm>
#include <srs_core_log.hpp>
#include <srs_core_error.hpp>
#include <srs_core_client.hpp>
#include <srs_core_config.hpp>
#define SERVER_LISTEN_BACKLOG 512
#define SRS_TIME_RESOLUTION_MS 500
SrsListener::SrsListener(SrsServer* _server, SrsListenerType _type)
{
fd = -1;
stfd = NULL;
port = 0;
server = _server;
type = _type;
pthread = new SrsThread(this, 0);
}
SrsListener::~SrsListener()
{
srs_close_stfd(stfd);
pthread->stop();
srs_freep(pthread);
// st does not close it sometimes,
// close it manually.
close(fd);
}
int SrsListener::listen(int _port)
{
int ret = ERROR_SUCCESS;
port = _port;
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
ret = ERROR_SOCKET_CREATE;
srs_error("create linux socket error. ret=%d", ret);
return ret;
}
srs_verbose("create linux socket success. fd=%d", fd);
int reuse_socket = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_socket, sizeof(int)) == -1) {
ret = ERROR_SOCKET_SETREUSE;
srs_error("setsockopt reuse-addr error. ret=%d", ret);
return ret;
}
srs_verbose("setsockopt reuse-addr success. fd=%d", fd);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(fd, (const sockaddr*)&addr, sizeof(sockaddr_in)) == -1) {
ret = ERROR_SOCKET_BIND;
srs_error("bind socket error. ret=%d", ret);
return ret;
}
srs_verbose("bind socket success. fd=%d", fd);
if (::listen(fd, SERVER_LISTEN_BACKLOG) == -1) {
ret = ERROR_SOCKET_LISTEN;
srs_error("listen socket error. ret=%d", ret);
return ret;
}
srs_verbose("listen socket success. fd=%d", fd);
if ((stfd = st_netfd_open_socket(fd)) == NULL){
ret = ERROR_ST_OPEN_SOCKET;
srs_error("st_netfd_open_socket open socket failed. ret=%d", ret);
return ret;
}
srs_verbose("st open socket success. fd=%d", fd);
if ((ret = pthread->start()) != ERROR_SUCCESS) {
srs_error("st_thread_create listen thread error. ret=%d", ret);
return ret;
}
srs_verbose("create st listen thread success.");
srs_trace("server started, listen at port=%d, fd=%d", port, fd);
return ret;
}
void SrsListener::on_enter_loop()
{
srs_trace("listen cycle start, port=%d, type=%d, fd=%d", port, type, fd);
}
int SrsListener::cycle()
{
int ret = ERROR_SUCCESS;
st_netfd_t client_stfd = st_accept(stfd, NULL, NULL, ST_UTIME_NO_TIMEOUT);
if(client_stfd == NULL){
// ignore error.
srs_warn("ignore accept thread stoppped for accept client error");
return ret;
}
srs_verbose("get a client. fd=%d", st_netfd_fileno(client_stfd));
if ((ret = server->accept_client(type, client_stfd)) != ERROR_SUCCESS) {
srs_warn("accept client error. ret=%d", ret);
return ret;
}
srs_verbose("accept client finished. conns=%d, ret=%d", (int)conns.size(), ret);
return ret;
}
SrsServer::SrsServer()
{
signal_reload = false;
srs_assert(config);
config->subscribe(this);
}
SrsServer::~SrsServer()
{
config->unsubscribe(this);
if (true) {
std::vector<SrsConnection*>::iterator it;
for (it = conns.begin(); it != conns.end(); ++it) {
SrsConnection* conn = *it;
srs_freep(conn);
}
conns.clear();
}
close_listeners();
}
int SrsServer::initialize()
{
int ret = ERROR_SUCCESS;
// use linux epoll.
if (st_set_eventsys(ST_EVENTSYS_ALT) == -1) {
ret = ERROR_ST_SET_EPOLL;
srs_error("st_set_eventsys use linux epoll failed. ret=%d", ret);
return ret;
}
srs_verbose("st_set_eventsys use linux epoll success");
if(st_init() != 0){
ret = ERROR_ST_INITIALIZE;
srs_error("st_init failed. ret=%d", ret);
return ret;
}
srs_verbose("st_init success");
// set current log id.
log_context->generate_id();
srs_info("log set id success");
return ret;
}
int SrsServer::listen()
{
int ret = ERROR_SUCCESS;
SrsConfDirective* conf = NULL;
// stream service port.
conf = config->get_listen();
srs_assert(conf);
close_listeners();
for (int i = 0; i < (int)conf->args.size(); i++) {
SrsListener* listener = new SrsListener(this, SrsListenerStream);
listeners.push_back(listener);
int port = ::atoi(conf->args.at(i).c_str());
if ((ret = listener->listen(port)) != ERROR_SUCCESS) {
srs_error("listen at port %d failed. ret=%d", port, ret);
return ret;
}
}
return ret;
}
int SrsServer::cycle()
{
int ret = ERROR_SUCCESS;
// the deamon thread, update the time cache
while (true) {
st_usleep(SRS_TIME_RESOLUTION_MS * 1000);
srs_update_system_time_ms();
if (signal_reload) {
signal_reload = false;
srs_info("get signal reload, to reload the config.");
if ((ret = config->reload()) != ERROR_SUCCESS) {
srs_error("reload config failed. ret=%d", ret);
return ret;
}
srs_trace("reload config success.");
}
}
return ret;
}
void SrsServer::remove(SrsConnection* conn)
{
std::vector<SrsConnection*>::iterator it = std::find(conns.begin(), conns.end(), conn);
if (it != conns.end()) {
conns.erase(it);
}
srs_info("conn removed. conns=%d", (int)conns.size());
// all connections are created by server,
// so we free it here.
srs_freep(conn);
}
void SrsServer::on_signal(int signo)
{
if (signo == SIGNAL_RELOAD) {
signal_reload = true;
}
// TODO: handle the SIGINT, SIGTERM.
}
void SrsServer::close_listeners()
{
std::vector<SrsListener*>::iterator it;
for (it = listeners.begin(); it != listeners.end(); ++it) {
SrsListener* listener = *it;
srs_freep(listener);
}
listeners.clear();
}
int SrsServer::accept_client(SrsListenerType type, st_netfd_t client_stfd)
{
int ret = ERROR_SUCCESS;
int max_connections = config->get_max_connections();
if ((int)conns.size() >= max_connections) {
int fd = st_netfd_fileno(client_stfd);
srs_error("exceed the max connections, drop client: "
"clients=%d, max=%d, fd=%d", (int)conns.size(), max_connections, fd);
srs_close_stfd(client_stfd);
return ret;
}
SrsConnection* conn = NULL;
if (type == SrsListenerStream) {
conn = new SrsClient(this, client_stfd);
} else {
// handler others
}
srs_assert(conn);
// directly enqueue, the cycle thread will remove the client.
conns.push_back(conn);
srs_verbose("add conn from port %d to vector. conns=%d", port, (int)conns.size());
// cycle will start process thread and when finished remove the client.
if ((ret = conn->start()) != ERROR_SUCCESS) {
return ret;
}
srs_verbose("conn start finished. ret=%d", ret);
return ret;
}
int SrsServer::on_reload_listen()
{
return listen();
}
SrsServer* _server()
{
static SrsServer server;
return &server;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) Daliworks, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <Arduino.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <Time.h>
#include "Thingplus.h"
#define THINGPLUS_VALUE_MESSAGE_LEN 36
#define THINGPLUS_TOPIC_LEN 80
#define THINGPLUS_SHORT_TOPIC_LEN 32
void serverTimeSync(const char *serverTimeMs) {
#define TIME_LENGTH 10
char serverTimeSec[TIME_LENGTH+1] = {0,};
strncpy(serverTimeSec, serverTimeMs, TIME_LENGTH);
int i;
time_t syncTime = 0;
for (i=0; i<TIME_LENGTH; i++)
syncTime = (10 * syncTime) + (serverTimeSec[i] - '0');
setTime(syncTime);
Serial.print(F("[INFO]Time Synced. NOW:"));
Serial.println(now());
}
void mqttSubscribeCallback(char *topic, uint8_t *payload, unsigned int length)
{
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject((char*)payload);
if (!root.success()) {
Serial.println(F("parseObject() failed"));
return;
}
const char *id = root["id"];
const char *method = root["method"];
Serial.print(F("Message subscribed. method:"));
Serial.println(method);
Serial.flush();
if (strcmp(method, "controlActuator") == 0) {
char *result = Thingplus._actuatorDo(root["params"]["id"], root["params"]["cmd"], root["params"]["options"]);
Thingplus._actuatorResultPublish(id, result);
}
else if (strcmp(method, "timeSync") == 0) {
serverTimeSync(root["params"]["time"]);
}
}
void ThingplusClass::_actuatorResultPublish(const char *messageId, char *result)
{
char responseTopic[THINGPLUS_SHORT_TOPIC_LEN] = {0,};
sprintf(responseTopic, "v/a/g/%s/res", this->gatewayId);
char resposeMessage[64] = {0,};
if (result)
sprintf(resposeMessage, "{\"id\":\"%s\",\"result\":\"%s\"}", messageId, result);
else
sprintf(resposeMessage, "{\"id\":\"%s\",\"error\": {\"code\": -32000}}", messageId);
this->mqtt.publish(responseTopic, resposeMessage);
}
char *ThingplusClass::_actuatorDo(const char *id, const char *cmd, const char *options)
{
if (!this->actuatorCallback) {
return NULL;
}
return this->actuatorCallback(id, cmd, options);
}
void ThingplusClass::actuatorCallbackSet(char* (*cb)(const char* id, const char* cmd, const char* options))
{
this->actuatorCallback = cb;
}
bool ThingplusClass::valuePublish(const char *id, char *value)
{
char valuePublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf(valuePublishTopic, "v/a/g/%s/s/%s", this->gatewayId, id);
char v[THINGPLUS_VALUE_MESSAGE_LEN] = {0,};
sprintf(v, "%ld000,%s", now(), value);
return this->mqtt.publish(valuePublishTopic, v);
}
bool ThingplusClass::valuePublish(const char *id, float value)
{
char valuePublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf(valuePublishTopic, "v/a/g/%s/s/%s", this->gatewayId, id);
char v[THINGPLUS_VALUE_MESSAGE_LEN] = {0,};
sprintf(v, "%ld000,", now());
dtostrf(value, 5, 2, &v[strlen(v)]);
return this->mqtt.publish(valuePublishTopic, v);
}
bool ThingplusClass::valuePublish(const char *id, int value)
{
char valuePublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf(valuePublishTopic, "v/a/g/%s/s/%s", this->gatewayId, id);
char v[THINGPLUS_VALUE_MESSAGE_LEN] = {0,};
sprintf(v, "%ld000,%d", now(), value);
return this->mqtt.publish(valuePublishTopic, v);
}
bool ThingplusClass::statusPublish(const char *topic, bool on, time_t durationSec)
{
char status[16] = {0,};
sprintf(status, "%s,%ld000", on ? "on" : "off", now() + durationSec);
return this->mqtt.publish(topic, status);
}
bool ThingplusClass::sensorStatusPublish(const char *id, bool on, time_t durationSec)
{
char statusPublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf(statusPublishTopic, "v/a/g/%s/s/%s/status", this->gatewayId, id);
return this->statusPublish(statusPublishTopic, on, durationSec);
}
bool ThingplusClass::gatewayStatusPublish(bool on, time_t durationSec)
{
char statusPublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf(statusPublishTopic, "v/a/g/%s/status", this->gatewayId);
return this->statusPublish(statusPublishTopic, on, durationSec);
}
bool ThingplusClass::mqttStatusPublish(bool on)
{
char topic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf(topic, "v/a/g/%s/mqtt/status", this->gatewayId);
const char *message = on ? "on" : "off";
return this->mqtt.publish(topic, message);
}
bool ThingplusClass::loop(void)
{
if (!this->mqtt.connected()) {
Serial.println(F("[ERR] MQTT disconnected"));
this->connect();
}
return this->mqtt.loop();
}
void ThingplusClass::connect(void)
{
#define MQTT_RETRY_INTERVAL_MS (5 * 1000)
bool ret;
char willTopic[32] = {0,};
sprintf(willTopic, "v/a/g/%s/mqtt/status", this->gatewayId);
do
{
ret = this->mqtt.connect(this->gatewayId, this->gatewayId,
this->apikey, willTopic, 1, true, "err");
if (!ret) {
Serial.print(F("ERR: MQTT connection failed."));
int errCode = this->mqtt.state();
if (errCode == 5)
Serial.println(F(" APIKEY ERROR"));
else
Serial.println(this->mqtt.state());
Serial.println(F("ERR: Retry"));
delay(MQTT_RETRY_INTERVAL_MS);
}
} while(!this->mqtt.connected());
char subscribeTopic[32] = {0,};
sprintf(subscribeTopic, "v/a/g/%s/req", this->gatewayId);
this->mqtt.subscribe(subscribeTopic);
this->mqttStatusPublish(true);
Serial.println(F("INFO: MQTT Connected"));
}
void ThingplusClass::disconnect(void)
{
this->mqtt.disconnect();
Serial.println(F("INFO: MQTT Disconnected"));
}
void ThingplusClass::begin(Client& client, byte mac[], const char *apikey)
{
const char *server = "dmqtt.thingplus.net";
const int port = 1883;
this->mac = mac;
sprintf(this->gatewayId, "%02x%02x%02x%02x%02x%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
this->apikey = apikey;
this->mqtt.setCallback(mqttSubscribeCallback);
this->mqtt.setServer(server, port);
this->mqtt.setClient(client);
}
ThingplusClass Thingplus;
<commit_msg>Move string allcation memory from stack to flash<commit_after>/*
* Copyright (C) Daliworks, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <Arduino.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <Time.h>
#include "Thingplus.h"
#define THINGPLUS_VALUE_MESSAGE_LEN 36
#define THINGPLUS_TOPIC_LEN 80
#define THINGPLUS_SHORT_TOPIC_LEN 32
void serverTimeSync(const char *serverTimeMs) {
#define TIME_LENGTH 10
char serverTimeSec[TIME_LENGTH+1] = {0,};
strncpy(serverTimeSec, serverTimeMs, TIME_LENGTH);
int i;
time_t syncTime = 0;
for (i=0; i<TIME_LENGTH; i++)
syncTime = (10 * syncTime) + (serverTimeSec[i] - '0');
setTime(syncTime);
Serial.print(F("[INFO]Time Synced. NOW:"));
Serial.println(now());
}
void mqttSubscribeCallback(char *topic, uint8_t *payload, unsigned int length)
{
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject((char*)payload);
if (!root.success()) {
Serial.println(F("parseObject() failed"));
return;
}
const char *id = root["id"];
const char *method = root["method"];
Serial.print(F("Message subscribed. method:"));
Serial.println(method);
Serial.flush();
if (strcmp(method, "controlActuator") == 0) {
char *result = Thingplus._actuatorDo(root["params"]["id"], root["params"]["cmd"], root["params"]["options"]);
Thingplus._actuatorResultPublish(id, result);
}
else if (strcmp(method, "timeSync") == 0) {
serverTimeSync(root["params"]["time"]);
}
}
void ThingplusClass::_actuatorResultPublish(const char *messageId, char *result)
{
char responseTopic[THINGPLUS_SHORT_TOPIC_LEN] = {0,};
sprintf_P(responseTopic, PSTR("v/a/g/%s/res"), this->gatewayId);
char resposeMessage[64] = {0,};
if (result)
sprintf_P(resposeMessage, PSTR("{\"id\":\"%s\",\"result\":\"%s\"}"), messageId, result);
else
sprintf_P(resposeMessage, PSTR("{\"id\":\"%s\",\"error\": {\"code\": -32000}}"), messageId);
this->mqtt.publish(responseTopic, resposeMessage);
}
char *ThingplusClass::_actuatorDo(const char *id, const char *cmd, const char *options)
{
if (!this->actuatorCallback) {
return NULL;
}
return this->actuatorCallback(id, cmd, options);
}
void ThingplusClass::actuatorCallbackSet(char* (*cb)(const char* id, const char* cmd, const char* options))
{
this->actuatorCallback = cb;
}
bool ThingplusClass::valuePublish(const char *id, char *value)
{
char valuePublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf_P(valuePublishTopic, PSTR("v/a/g/%s/s/%s"), this->gatewayId, id);
char v[THINGPLUS_VALUE_MESSAGE_LEN] = {0,};
sprintf_P(v, PSTR("%ld000,%s"), now(), value);
return this->mqtt.publish(valuePublishTopic, v);
}
bool ThingplusClass::valuePublish(const char *id, float value)
{
char valuePublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf_P(valuePublishTopic, PSTR("v/a/g/%s/s/%s"), this->gatewayId, id);
char v[THINGPLUS_VALUE_MESSAGE_LEN] = {0,};
sprintf_P(v, PSTR("%ld000,"), now());
dtostrf(value, 5, 2, &v[strlen(v)]);
return this->mqtt.publish(valuePublishTopic, v);
}
bool ThingplusClass::valuePublish(const char *id, int value)
{
char valuePublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf_P(valuePublishTopic, PSTR("v/a/g/%s/s/%s"), this->gatewayId, id);
char v[THINGPLUS_VALUE_MESSAGE_LEN] = {0,};
sprintf_P(v, PSTR("%ld000,%d"), now(), value);
return this->mqtt.publish(valuePublishTopic, v);
}
bool ThingplusClass::statusPublish(const char *topic, bool on, time_t durationSec)
{
char status[16] = {0,};
sprintf_P(status, PSTR("%s,%ld000"), on ? "on" : "off", now() + durationSec);
return this->mqtt.publish(topic, status);
}
bool ThingplusClass::sensorStatusPublish(const char *id, bool on, time_t durationSec)
{
char statusPublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf_P(statusPublishTopic, PSTR("v/a/g/%s/s/%s/status"), this->gatewayId, id);
return this->statusPublish(statusPublishTopic, on, durationSec);
}
bool ThingplusClass::gatewayStatusPublish(bool on, time_t durationSec)
{
char statusPublishTopic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf_P(statusPublishTopic, PSTR("v/a/g/%s/status"), this->gatewayId);
return this->statusPublish(statusPublishTopic, on, durationSec);
}
bool ThingplusClass::mqttStatusPublish(bool on)
{
char topic[THINGPLUS_TOPIC_LEN] = {0,};
sprintf_P(topic, PSTR("v/a/g/%s/mqtt/status"), this->gatewayId);
const char *message = on ? "on" : "off";
return this->mqtt.publish(topic, message);
}
bool ThingplusClass::loop(void)
{
if (!this->mqtt.connected()) {
Serial.println(F("[ERR] MQTT disconnected"));
this->connect();
}
return this->mqtt.loop();
}
void ThingplusClass::connect(void)
{
#define MQTT_RETRY_INTERVAL_MS (5 * 1000)
bool ret;
char willTopic[32] = {0,};
sprintf_P(willTopic, PSTR("v/a/g/%s/mqtt/status"), this->gatewayId);
do
{
ret = this->mqtt.connect(this->gatewayId, this->gatewayId,
this->apikey, willTopic, 1, true, "err");
if (!ret) {
Serial.print(F("ERR: MQTT connection failed."));
int errCode = this->mqtt.state();
if (errCode == 5)
Serial.println(F(" APIKEY ERROR"));
else
Serial.println(this->mqtt.state());
Serial.println(F("ERR: Retry"));
delay(MQTT_RETRY_INTERVAL_MS);
}
} while(!this->mqtt.connected());
char subscribeTopic[32] = {0,};
sprintf_P(subscribeTopic, PSTR("v/a/g/%s/req"), this->gatewayId);
this->mqtt.subscribe(subscribeTopic);
this->mqttStatusPublish(true);
Serial.println(F("INFO: MQTT Connected"));
}
void ThingplusClass::disconnect(void)
{
this->mqtt.disconnect();
Serial.println(F("INFO: MQTT Disconnected"));
}
void ThingplusClass::begin(Client& client, byte mac[], const char *apikey)
{
const char *server = "dmqtt.thingplus.net";
const int port = 1883;
this->mac = mac;
sprintf_P(this->gatewayId, PSTR("%02x%02x%02x%02x%02x%02x"),
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
this->apikey = apikey;
this->mqtt.setCallback(mqttSubscribeCallback);
this->mqtt.setServer(server, port);
this->mqtt.setClient(client);
}
ThingplusClass Thingplus;
<|endoftext|> |
<commit_before><commit_msg>adding config numbers to apply MBW from 5 TeV Nch<commit_after><|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1700
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1104077 by johtaylo@johtaylo-JTBUILDER03-increment on 2014/12/10 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1701
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>#include <sstream>
#include <string>
#include <curl/curl.h>
#include "curl.h"
#include "logger.h"
namespace
{
static size_t curlWriteCallBack(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::ostringstream*)userp)->write((char*)contents, size * nmemb);
return size * nmemb;
}
}
namespace geecxx
{
std::string Curl::retrievePageTitle(const std::string& url)
{
CURL *curl;
CURLcode res;
std::ostringstream readBuffer;
std::string title = "";
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ::curlWriteCallBack);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res == CURLE_OK) {
//parsing
size_t pos = readBuffer.str().find("<title>") + 7;
size_t pos2 = readBuffer.str().find("</title>");
if (pos != std::string::npos && pos2 != std::string::npos) {
title = readBuffer.str().substr(pos, pos2 - pos);
}
} else {
title = std::string(curl_easy_strerror(res));
}
} else {
LOG_ERROR("Failed to allocate curl object.");
}
return title;
}
}
<commit_msg>Defaul title is "Untitled"<commit_after>#include <sstream>
#include <string>
#include <curl/curl.h>
#include "curl.h"
#include "logger.h"
namespace
{
static size_t curlWriteCallBack(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::ostringstream*)userp)->write((char*)contents, size * nmemb);
return size * nmemb;
}
}
namespace geecxx
{
std::string Curl::retrievePageTitle(const std::string& url)
{
CURL *curl;
CURLcode res;
std::ostringstream readBuffer;
std::string title = "Untitled";
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ::curlWriteCallBack);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if(res == CURLE_OK) {
//parsing
size_t pos = readBuffer.str().find("<title>") + 7;
size_t pos2 = readBuffer.str().find("</title>");
if (pos != std::string::npos && pos2 != std::string::npos) {
title = readBuffer.str().substr(pos, pos2 - pos);
}
} else {
title = std::string(curl_easy_strerror(res));
}
} else {
LOG_ERROR("Failed to allocate curl object.");
}
return title;
}
}
<|endoftext|> |
<commit_before>AliAnalysisTaskChargedJetsPA* AddTaskChargedJetsPA(
const char* containerSuffix = "",
Double_t jetRadius = 0.4,
const char* centralityType = "V0A",
Int_t trigger = AliVEvent::kINT7,
Bool_t isPA = kTRUE,
Bool_t isMC = kFALSE,
Bool_t doJetProfileAnalysis = kFALSE,
Bool_t doTrackcutAnalysis = kFALSE,
Bool_t doJetAnalysis = kTRUE,
const char* usedTracks = "PicoTracks",
Int_t numberOfCentralityBins = 20,
Double_t areaPercentage = 0.6,
Double_t ktJetRadius = 0.4,
Double_t trackBgrdConeR = 0.6,
Double_t minEta = -0.9,
Double_t maxEta = +0.9,
Double_t minJetEta = -0.5,
Double_t maxJetEta = +0.5,
Bool_t isEMCalTrain = kFALSE,
)
{
// #### Detect the demanded trigger with its readable name
TString triggerName(Form("Trigger_%i", trigger));
if (trigger == AliVEvent::kAnyINT)
triggerName = "kAnyINT";
else if (trigger == AliVEvent::kAny)
triggerName = "kAny";
else if(trigger == AliVEvent::kINT7)
triggerName = "kINT7";
else if(trigger == AliVEvent::kMB)
triggerName = "kMB";
else if(trigger == AliVEvent::kEMC7)
triggerName = "kEMC7";
else if(trigger == AliVEvent::kEMCEJE)
triggerName = "kEMCEJE";
else if(trigger == AliVEvent::kEMCEGA)
triggerName = "kEMCEGA";
// #### Define manager and data container names
AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
if (!manager) {
::Error("AddTaskChargedJetsPA", "No analysis manager to connect to.");
return NULL;
}
TString containerNameSuffix("");
if (strcmp(containerSuffix,""))
containerNameSuffix = Form("_%s", containerSuffix);
TString bgrdName("Background");
TString myContName("");
TString myContJPName("");
TString myContTCName("");
if(isMC)
{
myContName = Form("AnalysisR0%2.0f_%s_MC%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContJPName = Form("JetProfileR0%2.0f_%s_MC%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContTCName = Form("TrackcutsR0%2.0f_%s_MC%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
}
else
{
myContName = Form("AnalysisR0%2.0f_%s%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContJPName = Form("JetProfileR0%2.0f_%s%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContTCName = Form("TrackcutsR0%2.0f_%s%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
}
if(doJetAnalysis)
{
// #### Add necessary jet finder tasks
gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C");
AliEmcalJetTask* jetFinderTask = AddTaskEmcalJet(usedTracks,"",1,jetRadius,1,0.150,0.300); // anti-kt
AliEmcalJetTask* jetFinderTaskKT = AddTaskEmcalJet(usedTracks,"",0,ktJetRadius,1,0.150,0.300); // kt
// #### Define external rho task
AliEmcalJetTask* jetFinderRho = AddTaskEmcalJet(usedTracks,"",1,0.4,1,0.150,0.300); // anti-kt
AliEmcalJetTask* jetFinderRhoKT = AddTaskEmcalJet(usedTracks,"",0,0.4,1,0.150,0.300); // kt
gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskRhoSparse.C");
AliAnalysisTaskRhoSparse* rhotask = AddTaskRhoSparse(jetFinderRhoKT->GetName(), NULL, usedTracks, "", bgrdName.Data(), 0.4,"TPC", 0., 5., 0, 0,2,kFALSE,bgrdName.Data(),kTRUE);
}
// #### Define analysis task
AliAnalysisTaskChargedJetsPA *task = NULL;
AliAnalysisDataContainer* contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJets", AliAnalysisManager::GetCommonFileName()));
if(doJetProfileAnalysis)
AliAnalysisDataContainer* contJetProfile = manager->CreateContainer(myContJPName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJets", AliAnalysisManager::GetCommonFileName()));
if(doTrackcutAnalysis)
AliAnalysisDataContainer* contTrackcuts = manager->CreateContainer(myContTCName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJets", AliAnalysisManager::GetCommonFileName()));
if(doJetAnalysis)
{
task = new AliAnalysisTaskChargedJetsPA(Form("AnalysisPA_%s_%s", jetFinderTask->GetName(), triggerName.Data()), usedTracks, jetFinderTask->GetName(),jetFinderTaskKT->GetName(), doJetProfileAnalysis, doTrackcutAnalysis);
task->SetExternalRhoTaskName(bgrdName.Data());
}
else
task = new AliAnalysisTaskChargedJetsPA(Form("AnalysisPA_%s_%s", "", triggerName.Data()), usedTracks, "","", doJetProfileAnalysis, doTrackcutAnalysis);
// #### Task preferences
task->SetIsPA(isPA);
task->SetAnalyzeJetProfile(doJetProfileAnalysis);
task->SetAnalyzeTrackcuts(doTrackcutAnalysis);
task->SetAcceptanceEta(minEta,maxEta);
task->SetAcceptanceJetEta(minJetEta,maxJetEta);
task->SetSignalJetRadius(jetRadius);
task->SetBackgroundJetRadius(jetRadius);
task->SetSignalJetMinArea(areaPercentage*jetRadius*jetRadius*TMath::Pi());
task->SetRandConeRadius(jetRadius);
task->SelectCollisionCandidates(trigger);
task->SetCentralityType(centralityType);
task->SetNumberOfCentralityBins(numberOfCentralityBins);
task->SetDoJetAnalysis(doJetAnalysis);
// #### Add analysis task
manager->AddTask(task);
manager->ConnectInput(task, 0, manager->GetCommonInputContainer());
manager->ConnectOutput(task, 1, contHistos);
if(doJetProfileAnalysis)
{
manager->ConnectOutput(task, 2, contJetProfile);
}
if(doTrackcutAnalysis && !doJetProfileAnalysis)
{
manager->ConnectOutput(task, 2, contTrackcuts);
}
else if(doTrackcutAnalysis && doJetProfileAnalysis)
{
manager->ConnectOutput(task, 3, contTrackcuts);
}
if(isEMCalTrain)
RequestMemory(task,200*1024);
return task;
}
<commit_msg>Charged jets (pPb): Small fix<commit_after>AliAnalysisTaskChargedJetsPA* AddTaskChargedJetsPA(
const char* containerSuffix = "",
Double_t jetRadius = 0.4,
const char* centralityType = "V0A",
Int_t trigger = AliVEvent::kINT7,
Bool_t isPA = kTRUE,
Bool_t isMC = kFALSE,
Bool_t doJetProfileAnalysis = kFALSE,
Bool_t doTrackcutAnalysis = kFALSE,
Bool_t doJetAnalysis = kTRUE,
const char* usedTracks = "PicoTracks",
Int_t numberOfCentralityBins = 20,
Double_t areaPercentage = 0.6,
Double_t ktJetRadius = 0.4,
Double_t trackBgrdConeR = 0.6,
Double_t minEta = -0.9,
Double_t maxEta = +0.9,
Double_t minJetEta = -0.5,
Double_t maxJetEta = +0.5,
Bool_t isEMCalTrain = kFALSE,
)
{
// #### Detect the demanded trigger with its readable name
TString triggerName(Form("Trigger_%i", trigger));
if (trigger == AliVEvent::kAnyINT)
triggerName = "kAnyINT";
else if (trigger == AliVEvent::kAny)
triggerName = "kAny";
else if(trigger == AliVEvent::kINT7)
triggerName = "kINT7";
else if(trigger == AliVEvent::kMB)
triggerName = "kMB";
else if(trigger == AliVEvent::kEMC7)
triggerName = "kEMC7";
else if(trigger == AliVEvent::kEMCEJE)
triggerName = "kEMCEJE";
else if(trigger == AliVEvent::kEMCEGA)
triggerName = "kEMCEGA";
// #### Define manager and data container names
AliAnalysisManager *manager = AliAnalysisManager::GetAnalysisManager();
if (!manager) {
::Error("AddTaskChargedJetsPA", "No analysis manager to connect to.");
return NULL;
}
TString containerNameSuffix("");
if (strcmp(containerSuffix,""))
containerNameSuffix = Form("_%s", containerSuffix);
TString bgrdName("Background");
TString myContName("");
TString myContJPName("");
TString myContTCName("");
if(isMC)
{
bgrdName = "BackgroundMC";
myContName = Form("AnalysisR0%2.0f_%s_MC%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContJPName = Form("JetProfileR0%2.0f_%s_MC%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContTCName = Form("TrackcutsR0%2.0f_%s_MC%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
}
else
{
bgrdName = "Background";
myContName = Form("AnalysisR0%2.0f_%s%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContJPName = Form("JetProfileR0%2.0f_%s%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
myContTCName = Form("TrackcutsR0%2.0f_%s%s", jetRadius*100, triggerName.Data(), containerNameSuffix.Data());
}
if(doJetAnalysis)
{
// #### Add necessary jet finder tasks
gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskEmcalJet.C");
AliEmcalJetTask* jetFinderTask = AddTaskEmcalJet(usedTracks,"",1,jetRadius,1,0.150,0.300); // anti-kt
AliEmcalJetTask* jetFinderTaskKT = AddTaskEmcalJet(usedTracks,"",0,ktJetRadius,1,0.150,0.300); // kt
// #### Define external rho task
AliEmcalJetTask* jetFinderRho = AddTaskEmcalJet(usedTracks,"",1,0.4,1,0.150,0.300); // anti-kt
AliEmcalJetTask* jetFinderRhoKT = AddTaskEmcalJet(usedTracks,"",0,0.4,1,0.150,0.300); // kt
gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskRhoSparse.C");
AliAnalysisTaskRhoSparse* rhotask = AddTaskRhoSparse(jetFinderRhoKT->GetName(), NULL, usedTracks, "", bgrdName.Data(), 0.4,"TPC", 0., 5., 0, 0,2,kFALSE,bgrdName.Data(),kTRUE);
}
// #### Define analysis task
AliAnalysisTaskChargedJetsPA *task = NULL;
AliAnalysisDataContainer* contHistos = manager->CreateContainer(myContName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJets", AliAnalysisManager::GetCommonFileName()));
if(doJetProfileAnalysis)
AliAnalysisDataContainer* contJetProfile = manager->CreateContainer(myContJPName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJets", AliAnalysisManager::GetCommonFileName()));
if(doTrackcutAnalysis)
AliAnalysisDataContainer* contTrackcuts = manager->CreateContainer(myContTCName.Data(), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:ChargedJets", AliAnalysisManager::GetCommonFileName()));
if(doJetAnalysis)
{
task = new AliAnalysisTaskChargedJetsPA(Form("AnalysisPA_%s_%s", jetFinderTask->GetName(), triggerName.Data()), usedTracks, jetFinderTask->GetName(),jetFinderTaskKT->GetName(), doJetProfileAnalysis, doTrackcutAnalysis);
task->SetExternalRhoTaskName(bgrdName.Data());
}
else
task = new AliAnalysisTaskChargedJetsPA(Form("AnalysisPA_%s_%s", "", triggerName.Data()), usedTracks, "","", doJetProfileAnalysis, doTrackcutAnalysis);
// #### Task preferences
task->SetIsPA(isPA);
task->SetAnalyzeJetProfile(doJetProfileAnalysis);
task->SetAnalyzeTrackcuts(doTrackcutAnalysis);
task->SetAcceptanceEta(minEta,maxEta);
task->SetAcceptanceJetEta(minJetEta,maxJetEta);
task->SetSignalJetRadius(jetRadius);
task->SetBackgroundJetRadius(jetRadius);
task->SetSignalJetMinArea(areaPercentage*jetRadius*jetRadius*TMath::Pi());
task->SetRandConeRadius(jetRadius);
task->SelectCollisionCandidates(trigger);
task->SetCentralityType(centralityType);
task->SetNumberOfCentralityBins(numberOfCentralityBins);
task->SetDoJetAnalysis(doJetAnalysis);
// #### Add analysis task
manager->AddTask(task);
manager->ConnectInput(task, 0, manager->GetCommonInputContainer());
manager->ConnectOutput(task, 1, contHistos);
if(doJetProfileAnalysis)
{
manager->ConnectOutput(task, 2, contJetProfile);
}
if(doTrackcutAnalysis && !doJetProfileAnalysis)
{
manager->ConnectOutput(task, 2, contTrackcuts);
}
else if(doTrackcutAnalysis && doJetProfileAnalysis)
{
manager->ConnectOutput(task, 3, contTrackcuts);
}
if(isEMCalTrain)
RequestMemory(task,200*1024);
return task;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2744
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1610187 by chui@ocl-promo-incrementor on 2018/09/25 02:56:08<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2745
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cstring>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
/// Normalizes path removing relative subpaths such as "." and "..".
/// Path delimiter is slash "/".
///
/// Note 1: consecutive delimiters are treated as one (same way as Linux does).
/// Example: "///" -> "/", "///bar////foo//" -> "/bar/foo/"
///
/// Note 2: trailing slash is kept as in input string: if input string has
/// trailing slash output will have too. If input doesn't output will not add it.
/// (Just like in assignment examples).
/// Example: "/bar" -> "/bar", "/bar/" -> "/bar/"
///
/// Note 3: no domain name detection implemented (that's not actually possible
/// with proposed function interface as local domain name cannot be distinguished
/// from folder name). Otherwise it's assumed that if path doesn't start with
/// "/", "./" or "../" than first subfolder is domain-like and it's considered
/// virtual root.
/// Example: "bar/../foo" -> "bar/foo", "/bar/../foo" -> "/foo"
std::string normalize(const std::string& path)
{
constexpr char delimiter = '/';
constexpr char rel_point = '.';
struct folder
{
folder(size_t b, size_t s): begin(b), size(s) {}
size_t begin;
size_t size;
};
// Possible optimization: assume that path length cannot be > PATH_MAX
// (typically 4096 on most Linux systems). So vector can be replaced with
// local array of 2049 elements, avoiding memory allocation/deallocation
// and making data context more local and cache-friendly.
std::vector<folder> folders;
// Number of subfolders is no more than path length / 2 + 1.
folders.reserve(path.size() / 2 + 1);
size_t root_idx = 0;
const char* const cpath = path.c_str();
const size_t size = path.size();
const char* const cend = cpath + size;
const char* cur_pos = cpath;
const char* prev_pos = cpath;
const auto add_folder =
[cpath, cend, size, &folders, &root_idx, &cur_pos, &prev_pos](const char* pos)
{
const size_t len = pos - prev_pos;
if (len == 0 ||
(len == 1 && *(pos - 1) == rel_point) ||
(len == 2 && *(pos - 1) == rel_point && *(pos - 2) == delimiter))
{
// Skip "", ".", "/." as empty subfolders
}
else if ((len == 2 && *(pos - 1) == rel_point && *(pos - 2) == rel_point) ||
(len == 3 && *(pos - 1) == rel_point && *(pos - 2) == rel_point &&
*(pos - 3) == delimiter))
{
// Remove previous subfolder for ".." and "/.." till reaching the root.
if (folders.size() > root_idx) folders.pop_back();
}
else
{
// Norm subfolder, add it.
folders.emplace_back(prev_pos - cpath, pos - prev_pos);
// Subfolder starts from string beginning but doesn't start with "/".
// Hmmm, guess it's domain name and new root. Don't harass it by upcoming "..".
if (prev_pos == cpath && *cpath != delimiter) root_idx = 1;
}
cur_pos = pos + 1;
// Skip adjacent path delimiters ('////' -> '/')
while (cur_pos < cend && *cur_pos == delimiter) ++cur_pos;
prev_pos = cur_pos - 1;
};
while (auto pos = std::strchr(cur_pos, delimiter))
{
add_folder(pos);
}
// Process last subfolder separately.
add_folder(cend);
std::string result;
result.reserve(size);
for (const auto& f : folders)
{
result.append(cpath + f.begin, f.size);
}
return result;
}
static int tests_failed = 0;
/// Simple unit testing function.
void test(const std::string& input, const std::string& expected)
{
const auto quote = [](const auto& str)
{
return "\'" + str + "\'";
};
const auto output = normalize(input);
const bool ok = output == expected;
if (!ok) ++tests_failed;
std::cout
<< (ok ? "OK" : "FAIL (expected " + quote(expected) + ")")
<< " - "
<< quote(input) << " -> " << quote(output)
<< std::endl;
}
std::string generate_path(size_t seed, size_t max_len)
{
std::string s;
while (s.size() < max_len)
{
if (seed % 2 == 0) s += "/";
if (seed % 3 == 0) s += "bar";
if (seed % 4 == 0) s += "foo";
if (seed % 5 == 0) s += "baz";
if (seed % 6 == 0) s += "/../";
if (seed % 7 == 0) s += "/./";
if (seed % 8 == 0) s += "/./../";
if (seed % 9 == 0) s += "/.././";
++seed;
}
return s;
}
void performance_test()
{
constexpr size_t max_count = 100000;
constexpr size_t max_path_size = 4096;
std::cout << "Starting performance test, please wait..." << std::endl;
std::cout << "Loop count - " << max_count << std::endl;
std::cout << "Path size - " << max_path_size << std::endl;
std::vector<std::string> test;
test.reserve(max_count);
double total_size = 0;
for (size_t i = 0; i < max_count; ++i)
{
test.push_back(generate_path(time(nullptr), max_path_size));
total_size += test.back().size();
}
// Warm-up pass.
for (volatile size_t i = 0; i < max_count; ++i)
{
volatile auto s = normalize(test[i]);
}
// Measure pass.
using namespace std::chrono;
const auto start = high_resolution_clock::now();
for (volatile size_t i = 0; i < max_count; ++i)
{
volatile auto s = normalize(test[i]);
}
const auto end = high_resolution_clock::now();
const duration<double, std::micro> total_time_us(end - start);
std::cout << std::fixed << std::setprecision(2);
std::cout << "Total duration " << total_time_us.count() << " us" << std::endl;
std::cout << "Average single call duration " << (total_time_us.count() / max_count) << " us" << std::endl;
const auto duration_sec = total_time_us.count() / 1E6;
const auto total_size_mb = total_size / 1E6;
std::cout << "Average throughput " << (total_size_mb / duration_sec) << " MB/s" << std::endl;
}
int main()
{
test("../bar", "/bar");
test("/foo/bar", "/foo/bar");
test("/foo/bar/../baz", "/foo/baz");
test("/foo/bar/./baz/", "/foo/bar/baz/");
test("/foo/../../baz", "/baz");
test("", "");
test("/", "/");
test("///", "/");
test("/../.", "");
test("/.././", "/");
test("./.././bee", "/bee");
test("/foo/bar", "/foo/bar");
test("foo/bar/", "foo/bar/");
test("foo////bar///", "foo/bar/");
test("../bar/../bor/foo", "/bor/foo");
test("..", "");
test(".", "");
test("../bar", "/bar");
test("./bar/././", "/bar/");
test("/bar/foo/bor/../../..", "");
test("/bar/foo/bor/../../../", "/");
test("/bar/foo/bor////../../../", "/");
test("domain.com/../foo", "domain.com/foo");
test("domain.com/./../foo/../bb/./../../../././skip_me/./../cool/./././", "domain.com/cool/");
test("domain.com/./../foo/../bb/./../../../././skip_me/./../cool/./././../more_cool", "domain.com/more_cool");
test("/domain.com/./../foo/../bb/./../../../././skip_me/./../cool/./././../still_cool", "/still_cool");
test("domain.com/.../foo", "domain.com/.../foo"); // Sorry, garbage in - garbage out
test(".../domain.com/.../foo", ".../domain.com/.../foo"); // Sorry, garbage in - garbage out
performance_test();
return tests_failed;
}
<commit_msg>Make perf test strings more random.<commit_after>#include <cstdlib>
#include <cstring>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
/// Normalizes path removing relative subpaths such as "." and "..".
/// Path delimiter is slash "/".
///
/// Note 1: consecutive delimiters are treated as one (same way as Linux does).
/// Example: "///" -> "/", "///bar////foo//" -> "/bar/foo/"
///
/// Note 2: trailing slash is kept as in input string: if input string has
/// trailing slash output will have too. If input doesn't output will not add it.
/// (Just like in assignment examples).
/// Example: "/bar" -> "/bar", "/bar/" -> "/bar/"
///
/// Note 3: no domain name detection implemented (that's not actually possible
/// with proposed function interface as local domain name cannot be distinguished
/// from folder name). Otherwise it's assumed that if path doesn't start with
/// "/", "./" or "../" than first subfolder is domain-like and it's considered
/// virtual root.
/// Example: "bar/../foo" -> "bar/foo", "/bar/../foo" -> "/foo"
std::string normalize(const std::string& path)
{
constexpr char delimiter = '/';
constexpr char rel_point = '.';
struct folder
{
folder(size_t b, size_t s): begin(b), size(s) {}
size_t begin;
size_t size;
};
// Possible optimization: assume that path length cannot be > PATH_MAX
// (typically 4096 on most Linux systems). So vector can be replaced with
// local array of 2049 elements, avoiding memory allocation/deallocation
// and making data context more local and cache-friendly.
std::vector<folder> folders;
// Number of subfolders is no more than path length / 2 + 1.
folders.reserve(path.size() / 2 + 1);
size_t root_idx = 0;
const char* const cpath = path.c_str();
const size_t size = path.size();
const char* const cend = cpath + size;
const char* cur_pos = cpath;
const char* prev_pos = cpath;
const auto add_folder =
[cpath, cend, size, &folders, &root_idx, &cur_pos, &prev_pos](const char* pos)
{
const size_t len = pos - prev_pos;
if (len == 0 ||
(len == 1 && *(pos - 1) == rel_point) ||
(len == 2 && *(pos - 1) == rel_point && *(pos - 2) == delimiter))
{
// Skip "", ".", "/." as empty subfolders
}
else if ((len == 2 && *(pos - 1) == rel_point && *(pos - 2) == rel_point) ||
(len == 3 && *(pos - 1) == rel_point && *(pos - 2) == rel_point &&
*(pos - 3) == delimiter))
{
// Remove previous subfolder for ".." and "/.." till reaching the root.
if (folders.size() > root_idx) folders.pop_back();
}
else
{
// Norm subfolder, add it.
folders.emplace_back(prev_pos - cpath, pos - prev_pos);
// Subfolder starts from string beginning but doesn't start with "/".
// Hmmm, guess it's domain name and new root. Don't harass it by upcoming "..".
if (prev_pos == cpath && *cpath != delimiter) root_idx = 1;
}
cur_pos = pos + 1;
// Skip adjacent path delimiters ('////' -> '/')
while (cur_pos < cend && *cur_pos == delimiter) ++cur_pos;
prev_pos = cur_pos - 1;
};
while (auto pos = std::strchr(cur_pos, delimiter))
{
add_folder(pos);
}
// Process last subfolder separately.
add_folder(cend);
std::string result;
result.reserve(size);
for (const auto& f : folders)
{
result.append(cpath + f.begin, f.size);
}
return result;
}
static int tests_failed = 0;
/// Simple unit testing function.
void test(const std::string& input, const std::string& expected)
{
const auto quote = [](const auto& str)
{
return "\'" + str + "\'";
};
const auto output = normalize(input);
const bool ok = output == expected;
if (!ok) ++tests_failed;
std::cout
<< (ok ? "OK" : "FAIL (expected " + quote(expected) + ")")
<< " - "
<< quote(input) << " -> " << quote(output)
<< std::endl;
}
std::string generate_path(size_t seed, size_t max_len)
{
std::string s;
while (s.size() < max_len)
{
if (seed % 2 == 0) s += "/";
if (seed % 3 == 0) s += "bar";
if (seed % 4 == 0) s += "foo";
if (seed % 5 == 0) s += "baz";
if (seed % 6 == 0) s += "/../";
if (seed % 7 == 0) s += "/./";
if (seed % 8 == 0) s += "/./../";
if (seed % 9 == 0) s += "/.././";
++seed;
}
return s;
}
void performance_test()
{
constexpr size_t max_count = 100000;
constexpr size_t max_path_size = 4096;
std::cout << "Starting performance test, please wait..." << std::endl;
std::cout << "Loop count - " << max_count << std::endl;
std::cout << "Path size - " << max_path_size << std::endl;
std::vector<std::string> test;
test.reserve(max_count);
std::srand(std::time(nullptr));
double total_size = 0;
for (size_t i = 0; i < max_count; ++i)
{
test.push_back(generate_path(std::rand(), max_path_size));
total_size += test.back().size();
}
// Warm-up pass.
for (volatile size_t i = 0; i < max_count; ++i)
{
volatile auto s = normalize(test[i]);
}
// Measure pass.
using namespace std::chrono;
const auto start = high_resolution_clock::now();
for (volatile size_t i = 0; i < max_count; ++i)
{
volatile auto s = normalize(test[i]);
}
const auto end = high_resolution_clock::now();
const duration<double, std::micro> total_time_us(end - start);
std::cout << std::fixed << std::setprecision(2);
std::cout << "Total duration " << total_time_us.count() << " us" << std::endl;
std::cout << "Average single call duration " << (total_time_us.count() / max_count) << " us" << std::endl;
const auto duration_sec = total_time_us.count() / 1E6;
const auto total_size_mb = total_size / 1E6;
std::cout << "Average throughput " << (total_size_mb / duration_sec) << " MB/s" << std::endl;
}
int main()
{
test("../bar", "/bar");
test("/foo/bar", "/foo/bar");
test("/foo/bar/../baz", "/foo/baz");
test("/foo/bar/./baz/", "/foo/bar/baz/");
test("/foo/../../baz", "/baz");
test("", "");
test("/", "/");
test("///", "/");
test("/../.", "");
test("/.././", "/");
test("./.././bee", "/bee");
test("/foo/bar", "/foo/bar");
test("foo/bar/", "foo/bar/");
test("foo////bar///", "foo/bar/");
test("../bar/../bor/foo", "/bor/foo");
test("..", "");
test(".", "");
test("../bar", "/bar");
test("./bar/././", "/bar/");
test("/bar/foo/bor/../../..", "");
test("/bar/foo/bor/../../../", "/");
test("/bar/foo/bor////../../../", "/");
test("domain.com/../foo", "domain.com/foo");
test("domain.com/./../foo/../bb/./../../../././skip_me/./../cool/./././", "domain.com/cool/");
test("domain.com/./../foo/../bb/./../../../././skip_me/./../cool/./././../more_cool", "domain.com/more_cool");
test("/domain.com/./../foo/../bb/./../../../././skip_me/./../cool/./././../still_cool", "/still_cool");
test("domain.com/.../foo", "domain.com/.../foo"); // Sorry, garbage in - garbage out
test(".../domain.com/.../foo", ".../domain.com/.../foo"); // Sorry, garbage in - garbage out
performance_test();
return tests_failed;
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
class bstNode
{
private:
int data;
bstNode *left;
bstNode *right;
public:
bstNode* Insert (bstNode*,int);
bool Search (bstNode*,int);
void preorder (bstNode*);
void inorder (bstNode*);
void postorder (bstNode*);
void levelorder (bstNode*);
int countLeaves (bstNode*,int);
bstNode* Copy (bstNode*);
int findMin (bstNode*);
int findMax (bstNode*);
int max (int,int);
int height (bstNode*);
bstNode* insertNode (bstNode*,int);
bstNode* deleteNode (bstNode*,int);
int compare (bstNode* , bstNode*);
bool printAncestors(bstNode*,int);
bstNode* printParent(bstNode*,int,bstNode*);
bool isMirror(bstNode*,bstNode*);
};
bstNode* bstNode::Insert (bstNode *root, int item)
{
bstNode* newNode = new bstNode();
newNode->data = item;
newNode->left = NULL;
newNode->right = NULL;
if(root == NULL)
{
root = newNode;
}
else if(item <= root->data)
{
root->left = Insert(root->left,item);
}
else if(item > root->data)
{
root->right = Insert(root->right,item);
}
return root;
}
bool bstNode::Search(bstNode *root,int item)
{
if(root == NULL)
return false;
if(item == root->data)
return true;
if(item <= root->data)
{
return Search(root->left,item);
}
if(item > root->data)
{
return Search(root->right,item);
}
}
void bstNode::preorder(bstNode* root)
{
if(root != NULL)
{
cout<<root->data<<"\t";
preorder(root->left);
preorder(root->right);
}
}
void bstNode::inorder(bstNode *root)
{
if(root == NULL)
return;
inorder(root->left);
cout<<root->data<<"\t";
inorder(root->right);
}
void bstNode::postorder(bstNode* root)
{
if(root != NULL)
{
postorder(root->left);
cout<<root->data<<"\t";
postorder(root->right);
}
}
void bstNode::levelorder(bstNode* root)
{
bstNode* arr[50] = {NULL};
int front=0;
int rear=0;
while(root != NULL)
{
cout<<root->data<<"\t";
if(root->left)
arr[rear++] = root->left;
if(root->right)
arr[rear++] = root->right;
root = arr[front++];
}
}
int bstNode::countLeaves(bstNode* root,int count)
{
if(root != NULL)
{
count = countLeaves(root->left,count);
if((root->left == NULL) && (root->right == NULL))
count++;
count = countLeaves(root->right,count);
}
return count;
}
bstNode* bstNode::Copy (bstNode* root)
{
bstNode *newRoot = new bstNode();
if(root == NULL)
return NULL;
newRoot->data = root->data;
newRoot->left = Copy(root->left);
newRoot->right = Copy(root->right);
return newRoot;
}
int bstNode::findMin (bstNode *root)
{
if(root == NULL)
{
cout<<"Empty Tree!"<<endl;
return -1;
}
while(root->left != NULL)
{
root = root->left;
}
return root->data;
}
int bstNode::findMax (bstNode *root)
{
if(root == NULL)
{
cout<<"Empty Tree!"<<endl;
return -1;
}
while(root->right != NULL)
{
root = root->right;
}
return root->data;
}
int bstNode::max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}
int bstNode::height(bstNode* root)
{
if(root == NULL)
return -1;
else
return (max(height(root->left),height(root->right))+1);
}
bstNode* bstNode::insertNode (bstNode* root,int data)
{
bstNode* newNode = new bstNode();
newNode->data = data;
if(root == NULL)
return newNode;
if(data < root->data)
root->left = insertNode(root->left,data);
else if(data > root->data)
root->right = insertNode(root->right,data);
return root;
}
bstNode* bstNode::deleteNode (bstNode* root,int data)
{
if(root == NULL)
return root;
else if(data < root->data)
root->left = deleteNode(root->left,data);
else if(data >root->data)
root->right = deleteNode(root->right,data);
else
{
//Case 1: No child
if(root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
}
//Case 2: 1 child
else if(root->left == NULL)
{
bstNode *temp = root;
root = root->right;
delete temp;
}
else if(root->right == NULL)
{
bstNode *temp = root;
root = root->left;
delete temp;
}
//Case 3: 2 children
else
{
root->data = findMin(root->right);
root->right = deleteNode(root->right,data);
}
}
return root;
}
int bstNode::compare (bstNode* root1, bstNode* root2)
{
if(root1 == NULL && root2 == NULL)
return 1;
else if(root1 == NULL || root2 == NULL)
return 0;
else if(root1->data == root2->data)
{
int p = compare(root1->left,root2->left);
int q = compare(root1->right,root2->right);
return p*q;
}
else
return 0;
}
bool bstNode::printAncestors(bstNode* root,int key)
{
if(root==NULL)
return false;
if(root->data==key)
return true;
if(printAncestors(root->left,key)||printAncestors(root->right,key))
{
cout<<root->data<<"\t";
return true;
}
return false;
}
bstNode* bstNode::printParent(bstNode* cur,int key,bstNode* prev)
{
if(cur==NULL)
return NULL;
printParent(cur->left,key,cur);
if(key==cur->data)
{
cout<<prev->data<<endl;
return prev;
}
printParent(cur->right,key,cur);
return NULL;
}
bool bstNode::isMirror(bstNode* root1,bstNode* root2)
{
if(root1==NULL && root2==NULL)
return true;
if(root1==NULL || root2==NULL)
return false;
return ((root1->data == root2->data) && isMirror(root1->left,root2->right) && isMirror(root1->right,root2->left));
}
int main()
{
bstNode n1;
bstNode *root = NULL;
int n;
cout<<"Enter the number of elements you want to enter"<<endl;
cin>>n;
int val;
for(int i=0;i<n;i++)
{
cout<<"Enter the item to insert"<<endl;
cin>>val;
root = n1.Insert(root,val);
}
cout<<"Preorder scheme of the tree:\n";
n1.preorder(root);
cout<<endl;
cout<<"Inorder scheme of the tree:\n";
n1.inorder(root);
cout<<endl;
cout<<"Postorder scheme of the tree:\n";
n1.postorder(root);
cout<<endl;
cout<<"Levelorder scheme of the tree:\n";
n1.levelorder(root);
cout<<endl;
// val=0;
// cout<<"Number of leaf nodes in the tree = "<<n1.countLeaves(root,val)<<endl;
bstNode* newRoot = n1.Copy(root);
// cout<<"Copy of the tree:(Preorder scheme)\n";
// n1.preorder(newRoot);
// cout<<endl;
// cout<<"Minimum element in the tree: "<<n1.findMin(root)<<endl;
// cout<<"Maximum element in the tree: "<<n1.findMax(root)<<endl;
// cout<<"Height of the tree is: "<<n1.height(root)<<endl;
// cout<<"Enter the value of the node to be created"<<endl;
// cin>>val;
// root = n1.insertNode(root,val);
// cout<<"Inorder scheme of the tree after node insertion\n";
// n1.inorder(root);
// cout<<endl;
// cout<<"Enter the node to be deleted\n";
// cin>>val;
// n1.deleteNode(root,val);
// cout<<"Inorder scheme of the tree after node deletion\n";
// n1.inorder(root);
// cout<<endl;
// cout<<"Comparison of two trees: \n";
// if(n1.compare(root,newRoot) == 1)
// cout<<"Trees are same!\n";
// else
// cout<<"Trees are different!\n";
// cout<<"Enter the element to be searched\n";
// cin>>val;
// if(n1.Search(root,val) == true)
// cout<<"Element found!\n";
// else
// cout<<"Element not found!\n";
cout<<"Enter the node whose ancestors are to be printed\n";
cin>>val;
n1.printAncestors(root,val);
cout<<endl;
cout<<"Enter the node whose parent is to be printed\n";
cin>>val;
cout<<"Parent of the entered node:\n";
n1.printParent(root,val,NULL);
cout<<"Checking for mirror image:\n";
if(n1.isMirror(root,newRoot))
{
cout<<"The two trees are mirror images of each other\n";
}
else
{
cout<<"The two trees are not mirror images of each other\n";
}
return 0;
}<commit_msg>Some changes<commit_after>#include <iostream>
using namespace std;
class bstNode
{
private:
int data;
bstNode *left;
bstNode *right;
public:
bstNode* Insert (bstNode*,int);
bool Search (bstNode*,int);
void preorder (bstNode*);
void inorder (bstNode*);
void postorder (bstNode*);
void levelorder (bstNode*);
int countLeaves (bstNode*,int);
bstNode* Copy (bstNode*);
int findMin (bstNode*);
int findMax (bstNode*);
int max (int,int);
int height (bstNode*);
bstNode* insertNode (bstNode*,int);
bstNode* deleteNode (bstNode*,int);
int compare (bstNode* , bstNode*);
bool printAncestors(bstNode*,int);
bstNode* printParent(bstNode*,int,bstNode*);
bool isMirror(bstNode*,bstNode*);
};
bstNode* bstNode::Insert (bstNode *root, int item)
{
bstNode* newNode = new bstNode();
newNode->data = item;
newNode->left = NULL;
newNode->right = NULL;
if(root == NULL)
{
root = newNode;
}
else if(item <= root->data)
{
root->left = Insert(root->left,item);
}
else if(item > root->data)
{
root->right = Insert(root->right,item);
}
return root;
}
bool bstNode::Search(bstNode *root,int item)
{
if(root == NULL)
return false;
if(item == root->data)
return true;
if(item <= root->data)
{
return Search(root->left,item);
}
if(item > root->data)
{
return Search(root->right,item);
}
}
void bstNode::preorder(bstNode* root)
{
if(root != NULL)
{
cout<<root->data<<"\t";
preorder(root->left);
preorder(root->right);
}
}
void bstNode::inorder(bstNode *root)
{
if(root == NULL)
return;
inorder(root->left);
cout<<root->data<<"\t";
inorder(root->right);
}
void bstNode::postorder(bstNode* root)
{
if(root != NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data<<"\t";
}
}
void bstNode::levelorder(bstNode* root)
{
bstNode* arr[50] = {NULL};
int front=0;
int rear=0;
while(root != NULL)
{
cout<<root->data<<"\t";
if(root->left)
arr[rear++] = root->left;
if(root->right)
arr[rear++] = root->right;
root = arr[front++];
}
}
int bstNode::countLeaves(bstNode* root,int count)
{
if(root != NULL)
{
count = countLeaves(root->left,count);
if((root->left == NULL) && (root->right == NULL))
count++;
count = countLeaves(root->right,count);
}
return count;
}
bstNode* bstNode::Copy (bstNode* root)
{
bstNode *newRoot = new bstNode();
if(root == NULL)
return NULL;
newRoot->data = root->data;
newRoot->left = Copy(root->left);
newRoot->right = Copy(root->right);
return newRoot;
}
int bstNode::findMin (bstNode *root)
{
if(root == NULL)
{
cout<<"Empty Tree!"<<endl;
return -1;
}
while(root->left != NULL)
{
root = root->left;
}
return root->data;
}
int bstNode::findMax (bstNode *root)
{
if(root == NULL)
{
cout<<"Empty Tree!"<<endl;
return -1;
}
while(root->right != NULL)
{
root = root->right;
}
return root->data;
}
int bstNode::max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}
int bstNode::height(bstNode* root)
{
if(root == NULL)
return -1;
else
return (max(height(root->left),height(root->right))+1);
}
bstNode* bstNode::insertNode (bstNode* root,int data)
{
bstNode* newNode = new bstNode();
newNode->data = data;
if(root == NULL)
return newNode;
if(data < root->data)
root->left = insertNode(root->left,data);
else if(data > root->data)
root->right = insertNode(root->right,data);
return root;
}
bstNode* bstNode::deleteNode (bstNode* root,int data)
{
if(root == NULL)
return root;
else if(data < root->data)
root->left = deleteNode(root->left,data);
else if(data >root->data)
root->right = deleteNode(root->right,data);
else
{
//Case 1: No child
if(root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
}
//Case 2: 1 child
else if(root->left == NULL)
{
bstNode *temp = root;
root = root->right;
delete temp;
}
else if(root->right == NULL)
{
bstNode *temp = root;
root = root->left;
delete temp;
}
//Case 3: 2 children
else
{
root->data = findMin(root->right);
root->right = deleteNode(root->right,data);
}
}
return root;
}
int bstNode::compare (bstNode* root1, bstNode* root2)
{
if(root1 == NULL && root2 == NULL)
return 1;
else if(root1 == NULL || root2 == NULL)
return 0;
else if(root1->data == root2->data)
{
int p = compare(root1->left,root2->left);
int q = compare(root1->right,root2->right);
return p*q;
}
else
return 0;
}
bool bstNode::printAncestors(bstNode* root,int key)
{
if(root==NULL)
return false;
if(root->data==key)
return true;
if(printAncestors(root->left,key)||printAncestors(root->right,key))
{
cout<<root->data<<"\t";
return true;
}
return false;
}
bstNode* bstNode::printParent(bstNode* cur,int key,bstNode* prev)
{
if(cur==NULL)
return NULL;
printParent(cur->left,key,cur);
if(key==cur->data)
{
cout<<prev->data<<endl;
return prev;
}
printParent(cur->right,key,cur);
return NULL;
}
bool bstNode::isMirror(bstNode* root1,bstNode* root2)
{
if(root1==NULL && root2==NULL)
return true;
if(root1==NULL || root2==NULL)
return false;
return ((root1->data == root2->data) && isMirror(root1->left,root2->right) && isMirror(root1->right,root2->left));
}
int main()
{
bstNode n1;
bstNode *root = NULL;
int n;
cout<<"Enter the number of elements you want to enter"<<endl;
cin>>n;
int val;
for(int i=0;i<n;i++)
{
cout<<"Enter the item to insert"<<endl;
cin>>val;
root = n1.Insert(root,val);
}
cout<<"Preorder scheme of the tree:\n";
n1.preorder(root);
cout<<endl;
cout<<"Inorder scheme of the tree:\n";
n1.inorder(root);
cout<<endl;
cout<<"Postorder scheme of the tree:\n";
n1.postorder(root);
cout<<endl;
cout<<"Levelorder scheme of the tree:\n";
n1.levelorder(root);
cout<<endl;
// val=0;
// cout<<"Number of leaf nodes in the tree = "<<n1.countLeaves(root,val)<<endl;
bstNode* newRoot = n1.Copy(root);
// cout<<"Copy of the tree:(Preorder scheme)\n";
// n1.preorder(newRoot);
// cout<<endl;
// cout<<"Minimum element in the tree: "<<n1.findMin(root)<<endl;
// cout<<"Maximum element in the tree: "<<n1.findMax(root)<<endl;
// cout<<"Height of the tree is: "<<n1.height(root)<<endl;
// cout<<"Enter the value of the node to be created"<<endl;
// cin>>val;
// root = n1.insertNode(root,val);
// cout<<"Inorder scheme of the tree after node insertion\n";
// n1.inorder(root);
// cout<<endl;
// cout<<"Enter the node to be deleted\n";
// cin>>val;
// n1.deleteNode(root,val);
// cout<<"Inorder scheme of the tree after node deletion\n";
// n1.inorder(root);
// cout<<endl;
// cout<<"Comparison of two trees: \n";
// if(n1.compare(root,newRoot) == 1)
// cout<<"Trees are same!\n";
// else
// cout<<"Trees are different!\n";
// cout<<"Enter the element to be searched\n";
// cin>>val;
// if(n1.Search(root,val) == true)
// cout<<"Element found!\n";
// else
// cout<<"Element not found!\n";
cout<<"Enter the node whose ancestors are to be printed\n";
cin>>val;
n1.printAncestors(root,val);
cout<<endl;
cout<<"Enter the node whose parent is to be printed\n";
cin>>val;
cout<<"Parent of the entered node:\n";
n1.printParent(root,val,NULL);
cout<<"Checking for mirror image:\n";
if(n1.isMirror(root,newRoot))
{
cout<<"The two trees are mirror images of each other\n";
}
else
{
cout<<"The two trees are not mirror images of each other\n";
}
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "DecoratorTest.h"
#include "AutoPacket.h"
#include "AutoPacketFactory.h"
#include "AutoPacketListener.h"
#include "FilterPropertyExtractor.h"
#include "TestFixtures/Decoration.h"
using namespace std;
TEST_F(DecoratorTest, VerifyCorrectExtraction) {
vector<const type_info*> v;
// Run our prop extractor based on a known decorator:
RecipientPropertyExtractor<FilterA>::Enumerate(
[&v] (const std::type_info& ti) {
v.push_back(&ti);
}
);
ASSERT_EQ(2UL, v.size()) << "Extracted an insufficient number of types from a known filter function";
// Arguments MUST be in order:
EXPECT_EQ(typeid(Decoration<0>), *v[0]);
EXPECT_EQ(typeid(Decoration<1>), *v[1]);
// Verify both overloads wind up returning the same array:
auto ppCur = RecipientPropertyExtractor<FilterA>::Enumerate();
for(size_t i = 0; ppCur[i]; i++)
EXPECT_EQ(*v[i], *ppCur[i]) << "Two overloads of Enumerate returned contradictory types";
}
TEST_F(DecoratorTest, VerifyEmptyExtraction) {
const type_info*const* v = RecipientPropertyExtractor<Object>::Enumerate();
EXPECT_EQ(nullptr, *v) << "Extracted arguments from an object known not to have a Filter method";
}
TEST_F(DecoratorTest, VerifySimplePacketDecoration) {
AutoRequired<AutoPacketFactory> factory;
// Create the packet we will be persisting:
auto packet = factory->NewPacket();
// Add a few decorations on this packet:
auto& knownDec0 = packet->Decorate(Decoration<0>());
auto& knownDec1 = packet->Decorate(Decoration<1>());
auto& knownDec2 = packet->Decorate(Decoration<2>());
// Verify we can get these packets back--might throw exceptions here!
auto& dec0 = packet->Get<Decoration<0>>();
auto& dec1 = packet->Get<Decoration<1>>();
auto& dec2 = packet->Get<Decoration<2>>();
// Verify identities:
EXPECT_EQ(&knownDec0, &dec0) << "Decoration 0 returned at an incorrect location";
EXPECT_EQ(&knownDec1, &dec1) << "Decoration 1 returned at an incorrect location";
EXPECT_EQ(&knownDec2, &dec2) << "Decoration 2 returned at an incorrect location";
// Verify content correctness:
EXPECT_EQ(0, dec0.i) << "Decoration 0 incorrectly persisted";
EXPECT_EQ(1, dec1.i) << "Decoration 1 incorrectly persisted";
EXPECT_EQ(2, dec2.i) << "Decoration 2 incorrectly persisted";
}
TEST_F(DecoratorTest, VerifyDecoratorAwareness) {
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Create another packet where a subscriber exists:
AutoRequired<FilterA> filterA;
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
auto packet2 = factory->NewPacket();
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
// Verify the second one does:
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
}
TEST_F(DecoratorTest, VerifySimpleFilter) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Manually register the subscriber:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet from the factory:
auto packet = factory->NewPacket();
// Decorate with one instance:
packet->Decorate(Decoration<0>());
// Verify that no hit takes place with inadequate decoration:
EXPECT_FALSE(filterA->m_called) << "Filter called prematurely with insufficient decoration";
// Now decorate with the other requirement of the filter:
packet->Decorate(Decoration<1>());
// A hit should have taken place at this point:
EXPECT_TRUE(filterA->m_called) << "Filter was not called even though it was fully satisfied";
}
TEST_F(DecoratorTest, VerifyNoMultiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Subscriber registration verification:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet and attempt redundant introduction:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Redundant decoration did not throw an exception as expected";
// Verify that a call has not yet been made
EXPECT_FALSE(filterA->m_called) << "A call made on an idempotent packet decoration";
// Now finish saturating the filter and ensure we get a call:
packet->Decorate(Decoration<1>());
EXPECT_TRUE(filterA->m_called) << "Filter was not called after being fully satisfied";
}
TEST_F(DecoratorTest, VerifyInterThreadDecoration) {
AutoRequired<FilterB> filterB;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext ctxt;
// Kick off all threads:
ctxt->InitiateCoreThreads();
// Obtain a packet for processing and decorate it:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
// Verify that the recipient has NOT yet received the message:
EXPECT_FALSE(filterB->m_called) << "A call was made to a thread which should not have been able to process it";
// Wake up the barrier and post a quit message:
filterB->m_barr.wait();
*filterB += [&filterB] { filterB->Stop(); };
filterB->Wait();
// Verify that the filter method has been called
EXPECT_TRUE(filterB->m_called) << "A deferred filter method was not called as expected";
}
TEST_F(DecoratorTest, VerifyTeardownArrangement) {
AutoRequired<AutoPacketFactory> factory;
std::weak_ptr<FilterA> filterAWeak;
{
std::shared_ptr<AutoPacket> packet;
{
// Create the filter and subscribe it
std::shared_ptr<FilterA> filterA(new FilterA);
filterAWeak = filterA;
factory->AddSubscriber(filterA);
// Create the packet--this should lock in references to all subscribers:
packet = factory->NewPacket();
}
// Verify that the subscription has not expired:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber while it was still registered";
{
std::shared_ptr<FilterA> filterA = filterAWeak.lock();
// Unsubscribe the filter:
factory->RemoveSubscriber(filterA);
}
// Verify that unsubscription STILL does not result in expiration:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber expired before all packets on that subscriber were satisfied";
// Satisfy the packet:
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
}
// Filter should be expired now:
ASSERT_TRUE(filterAWeak.expired()) << "Subscriber was still left outstanding even though all references should be gone";
}
TEST_F(DecoratorTest, VerifyCheckout) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
{
// Verify that an unsubscribed decoration returns a correct checkout:
auto unused = packet->Checkout<Decoration<4>>();
EXPECT_FALSE(unused) << "Checkout incorrectly generated for unsubscribed decoration";
}
// Satisfy the other decoration:
packet->Decorate(Decoration<1>());
{
AutoCheckout<Decoration<0>> exterior;
{
AutoCheckout<Decoration<0>> checkout = packet->Checkout<Decoration<0>>();
// Verify we can move the original type:
AutoCheckout<Decoration<0>> checkoutMoved(std::move(checkout));
// Verify no hits yet:
EXPECT_FALSE(filterA->m_called) << "Filter called as a consequence of a checkout move operation";
// Move the checkout a second time:
exterior = std::move(checkoutMoved);
}
// Still no hits
EXPECT_FALSE(filterA->m_called) << "Filter called before a decoration checkout expired";
// Mark ready so we get committed:
exterior.Ready();
}
// Verify a hit took place now
EXPECT_TRUE(filterA->m_called) << "Filter was not called after all decorations were installed";
}
TEST_F(DecoratorTest, RollbackCorrectness) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<1>());
// Request and immediately allow the destruction of a checkout:
packet->Checkout<Decoration<0>>();
// Verify no hit took place--the checkout should have been cancelled:
EXPECT_FALSE(filterA->m_called) << "Filter was not called after all decorations were installed";
// We should not be able to obtain another checkout of this decoration on this packet:
EXPECT_ANY_THROW(packet->Checkout<Decoration<0>>()) << "An attempt to check out a decoration a second time should have failed";
// We shouldn't be able to manually decorate, either:
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "An attempt to manually add a previously failed decoration succeeded where it should not have";
}
TEST_F(DecoratorTest, VerifyAntiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
{
// Obtain a new packet and mark an unsatisfiable decoration:
auto packet = factory->NewPacket();
packet->Unsatisfiable<Decoration<0>>();
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Decoration succeeded on a decoration marked unsatisfiable";
}
{
// Obtain a new packet and try to make a satisfied decoration unsatisfiable.
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Unsatisfiable<Decoration<0>>()) << "Succeeded in marking an already-existing decoration as unsatisfiable";
}
}
TEST_F(DecoratorTest, VerifyReflexiveReciept) {
AutoRequired<FilterA> filterA;
AutoRequired<FilterC> filterC;
AutoRequired<FilterD> filterD;
AutoRequired<FilterE> filterE;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet first:
auto packet = factory->NewPacket();
// The mere act of obtaining a packet should have triggered filterD to be fired:
EXPECT_TRUE(filterD->m_called) << "Trivial filter was not called as expected";
// The packet should be able to obtain a pointer to itself:
{
AutoPacketAdaptor extractor(*packet);
AutoPacket* reflex = extractor;
EXPECT_EQ(packet.get(), reflex) << "Packet reflexive reference was not an identity";
}
// Decorate--should satisfy filterC
packet->Decorate(Decoration<0>());
EXPECT_TRUE(filterC->m_called) << "FilterC should have been satisfied with one decoration";
// FilterC should have also satisfied filterA:
EXPECT_TRUE(filterA->m_called) << "FilterA should have been satisfied by FilterC";
// Release the packet, and verify that filterD gets hit only once this happens
EXPECT_FALSE(filterE->m_called) << "Packet listener was notified prematurely";
packet.reset();
EXPECT_TRUE(filterE->m_called) << "Packet listener was not notified as anticipated";
}
<commit_msg>added a unit test of expected functionality..<commit_after>#include "stdafx.h"
#include "DecoratorTest.h"
#include "AutoPacket.h"
#include "AutoPacketFactory.h"
#include "AutoPacketListener.h"
#include "FilterPropertyExtractor.h"
#include "TestFixtures/Decoration.h"
using namespace std;
TEST_F(DecoratorTest, VerifyCorrectExtraction) {
vector<const type_info*> v;
// Run our prop extractor based on a known decorator:
RecipientPropertyExtractor<FilterA>::Enumerate(
[&v] (const std::type_info& ti) {
v.push_back(&ti);
}
);
ASSERT_EQ(2UL, v.size()) << "Extracted an insufficient number of types from a known filter function";
// Arguments MUST be in order:
EXPECT_EQ(typeid(Decoration<0>), *v[0]);
EXPECT_EQ(typeid(Decoration<1>), *v[1]);
// Verify both overloads wind up returning the same array:
auto ppCur = RecipientPropertyExtractor<FilterA>::Enumerate();
for(size_t i = 0; ppCur[i]; i++)
EXPECT_EQ(*v[i], *ppCur[i]) << "Two overloads of Enumerate returned contradictory types";
}
TEST_F(DecoratorTest, VerifyEmptyExtraction) {
const type_info*const* v = RecipientPropertyExtractor<Object>::Enumerate();
EXPECT_EQ(nullptr, *v) << "Extracted arguments from an object known not to have a Filter method";
}
TEST_F(DecoratorTest, VerifySimplePacketDecoration) {
AutoRequired<AutoPacketFactory> factory;
// Create the packet we will be persisting:
auto packet = factory->NewPacket();
// Add a few decorations on this packet:
auto& knownDec0 = packet->Decorate(Decoration<0>());
auto& knownDec1 = packet->Decorate(Decoration<1>());
auto& knownDec2 = packet->Decorate(Decoration<2>());
// Verify we can get these packets back--might throw exceptions here!
auto& dec0 = packet->Get<Decoration<0>>();
auto& dec1 = packet->Get<Decoration<1>>();
auto& dec2 = packet->Get<Decoration<2>>();
// Verify identities:
EXPECT_EQ(&knownDec0, &dec0) << "Decoration 0 returned at an incorrect location";
EXPECT_EQ(&knownDec1, &dec1) << "Decoration 1 returned at an incorrect location";
EXPECT_EQ(&knownDec2, &dec2) << "Decoration 2 returned at an incorrect location";
// Verify content correctness:
EXPECT_EQ(0, dec0.i) << "Decoration 0 incorrectly persisted";
EXPECT_EQ(1, dec1.i) << "Decoration 1 incorrectly persisted";
EXPECT_EQ(2, dec2.i) << "Decoration 2 incorrectly persisted";
}
TEST_F(DecoratorTest, VerifyDecoratorAwareness) {
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Create another packet where a subscriber exists:
AutoRequired<FilterA> filterA;
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
auto packet2 = factory->NewPacket();
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
// Verify the second one does:
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
}
TEST_F(DecoratorTest, VerifyDescendentAwareness) {
// Create a packet while the factory has no subscribers:
AutoRequired<AutoPacketFactory> factory;
auto packet1 = factory->NewPacket();
// Verify subscription-free status:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
//Create a subcontext
AutoCurrentContext ctxt;
auto pContext = ctxt->CreateAnonymous();
{
CurrentContextPusher pusher;
pContext->SetCurrent();
//add a filter in the subcontext
AutoRequired<FilterA> subFilter;
}
//Create a packet where a subscriber exists only in a subcontext
auto packet2 = factory->NewPacket();
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked expected subscription from subcontext";
//destroy the subcontext
pContext.reset();
auto packet3 = factory->NewPacket();
EXPECT_FALSE(packet3->HasSubscribers<Decoration<0>>()) << "Subscription exists where one should not have existed";
// Verify the first packet still does not have subscriptions:
EXPECT_FALSE(packet1->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
// Verify the second one does:
EXPECT_TRUE(packet2->HasSubscribers<Decoration<0>>()) << "Packet lacked an expected subscription";
// Verify the third one does not:
EXPECT_FALSE(packet3->HasSubscribers<Decoration<0>>()) << "Subscription was incorrectly, retroactively added to a packet";
}
TEST_F(DecoratorTest, VerifySimpleFilter) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Manually register the subscriber:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet from the factory:
auto packet = factory->NewPacket();
// Decorate with one instance:
packet->Decorate(Decoration<0>());
// Verify that no hit takes place with inadequate decoration:
EXPECT_FALSE(filterA->m_called) << "Filter called prematurely with insufficient decoration";
// Now decorate with the other requirement of the filter:
packet->Decorate(Decoration<1>());
// A hit should have taken place at this point:
EXPECT_TRUE(filterA->m_called) << "Filter was not called even though it was fully satisfied";
}
TEST_F(DecoratorTest, VerifyNoMultiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Subscriber registration verification:
ASSERT_TRUE(factory->IsSubscriber<FilterA>());
// Obtain a packet and attempt redundant introduction:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Redundant decoration did not throw an exception as expected";
// Verify that a call has not yet been made
EXPECT_FALSE(filterA->m_called) << "A call made on an idempotent packet decoration";
// Now finish saturating the filter and ensure we get a call:
packet->Decorate(Decoration<1>());
EXPECT_TRUE(filterA->m_called) << "Filter was not called after being fully satisfied";
}
TEST_F(DecoratorTest, VerifyInterThreadDecoration) {
AutoRequired<FilterB> filterB;
AutoRequired<AutoPacketFactory> factory;
AutoCurrentContext ctxt;
// Kick off all threads:
ctxt->InitiateCoreThreads();
// Obtain a packet for processing and decorate it:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
// Verify that the recipient has NOT yet received the message:
EXPECT_FALSE(filterB->m_called) << "A call was made to a thread which should not have been able to process it";
// Wake up the barrier and post a quit message:
filterB->m_barr.wait();
*filterB += [&filterB] { filterB->Stop(); };
filterB->Wait();
// Verify that the filter method has been called
EXPECT_TRUE(filterB->m_called) << "A deferred filter method was not called as expected";
}
TEST_F(DecoratorTest, VerifyTeardownArrangement) {
AutoRequired<AutoPacketFactory> factory;
std::weak_ptr<FilterA> filterAWeak;
{
std::shared_ptr<AutoPacket> packet;
{
// Create the filter and subscribe it
std::shared_ptr<FilterA> filterA(new FilterA);
filterAWeak = filterA;
factory->AddSubscriber(filterA);
// Create the packet--this should lock in references to all subscribers:
packet = factory->NewPacket();
}
// Verify that the subscription has not expired:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber while it was still registered";
{
std::shared_ptr<FilterA> filterA = filterAWeak.lock();
// Unsubscribe the filter:
factory->RemoveSubscriber(filterA);
}
// Verify that unsubscription STILL does not result in expiration:
ASSERT_FALSE(filterAWeak.expired()) << "A subscriber expired before all packets on that subscriber were satisfied";
// Satisfy the packet:
packet->Decorate(Decoration<0>());
packet->Decorate(Decoration<1>());
}
// Filter should be expired now:
ASSERT_TRUE(filterAWeak.expired()) << "Subscriber was still left outstanding even though all references should be gone";
}
TEST_F(DecoratorTest, VerifyCheckout) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
{
// Verify that an unsubscribed decoration returns a correct checkout:
auto unused = packet->Checkout<Decoration<4>>();
EXPECT_FALSE(unused) << "Checkout incorrectly generated for unsubscribed decoration";
}
// Satisfy the other decoration:
packet->Decorate(Decoration<1>());
{
AutoCheckout<Decoration<0>> exterior;
{
AutoCheckout<Decoration<0>> checkout = packet->Checkout<Decoration<0>>();
// Verify we can move the original type:
AutoCheckout<Decoration<0>> checkoutMoved(std::move(checkout));
// Verify no hits yet:
EXPECT_FALSE(filterA->m_called) << "Filter called as a consequence of a checkout move operation";
// Move the checkout a second time:
exterior = std::move(checkoutMoved);
}
// Still no hits
EXPECT_FALSE(filterA->m_called) << "Filter called before a decoration checkout expired";
// Mark ready so we get committed:
exterior.Ready();
}
// Verify a hit took place now
EXPECT_TRUE(filterA->m_called) << "Filter was not called after all decorations were installed";
}
TEST_F(DecoratorTest, RollbackCorrectness) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet for use with deferred decoration:
auto packet = factory->NewPacket();
packet->Decorate(Decoration<1>());
// Request and immediately allow the destruction of a checkout:
packet->Checkout<Decoration<0>>();
// Verify no hit took place--the checkout should have been cancelled:
EXPECT_FALSE(filterA->m_called) << "Filter was not called after all decorations were installed";
// We should not be able to obtain another checkout of this decoration on this packet:
EXPECT_ANY_THROW(packet->Checkout<Decoration<0>>()) << "An attempt to check out a decoration a second time should have failed";
// We shouldn't be able to manually decorate, either:
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "An attempt to manually add a previously failed decoration succeeded where it should not have";
}
TEST_F(DecoratorTest, VerifyAntiDecorate) {
AutoRequired<FilterA> filterA;
AutoRequired<AutoPacketFactory> factory;
{
// Obtain a new packet and mark an unsatisfiable decoration:
auto packet = factory->NewPacket();
packet->Unsatisfiable<Decoration<0>>();
EXPECT_ANY_THROW(packet->Decorate(Decoration<0>())) << "Decoration succeeded on a decoration marked unsatisfiable";
}
{
// Obtain a new packet and try to make a satisfied decoration unsatisfiable.
auto packet = factory->NewPacket();
packet->Decorate(Decoration<0>());
EXPECT_ANY_THROW(packet->Unsatisfiable<Decoration<0>>()) << "Succeeded in marking an already-existing decoration as unsatisfiable";
}
}
TEST_F(DecoratorTest, VerifyReflexiveReciept) {
AutoRequired<FilterA> filterA;
AutoRequired<FilterC> filterC;
AutoRequired<FilterD> filterD;
AutoRequired<FilterE> filterE;
AutoRequired<AutoPacketFactory> factory;
// Obtain a packet first:
auto packet = factory->NewPacket();
// The mere act of obtaining a packet should have triggered filterD to be fired:
EXPECT_TRUE(filterD->m_called) << "Trivial filter was not called as expected";
// The packet should be able to obtain a pointer to itself:
{
AutoPacketAdaptor extractor(*packet);
AutoPacket* reflex = extractor;
EXPECT_EQ(packet.get(), reflex) << "Packet reflexive reference was not an identity";
}
// Decorate--should satisfy filterC
packet->Decorate(Decoration<0>());
EXPECT_TRUE(filterC->m_called) << "FilterC should have been satisfied with one decoration";
// FilterC should have also satisfied filterA:
EXPECT_TRUE(filterA->m_called) << "FilterA should have been satisfied by FilterC";
// Release the packet, and verify that filterD gets hit only once this happens
EXPECT_FALSE(filterE->m_called) << "Packet listener was notified prematurely";
packet.reset();
EXPECT_TRUE(filterE->m_called) << "Packet listener was not notified as anticipated";
}
<|endoftext|> |
<commit_before><commit_msg>Update ConfigPhiLeadingPb.C<commit_after><|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2201
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1305300 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/08/20 03:00:10<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2202
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>#include <algorithm>
#include "TrimNoOps.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Simplify.h"
#include "Solve.h"
#include "IREquality.h"
#include "ExprUsesVar.h"
#include "Substitute.h"
#include "CodeGen_GPU_Dev.h"
#include "Var.h"
#include "CSE.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
using std::pair;
using std::make_pair;
using std::map;
namespace {
/** Remove identity functions, even if they have side-effects. */
class StripIdentities : public IRMutator {
using IRMutator::visit;
void visit(const Call *op) {
if (op->call_type == Call::Intrinsic &&
op->name == Call::trace_expr) {
expr = mutate(op->args[4]);
} else if (op->call_type == Call::Intrinsic &&
(op->name == Call::return_second ||
op->name == Call::likely)) {
expr = mutate(op->args.back());
} else {
IRMutator::visit(op);
}
}
};
/** Construct a sufficient condition for the visited stmt to be a no-op. */
class IsNoOp : public IRVisitor {
using IRVisitor::visit;
Expr make_and(Expr a, Expr b) {
if (is_zero(a) || is_one(b)) return a;
if (is_zero(b) || is_one(a)) return b;
return a && b;
}
Expr make_or(Expr a, Expr b) {
if (is_zero(a) || is_one(b)) return b;
if (is_zero(b) || is_one(a)) return a;
return a || b;
}
void visit(const Store *op) {
if (op->value.type().is_handle()) {
condition = const_false();
} else {
if (is_zero(condition)) {
return;
}
// If the value being stored is the same as the value loaded,
// this is a no-op
debug(3) << "Considering store: " << Stmt(op) << "\n";
Expr equivalent_load = Load::make(op->value.type(), op->name, op->index, Buffer(), Parameter());
Expr is_no_op = equivalent_load == op->value;
is_no_op = StripIdentities().mutate(is_no_op);
// We need to call CSE since sometimes we have "let" stmt on the RHS
// that makes the expr harder to solve, i.e. the solver will just give up
// and return a conservative false on call to and_condition_over_domain().
is_no_op = simplify(common_subexpression_elimination(is_no_op));
debug(3) << "Anding condition over domain... " << is_no_op << "\n";
is_no_op = and_condition_over_domain(is_no_op, Scope<Interval>::empty_scope());
condition = make_and(condition, is_no_op);
debug(3) << "Condition is now " << condition << "\n";
}
}
void visit(const For *op) {
if (is_zero(condition)) {
return;
}
Expr old_condition = condition;
condition = const_true();
op->body.accept(this);
Scope<Interval> varying;
varying.push(op->name, Interval(op->min, op->min + op->extent - 1));
condition = simplify(common_subexpression_elimination(condition));
debug(3) << "About to relax over " << op->name << " : " << condition << "\n";
condition = and_condition_over_domain(condition, varying);
debug(3) << "Relaxed: " << condition << "\n";
condition = make_and(old_condition, make_or(condition, simplify(op->extent <= 0)));
}
void visit(const IfThenElse *op) {
if (is_zero(condition)) {
return;
}
Expr total_condition = condition;
condition = const_true();
op->then_case.accept(this);
// This is a no-op if we're previously a no-op, and the
// condition is false or the if body is a no-op.
total_condition = make_and(total_condition, make_or(!op->condition, condition));
condition = const_true();
if (op->else_case.defined()) {
op->else_case.accept(this);
total_condition = make_and(total_condition, make_or(op->condition, condition));
}
condition = total_condition;
}
void visit(const Call *op) {
// Certain intrinsics that may appear in loops have side-effects. Most notably: image_store.
if (op->call_type == Call::Intrinsic &&
(op->name == Call::rewrite_buffer ||
op->name == Call::image_store ||
op->name == Call::copy_memory)) {
condition = const_false();
} else {
IRVisitor::visit(op);
}
}
template<typename LetOrLetStmt>
void visit_let(const LetOrLetStmt *op) {
IRVisitor::visit(op);
if (expr_uses_var(condition, op->name)) {
condition = Let::make(op->name, op->value, condition);
}
}
void visit(const LetStmt *op) {
visit_let(op);
}
void visit(const Let *op) {
visit_let(op);
}
public:
Expr condition = const_true();
};
class SimplifyUsingBounds : public IRMutator {
struct ContainingLoop {
string var;
Interval i;
};
vector<ContainingLoop> containing_loops;
using IRMutator::visit;
// Can we prove a condition over the non-rectangular domain of the for loops we're in?
bool provably_true_over_domain(Expr test) {
debug(3) << "Attempting to prove: " << test << "\n";
for (size_t i = containing_loops.size(); i > 0; i--) {
// Because the domain is potentially non-rectangular, we
// need to take each variable one-by-one, simplifying in
// between to allow for cancellations of the bounds of
// inner loops with outer loop variables.
auto loop = containing_loops[i-1];
if (is_const(test)) {
break;
} else if (!expr_uses_var(test, loop.var)) {
continue;
} else if (is_one(simplify(loop.i.min == loop.i.max)) && expr_uses_var(test, loop.var)) {
// If min == max then either the domain only has one correct value, which we
// can substitute directly.
test = common_subexpression_elimination(Let::make(loop.var, loop.i.min, test));
} else if (is_one(simplify(loop.i.min >= loop.i.max)) && expr_uses_var(test, loop.var)) {
// If min >= max then either the domain only has one correct value,
// or the domain is empty, which implies both min/max are true under
// the domain.
test = common_subexpression_elimination(Let::make(loop.var, loop.i.min, test) ||
Let::make(loop.var, loop.i.max, test));
} else {
Scope<Interval> s;
// Rearrange the expression if possible so that the
// loop var only occurs once.
Expr solved = solve_expression(test, loop.var);
if (solved.defined()) {
test = solved;
}
s.push(loop.var, loop.i);
test = and_condition_over_domain(test, s);
}
test = simplify(test);
debug(3) << " -> " << test << "\n";
}
return is_one(test);
}
void visit(const Min *op) {
if (!op->type.is_int() || op->type.bits() < 32) {
IRMutator::visit(op);
} else {
Expr a = mutate(op->a);
Expr b = mutate(op->b);
Expr test = a <= b;
if (provably_true_over_domain(a <= b)) {
expr = a;
} else if (provably_true_over_domain(b <= a)) {
expr = b;
} else {
expr = Min::make(a, b);
}
}
}
void visit(const Max *op) {
if (!op->type.is_int() || op->type.bits() < 32) {
IRMutator::visit(op);
} else {
Expr a = mutate(op->a);
Expr b = mutate(op->b);
if (provably_true_over_domain(a >= b)) {
expr = a;
} else if (provably_true_over_domain(b >= a)) {
expr = b;
} else {
expr = Max::make(a, b);
}
}
}
template<typename Cmp>
void visit_cmp(const Cmp *op) {
IRMutator::visit(op);
if (provably_true_over_domain(expr)) {
expr = make_one(op->type);
} else if (provably_true_over_domain(!expr)) {
expr = make_zero(op->type);
}
}
void visit(const LE *op) {
visit_cmp(op);
}
void visit(const LT *op) {
visit_cmp(op);
}
void visit(const GE *op) {
visit_cmp(op);
}
void visit(const GT *op) {
visit_cmp(op);
}
void visit(const EQ *op) {
visit_cmp(op);
}
void visit(const NE *op) {
visit_cmp(op);
}
template<typename StmtOrExpr, typename LetStmtOrLet>
StmtOrExpr visit_let(const LetStmtOrLet *op) {
Expr value = mutate(op->value);
containing_loops.push_back({op->name, {value, value}});
StmtOrExpr body = mutate(op->body);
containing_loops.pop_back();
return LetStmtOrLet::make(op->name, value, body);
}
void visit(const Let *op) {
expr = visit_let<Expr, Let>(op);
}
void visit(const LetStmt *op) {
stmt = visit_let<Stmt, LetStmt>(op);
}
void visit(const For *op) {
// Simplify the loop bounds.
Expr min = mutate(op->min);
Expr extent = mutate(op->extent);
containing_loops.push_back({op->name, {min, min + extent - 1}});
Stmt body = mutate(op->body);
containing_loops.pop_back();
stmt = For::make(op->name, min, extent, op->for_type, op->device_api, body);
}
public:
SimplifyUsingBounds(const string &v, const Interval &i) {
containing_loops.push_back({v, i});
}
SimplifyUsingBounds() {}
};
class TrimNoOps : public IRMutator {
using IRMutator::visit;
void visit(const For *op) {
// Bounds of GPU loops can't depend on outer gpu loop vars
if (CodeGen_GPU_Dev::is_gpu_var(op->name)) {
debug(3) << "TrimNoOps found gpu loop var: " << op->name << "\n";
IRMutator::visit(op);
return;
}
Stmt body = mutate(op->body);
debug(3) << "\n\n ***** Trim no ops in loop over " << op->name << "\n";
IsNoOp is_no_op;
body.accept(&is_no_op);
debug(3) << "Condition is " << is_no_op.condition << "\n";
is_no_op.condition = simplify(simplify(common_subexpression_elimination(is_no_op.condition)));
debug(3) << "Simplified condition is " << is_no_op.condition << "\n";
if (is_one(is_no_op.condition)) {
// This loop is definitely useless
stmt = Evaluate::make(0);
return;
} else if (is_zero(is_no_op.condition)) {
// This loop is definitely needed
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
return;
}
// The condition is something interesting. Try to see if we
// can trim the loop bounds over which the loop does
// something.
Interval i = solve_for_outer_interval(!is_no_op.condition, op->name);
debug(3) << "Interval is: " << i.min << ", " << i.max << "\n";
if (interval_is_everything(i)) {
// Nope.
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
return;
}
if (interval_is_empty(i)) {
// Empty loop
stmt = Evaluate::make(0);
return;
}
// Simplify the body to take advantage of the fact that the
// loop range is now truncated
body = simplify(SimplifyUsingBounds(op->name, i).mutate(body));
string new_min_name = unique_name(op->name + ".new_min", false);
string new_max_name = unique_name(op->name + ".new_max", false);
string old_max_name = unique_name(op->name + ".old_max", false);
Expr new_min_var = Variable::make(Int(32), new_min_name);
Expr new_max_var = Variable::make(Int(32), new_max_name);
Expr old_max_var = Variable::make(Int(32), old_max_name);
// Convert max to max-plus-one
if (interval_has_upper_bound(i)) {
i.max = i.max + 1;
}
// Truncate the loop bounds to the region over which it's not
// a no-op.
Expr old_max = op->min + op->extent;
Expr new_min, new_max;
if (interval_has_lower_bound(i)) {
new_min = clamp(i.min, op->min, old_max_var);
} else {
new_min = op->min;
}
if (interval_has_upper_bound(i)) {
new_max = clamp(i.max, new_min_var, old_max_var);
} else {
new_max = old_max;
}
Expr new_extent = new_max_var - new_min_var;
stmt = For::make(op->name, new_min_var, new_extent, op->for_type, op->device_api, body);
stmt = LetStmt::make(new_max_name, new_max, stmt);
stmt = LetStmt::make(new_min_name, new_min, stmt);
stmt = LetStmt::make(old_max_name, old_max, stmt);
stmt = simplify(stmt);
debug(3) << "Rewrote loop.\n"
<< "Old: " << Stmt(op) << "\n"
<< "New: " << stmt << "\n";
}
};
}
Stmt trim_no_ops(Stmt s) {
s = TrimNoOps().mutate(s);
return s;
}
}
}
<commit_msg>update intrinsic checking code<commit_after>#include <algorithm>
#include "TrimNoOps.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Simplify.h"
#include "Solve.h"
#include "IREquality.h"
#include "ExprUsesVar.h"
#include "Substitute.h"
#include "CodeGen_GPU_Dev.h"
#include "Var.h"
#include "CSE.h"
namespace Halide {
namespace Internal {
using std::string;
using std::vector;
using std::pair;
using std::make_pair;
using std::map;
namespace {
/** Remove identity functions, even if they have side-effects. */
class StripIdentities : public IRMutator {
using IRMutator::visit;
void visit(const Call *op) {
if (op->is_intrinsic(Call::trace_expr)) {
expr = mutate(op->args[4]);
} else if (op->is_intrinsic(Call::return_second) ||
op->is_intrinsic(Call::likely)) {
expr = mutate(op->args.back());
} else {
IRMutator::visit(op);
}
}
};
/** Construct a sufficient condition for the visited stmt to be a no-op. */
class IsNoOp : public IRVisitor {
using IRVisitor::visit;
Expr make_and(Expr a, Expr b) {
if (is_zero(a) || is_one(b)) return a;
if (is_zero(b) || is_one(a)) return b;
return a && b;
}
Expr make_or(Expr a, Expr b) {
if (is_zero(a) || is_one(b)) return b;
if (is_zero(b) || is_one(a)) return a;
return a || b;
}
void visit(const Store *op) {
if (op->value.type().is_handle()) {
condition = const_false();
} else {
if (is_zero(condition)) {
return;
}
// If the value being stored is the same as the value loaded,
// this is a no-op
debug(3) << "Considering store: " << Stmt(op) << "\n";
Expr equivalent_load = Load::make(op->value.type(), op->name, op->index, Buffer(), Parameter());
Expr is_no_op = equivalent_load == op->value;
is_no_op = StripIdentities().mutate(is_no_op);
// We need to call CSE since sometimes we have "let" stmt on the RHS
// that makes the expr harder to solve, i.e. the solver will just give up
// and return a conservative false on call to and_condition_over_domain().
is_no_op = simplify(common_subexpression_elimination(is_no_op));
debug(3) << "Anding condition over domain... " << is_no_op << "\n";
is_no_op = and_condition_over_domain(is_no_op, Scope<Interval>::empty_scope());
condition = make_and(condition, is_no_op);
debug(3) << "Condition is now " << condition << "\n";
}
}
void visit(const For *op) {
if (is_zero(condition)) {
return;
}
Expr old_condition = condition;
condition = const_true();
op->body.accept(this);
Scope<Interval> varying;
varying.push(op->name, Interval(op->min, op->min + op->extent - 1));
condition = simplify(common_subexpression_elimination(condition));
debug(3) << "About to relax over " << op->name << " : " << condition << "\n";
condition = and_condition_over_domain(condition, varying);
debug(3) << "Relaxed: " << condition << "\n";
condition = make_and(old_condition, make_or(condition, simplify(op->extent <= 0)));
}
void visit(const IfThenElse *op) {
if (is_zero(condition)) {
return;
}
Expr total_condition = condition;
condition = const_true();
op->then_case.accept(this);
// This is a no-op if we're previously a no-op, and the
// condition is false or the if body is a no-op.
total_condition = make_and(total_condition, make_or(!op->condition, condition));
condition = const_true();
if (op->else_case.defined()) {
op->else_case.accept(this);
total_condition = make_and(total_condition, make_or(op->condition, condition));
}
condition = total_condition;
}
void visit(const Call *op) {
// Certain intrinsics that may appear in loops have side-effects. Most notably: image_store.
if (op->call_type == Call::Intrinsic &&
(op->name == Call::rewrite_buffer ||
op->name == Call::image_store ||
op->name == Call::copy_memory)) {
condition = const_false();
} else {
IRVisitor::visit(op);
}
}
template<typename LetOrLetStmt>
void visit_let(const LetOrLetStmt *op) {
IRVisitor::visit(op);
if (expr_uses_var(condition, op->name)) {
condition = Let::make(op->name, op->value, condition);
}
}
void visit(const LetStmt *op) {
visit_let(op);
}
void visit(const Let *op) {
visit_let(op);
}
public:
Expr condition = const_true();
};
class SimplifyUsingBounds : public IRMutator {
struct ContainingLoop {
string var;
Interval i;
};
vector<ContainingLoop> containing_loops;
using IRMutator::visit;
// Can we prove a condition over the non-rectangular domain of the for loops we're in?
bool provably_true_over_domain(Expr test) {
debug(3) << "Attempting to prove: " << test << "\n";
for (size_t i = containing_loops.size(); i > 0; i--) {
// Because the domain is potentially non-rectangular, we
// need to take each variable one-by-one, simplifying in
// between to allow for cancellations of the bounds of
// inner loops with outer loop variables.
auto loop = containing_loops[i-1];
if (is_const(test)) {
break;
} else if (!expr_uses_var(test, loop.var)) {
continue;
} else if (is_one(simplify(loop.i.min == loop.i.max)) && expr_uses_var(test, loop.var)) {
// If min == max then either the domain only has one correct value, which we
// can substitute directly.
test = common_subexpression_elimination(Let::make(loop.var, loop.i.min, test));
} else if (is_one(simplify(loop.i.min >= loop.i.max)) && expr_uses_var(test, loop.var)) {
// If min >= max then either the domain only has one correct value,
// or the domain is empty, which implies both min/max are true under
// the domain.
test = common_subexpression_elimination(Let::make(loop.var, loop.i.min, test) ||
Let::make(loop.var, loop.i.max, test));
} else {
Scope<Interval> s;
// Rearrange the expression if possible so that the
// loop var only occurs once.
Expr solved = solve_expression(test, loop.var);
if (solved.defined()) {
test = solved;
}
s.push(loop.var, loop.i);
test = and_condition_over_domain(test, s);
}
test = simplify(test);
debug(3) << " -> " << test << "\n";
}
return is_one(test);
}
void visit(const Min *op) {
if (!op->type.is_int() || op->type.bits() < 32) {
IRMutator::visit(op);
} else {
Expr a = mutate(op->a);
Expr b = mutate(op->b);
Expr test = a <= b;
if (provably_true_over_domain(a <= b)) {
expr = a;
} else if (provably_true_over_domain(b <= a)) {
expr = b;
} else {
expr = Min::make(a, b);
}
}
}
void visit(const Max *op) {
if (!op->type.is_int() || op->type.bits() < 32) {
IRMutator::visit(op);
} else {
Expr a = mutate(op->a);
Expr b = mutate(op->b);
if (provably_true_over_domain(a >= b)) {
expr = a;
} else if (provably_true_over_domain(b >= a)) {
expr = b;
} else {
expr = Max::make(a, b);
}
}
}
template<typename Cmp>
void visit_cmp(const Cmp *op) {
IRMutator::visit(op);
if (provably_true_over_domain(expr)) {
expr = make_one(op->type);
} else if (provably_true_over_domain(!expr)) {
expr = make_zero(op->type);
}
}
void visit(const LE *op) {
visit_cmp(op);
}
void visit(const LT *op) {
visit_cmp(op);
}
void visit(const GE *op) {
visit_cmp(op);
}
void visit(const GT *op) {
visit_cmp(op);
}
void visit(const EQ *op) {
visit_cmp(op);
}
void visit(const NE *op) {
visit_cmp(op);
}
template<typename StmtOrExpr, typename LetStmtOrLet>
StmtOrExpr visit_let(const LetStmtOrLet *op) {
Expr value = mutate(op->value);
containing_loops.push_back({op->name, {value, value}});
StmtOrExpr body = mutate(op->body);
containing_loops.pop_back();
return LetStmtOrLet::make(op->name, value, body);
}
void visit(const Let *op) {
expr = visit_let<Expr, Let>(op);
}
void visit(const LetStmt *op) {
stmt = visit_let<Stmt, LetStmt>(op);
}
void visit(const For *op) {
// Simplify the loop bounds.
Expr min = mutate(op->min);
Expr extent = mutate(op->extent);
containing_loops.push_back({op->name, {min, min + extent - 1}});
Stmt body = mutate(op->body);
containing_loops.pop_back();
stmt = For::make(op->name, min, extent, op->for_type, op->device_api, body);
}
public:
SimplifyUsingBounds(const string &v, const Interval &i) {
containing_loops.push_back({v, i});
}
SimplifyUsingBounds() {}
};
class TrimNoOps : public IRMutator {
using IRMutator::visit;
void visit(const For *op) {
// Bounds of GPU loops can't depend on outer gpu loop vars
if (CodeGen_GPU_Dev::is_gpu_var(op->name)) {
debug(3) << "TrimNoOps found gpu loop var: " << op->name << "\n";
IRMutator::visit(op);
return;
}
Stmt body = mutate(op->body);
debug(3) << "\n\n ***** Trim no ops in loop over " << op->name << "\n";
IsNoOp is_no_op;
body.accept(&is_no_op);
debug(3) << "Condition is " << is_no_op.condition << "\n";
is_no_op.condition = simplify(simplify(common_subexpression_elimination(is_no_op.condition)));
debug(3) << "Simplified condition is " << is_no_op.condition << "\n";
if (is_one(is_no_op.condition)) {
// This loop is definitely useless
stmt = Evaluate::make(0);
return;
} else if (is_zero(is_no_op.condition)) {
// This loop is definitely needed
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
return;
}
// The condition is something interesting. Try to see if we
// can trim the loop bounds over which the loop does
// something.
Interval i = solve_for_outer_interval(!is_no_op.condition, op->name);
debug(3) << "Interval is: " << i.min << ", " << i.max << "\n";
if (interval_is_everything(i)) {
// Nope.
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
return;
}
if (interval_is_empty(i)) {
// Empty loop
stmt = Evaluate::make(0);
return;
}
// Simplify the body to take advantage of the fact that the
// loop range is now truncated
body = simplify(SimplifyUsingBounds(op->name, i).mutate(body));
string new_min_name = unique_name(op->name + ".new_min", false);
string new_max_name = unique_name(op->name + ".new_max", false);
string old_max_name = unique_name(op->name + ".old_max", false);
Expr new_min_var = Variable::make(Int(32), new_min_name);
Expr new_max_var = Variable::make(Int(32), new_max_name);
Expr old_max_var = Variable::make(Int(32), old_max_name);
// Convert max to max-plus-one
if (interval_has_upper_bound(i)) {
i.max = i.max + 1;
}
// Truncate the loop bounds to the region over which it's not
// a no-op.
Expr old_max = op->min + op->extent;
Expr new_min, new_max;
if (interval_has_lower_bound(i)) {
new_min = clamp(i.min, op->min, old_max_var);
} else {
new_min = op->min;
}
if (interval_has_upper_bound(i)) {
new_max = clamp(i.max, new_min_var, old_max_var);
} else {
new_max = old_max;
}
Expr new_extent = new_max_var - new_min_var;
stmt = For::make(op->name, new_min_var, new_extent, op->for_type, op->device_api, body);
stmt = LetStmt::make(new_max_name, new_max, stmt);
stmt = LetStmt::make(new_min_name, new_min, stmt);
stmt = LetStmt::make(old_max_name, old_max, stmt);
stmt = simplify(stmt);
debug(3) << "Rewrote loop.\n"
<< "Old: " << Stmt(op) << "\n"
<< "New: " << stmt << "\n";
}
};
}
Stmt trim_no_ops(Stmt s) {
s = TrimNoOps().mutate(s);
return s;
}
}
}
<|endoftext|> |
<commit_before>#include <QtWidgets>
#include "dragwidget.h"
#include <log.h>
DragWidget::DragWidget(QWidget* parent)
: QFrame(parent)
{
setAcceptDrops(true);
}
void DragWidget::dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void DragWidget::mousePressEvent(QMouseEvent* event)
{
QWidget* el = childAt(event->pos());
if (!el) {
return;
}
QVariant type = el->property("type");
if (!type.isValid() || type.toString() != "IconLabel") {
cds_debug("Dragging disabled for {}", el->objectName().toStdString());
return;
}
QLabel* child = static_cast<QLabel*>(childAt(event->pos()));
if (!child) {
return;
}
const QPixmap* pixmap = child->pixmap();
if (!pixmap)
return;
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << QPoint(event->pos() - child->pos()) << child->objectName();
QMimeData* mimeData = new QMimeData;
mimeData->setData("CANdevStudio/x-dnditemdata", itemData);
QDrag* drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(*pixmap);
drag->setHotSpot({ 0, 0 });
if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction) {
child->close();
} else {
child->show();
child->setPixmap(*pixmap);
}
}
<commit_msg>Fix for drag and drop issue reported as #122<commit_after>#include <QtWidgets>
#include "dragwidget.h"
#include <log.h>
DragWidget::DragWidget(QWidget* parent)
: QFrame(parent)
{
setAcceptDrops(true);
}
void DragWidget::dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasFormat("CANdevStudio/x-dnditemdata")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void DragWidget::mousePressEvent(QMouseEvent* event)
{
QWidget* el = childAt(event->pos());
if (!el) {
return;
}
QVariant type = el->property("type");
if (!type.isValid() || type.toString() != "IconLabel") {
cds_debug("Dragging disabled for {}", el->objectName().toStdString());
return;
}
QLabel* child = static_cast<QLabel*>(childAt(event->pos()));
if (!child) {
return;
}
const QPixmap* pixmap = child->pixmap();
if (!pixmap)
return;
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << QPoint(event->pos() - child->pos()) << child->objectName();
QMimeData* mimeData = new QMimeData;
mimeData->setData("CANdevStudio/x-dnditemdata", itemData);
QDrag* drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(*pixmap);
drag->setHotSpot({ 0, 0 });
if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction) {
child->close();
} else {
child->show();
child->setPixmap(*pixmap);
}
}
<|endoftext|> |
<commit_before>/**
* @file configreader.hpp
* @brief COSSB configuration Reader
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details Load(Read) configuration file
*/
#ifndef _COSSB_CONFIG_HPP_
#define _COSSB_CONFIG_HPP_
#include "../arch/singleton.hpp"
#include <tinyxml2.h>
#include <vector>
#include <string>
#include <map>
using namespace tinyxml2;
using namespace std;
namespace cossb {
namespace base {
enum class dependencyType : unsigned int { COMPONENT=1, PACKAGE };
typedef struct _sDependency {
dependencyType type;
std::string name;
public:
_sDependency(dependencyType _type, string _name):type(_type),name(_name) { }
_sDependency& operator=(const _sDependency& other) { return *this; }
} sDependency;
typedef struct _sLibrary {
std::string use;
std::string sofile;
public:
_sLibrary(string _use, string _sofile):use(_use), sofile(_sofile) { }
} sLibrary;
/**
* @brief system configuration class
*/
class configreader : public arch::singleton<configreader> {
public:
configreader();
virtual ~configreader();
/**
* @brief load configuration file(manifest file)
*/
bool load(const char* manifest_conf);
/**
* @brief update configuration
*/
bool update(configreader* conf);
/**
* @brief getting manifest information
*/
vector<sDependency*>* get_dependency() { return &_dependency; };
vector<string>* get_repository() { return &_repository; }
vector<sLibrary*>* get_library() { return &_library; }
map<string, string>* get_path() { return &_path; }
map<string, string>* get_product() { return &_product; }
private:
void parse_dependency();
void parse_path();
void parse_repository();
void parse_product();
void parse_library();
private:
tinyxml2::XMLDocument* _doc;
vector<sDependency*> _dependency;
vector<string> _repository;
vector<sLibrary*> _library;
map<string, string> _path;
map<string, string> _product;
};
#define cossb_config cossb::base::configreader::instance()
} /* namespace base */
} /* namespace cossb */
#endif /* _COSSB_CONFIG_HPP_ */
<commit_msg>add code for service<commit_after>/**
* @file configreader.hpp
* @brief COSSB configuration Reader
* @author Byunghun Hwang<bhhwang@nsynapse.com>
* @date 2015. 6. 21
* @details Load(Read) configuration file
*/
#ifndef _COSSB_CONFIG_HPP_
#define _COSSB_CONFIG_HPP_
#include "../arch/singleton.hpp"
#include <tinyxml2.h>
#include <vector>
#include <string>
#include <map>
using namespace tinyxml2;
using namespace std;
namespace cossb {
namespace base {
enum class dependencyType : unsigned int { COMPONENT=1, PACKAGE };
typedef struct _sDependency {
dependencyType type;
std::string name;
public:
_sDependency(dependencyType _type, string _name):type(_type),name(_name) { }
_sDependency& operator=(const _sDependency& other) { return *this; }
} sDependency;
typedef struct _sLibrary {
std::string use;
std::string sofile;
public:
_sLibrary(string _use, string _sofile):use(_use), sofile(_sofile) { }
} sLibrary;
/**
* @brief system configuration class
*/
class configreader : public arch::singleton<configreader> {
public:
configreader();
virtual ~configreader();
/**
* @brief load configuration file(manifest file)
*/
bool load(const char* manifest_conf);
/**
* @brief update configuration
*/
bool update(configreader* conf);
/**
* @brief getting manifest information
*/
vector<sDependency*>* get_dependency() { return &_dependency; };
vector<string>* get_repository() { return &_repository; }
vector<sLibrary*>* get_library() { return &_library; }
map<string, string>* get_path() { return &_path; }
map<string, string>* get_product() { return &_product; }
map<string, string>* get_service() { return &_service; }
private:
void parse_dependency();
void parse_path();
void parse_repository();
void parse_product();
void parse_library();
void parse_service();
private:
tinyxml2::XMLDocument* _doc;
vector<sDependency*> _dependency;
vector<string> _repository;
vector<sLibrary*> _library;
map<string, string> _path;
map<string, string> _product;
map<string, string> _service;
};
#define cossb_config cossb::base::configreader::instance()
} /* namespace base */
} /* namespace cossb */
#endif /* _COSSB_CONFIG_HPP_ */
<|endoftext|> |
<commit_before>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 David Shah <david@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include "cells.h"
#include "design_utils.h"
#include "log.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
static bool is_nextpnr_iob(Context *ctx, CellInfo *cell)
{
return cell->type == ctx->id("$nextpnr_ibuf") || cell->type == ctx->id("$nextpnr_obuf") ||
cell->type == ctx->id("$nextpnr_iobuf");
}
class Ecp5Packer
{
public:
Ecp5Packer(Context *ctx) : ctx(ctx){};
private:
// Process the contents of packed_cells and new_cells
void flush_cells()
{
for (auto pcell : packed_cells) {
ctx->cells.erase(pcell);
}
for (auto &ncell : new_cells) {
ctx->cells[ncell->name] = std::move(ncell);
}
packed_cells.clear();
new_cells.clear();
}
// Find FFs associated with LUTs, or LUT expansion muxes
void find_lutff_pairs()
{
for (auto cell : sorted(ctx->cells)) {
CellInfo *ci = cell.second;
if (is_lut(ctx, ci) || is_pfumx(ctx, ci) || is_l6mux(ctx, ci)) {
NetInfo *znet = ci->ports.at(ctx->id("Z")).net;
if (znet != nullptr) {
CellInfo *ff = net_only_drives(ctx, znet, is_ff, ctx->id("DI"), false);
if (ff != nullptr) {
lutffPairs[ci->name] = ff->name;
}
}
}
}
}
// Simple "packer" to remove nextpnr IOBUFs, this assumes IOBUFs are manually instantiated
void pack_io()
{
log_info("Packing IOs..\n");
for (auto cell : sorted(ctx->cells)) {
CellInfo *ci = cell.second;
if (is_nextpnr_iob(ctx, ci)) {
CellInfo *trio = nullptr;
if (ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_iobuf")) {
trio = net_only_drives(ctx, ci->ports.at(ctx->id("O")).net, is_trellis_io, ctx->id("B"), true, ci);
} else if (ci->type == ctx->id("$nextpnr_obuf")) {
trio = net_only_drives(ctx, ci->ports.at(ctx->id("I")).net, is_trellis_io, ctx->id("B"), true, ci);
}
if (trio != nullptr) {
// Trivial case, TRELLIS_IO used. Just destroy the net and the
// iobuf
log_info("%s feeds TRELLIS_IO %s, removing %s %s.\n", ci->name.c_str(ctx), trio->name.c_str(ctx),
ci->type.c_str(ctx), ci->name.c_str(ctx));
NetInfo *net = trio->ports.at(ctx->id("B")).net;
if (net != nullptr) {
ctx->nets.erase(net->name);
trio->ports.at(ctx->id("B")).net = nullptr;
}
if (ci->type == ctx->id("$nextpnr_iobuf")) {
NetInfo *net2 = ci->ports.at(ctx->id("I")).net;
if (net2 != nullptr) {
ctx->nets.erase(net2->name);
}
}
} else {
log_error("TRELLIS_IO required on all top level IOs...\n");
}
packed_cells.insert(ci->name);
std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(trio->attrs, trio->attrs.begin()));
}
}
flush_cells();
}
// Pass to pack LUT5s into a newly created slice
void pack_lut5s()
{
log_info("Packing LUT5s...\n");
for (auto cell : sorted(ctx->cells)) {
CellInfo *ci = cell.second;
if (is_pfumx(ctx, ci)) {
std::unique_ptr<CellInfo> packed =
create_ecp5_cell(ctx, ctx->id("TRELLIS_SLICE"), ci->name.str(ctx) + "_SLICE");
NetInfo *f0 = ci->ports.at(ctx->id("BLUT")).net;
if (f0 == nullptr)
log_error("PFUMX '%s' has disconnected port 'BLUT'\n", ci->name.c_str(ctx));
NetInfo *f1 = ci->ports.at(ctx->id("ALUT")).net;
if (f1 == nullptr)
log_error("PFUMX '%s' has disconnected port 'ALUT'\n", ci->name.c_str(ctx));
CellInfo *lc0 = net_driven_by(ctx, f0, is_lut, ctx->id("Z"));
CellInfo *lc1 = net_driven_by(ctx, f1, is_lut, ctx->id("Z"));
if (lc0 == nullptr)
log_error("PFUMX '%s' has BLUT driven by cell other than a LUT\n", ci->name.c_str(ctx));
if (lc1 == nullptr)
log_error("PFUMX '%s' has ALUT driven by cell other than a LUT\n", ci->name.c_str(ctx));
replace_port(lc0, ctx->id("A"), packed.get(), ctx->id("A0"));
replace_port(lc0, ctx->id("B"), packed.get(), ctx->id("B0"));
replace_port(lc0, ctx->id("C"), packed.get(), ctx->id("C0"));
replace_port(lc0, ctx->id("D"), packed.get(), ctx->id("D0"));
replace_port(lc1, ctx->id("A"), packed.get(), ctx->id("A1"));
replace_port(lc1, ctx->id("B"), packed.get(), ctx->id("B1"));
replace_port(lc1, ctx->id("C"), packed.get(), ctx->id("C1"));
replace_port(lc1, ctx->id("D"), packed.get(), ctx->id("D1"));
replace_port(ci, ctx->id("C0"), packed.get(), ctx->id("M0"));
replace_port(ci, ctx->id("Z"), packed.get(), ctx->id("OFX0"));
ctx->nets.erase(f0->name);
ctx->nets.erase(f1->name);
if (lutffPairs.find(ci->name) != lutffPairs.end()) {
CellInfo *ff = ctx->cells.at(lutffPairs[ci->name]).get();
ff_to_lc(ctx, ff, packed.get(), 0, true);
packed_cells.insert(ff->name);
}
new_cells.push_back(std::move(packed));
packed_cells.insert(lc0->name);
packed_cells.insert(lc1->name);
packed_cells.insert(ci->name);
}
}
flush_cells();
}
public:
void pack()
{
pack_io();
pack_lut5s();
}
private:
Context *ctx;
std::unordered_set<IdString> packed_cells;
std::vector<std::unique_ptr<CellInfo>> new_cells;
struct SliceUsage
{
bool lut0_used = false, lut1_used = false;
bool ccu2_used = false, dpram_used = false, ramw_used = false;
bool ff0_used = false, ff1_used = false;
bool mux5_used = false, muxx_used = false;
};
std::unordered_map<IdString, SliceUsage> sliceUsage;
std::unordered_map<IdString, IdString> lutffPairs;
};
// Main pack function
bool Arch::pack()
{
Context *ctx = getCtx();
try {
log_break();
Ecp5Packer(ctx).pack();
log_info("Checksum: 0x%08x\n", ctx->checksum());
return true;
} catch (log_execution_error_exception) {
return false;
}
}
NEXTPNR_NAMESPACE_END
<commit_msg>ecp5: Working on packer LUT pairing functionality<commit_after>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 David Shah <david@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <algorithm>
#include <iterator>
#include <unordered_set>
#include "cells.h"
#include "design_utils.h"
#include "log.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
static bool is_nextpnr_iob(Context *ctx, CellInfo *cell)
{
return cell->type == ctx->id("$nextpnr_ibuf") || cell->type == ctx->id("$nextpnr_obuf") ||
cell->type == ctx->id("$nextpnr_iobuf");
}
class Ecp5Packer
{
public:
Ecp5Packer(Context *ctx) : ctx(ctx){};
private:
// Process the contents of packed_cells and new_cells
void flush_cells()
{
for (auto pcell : packed_cells) {
ctx->cells.erase(pcell);
}
for (auto &ncell : new_cells) {
ctx->cells[ncell->name] = std::move(ncell);
}
packed_cells.clear();
new_cells.clear();
}
// Find FFs associated with LUTs, or LUT expansion muxes
void find_lutff_pairs()
{
for (auto cell : sorted(ctx->cells)) {
CellInfo *ci = cell.second;
if (is_lut(ctx, ci) || is_pfumx(ctx, ci) || is_l6mux(ctx, ci)) {
NetInfo *znet = ci->ports.at(ctx->id("Z")).net;
if (znet != nullptr) {
CellInfo *ff = net_only_drives(ctx, znet, is_ff, ctx->id("DI"), false);
if (ff != nullptr) {
lutffPairs[ci->name] = ff->name;
fflutPairs[ff->name] = ci->name;
}
}
}
}
}
// Return whether two FFs can be packed together in the same slice
bool can_pack_ffs(CellInfo *ff0, CellInfo *ff1)
{
if (str_or_default(ff0->params, ctx->id("GSR"), "DISABLED") !=
str_or_default(ff1->params, ctx->id("GSR"), "DISABLED"))
return false;
if (str_or_default(ff0->params, ctx->id("SRMODE"), "LSR_OVER_CE") !=
str_or_default(ff1->params, ctx->id("SRMODE"), "LSR_OVER_CE"))
return false;
if (str_or_default(ff0->params, ctx->id("CEMUX"), "1") != str_or_default(ff1->params, ctx->id("CEMUX"), "1"))
return false;
if (str_or_default(ff0->params, ctx->id("LSRMUX"), "LSR") !=
str_or_default(ff1->params, ctx->id("LSRMUX"), "LSR"))
return false;
if (str_or_default(ff0->params, ctx->id("CLKMUX"), "CLK") !=
str_or_default(ff1->params, ctx->id("CLKMUX"), "CLK"))
return false;
if (ff0->ports.at(ctx->id("CLK")).net != ff1->ports.at(ctx->id("CLK")).net)
return false;
if (ff0->ports.at(ctx->id("CE")).net != ff1->ports.at(ctx->id("CE")).net)
return false;
if (ff0->ports.at(ctx->id("LSR")).net != ff1->ports.at(ctx->id("LSR")).net)
return false;
return true;
}
// Return true if two LUTs can be paired considering FF compatibility
bool can_pack_lutff(IdString lut0, IdString lut1)
{
auto ff0 = lutffPairs.find(lut0), ff1 = lutffPairs.find(lut1);
if (ff0 != lutffPairs.end() && ff1 != lutffPairs.end()) {
return can_pack_ffs(ctx->cells.at(ff0->second).get(), ctx->cells.at(ff1->second).get());
} else {
return true;
}
}
// Find "closely connected" LUTs and pair them together
void pair_luts(std::unordered_map<IdString, IdString> &lutPairs)
{
std::unordered_set<IdString> procdLuts;
for (auto cell : sorted(ctx->cells)) {
CellInfo *ci = cell.second;
if (is_lut(ctx, ci) && procdLuts.find(cell.first) == procdLuts.end()) {
NetInfo *znet = ci->ports.at(ctx->id("Z")).net;
if (znet != nullptr) {
for (auto user : znet->users) {
if (is_lut(ctx, user.cell) && procdLuts.find(user.cell->name) == procdLuts.end()) {
if (can_pack_lutff(ci->name, user.cell->name)) {
procdLuts.insert(ci->name);
procdLuts.insert(user.cell->name);
lutPairs[ci->name] = user.cell->name;
goto paired;
}
}
}
if (false) {
paired:
continue;
}
}
if (lutffPairs.find(ci->name) != lutffPairs.end()) {
NetInfo *qnet = ctx->cells.at(lutffPairs[ci->name])->ports.at(ctx->id("Q")).net;
if (qnet != nullptr) {
for (auto user : qnet->users) {
if (is_lut(ctx, user.cell) && procdLuts.find(user.cell->name) == procdLuts.end()) {
if (can_pack_lutff(ci->name, user.cell->name)) {
procdLuts.insert(ci->name);
procdLuts.insert(user.cell->name);
lutPairs[ci->name] = user.cell->name;
goto paired_ff;
}
}
}
if (false) {
paired_ff:
continue;
}
}
}
for (char inp : "ABCD") {
NetInfo *innet = ci->ports.at(ctx->id(std::string("") + inp)).net;
if (innet != nullptr && innet->driver.cell != nullptr) {
CellInfo *drv = innet->driver.cell;
if (is_lut(ctx, drv) && innet->driver.port == ctx->id("Z")) {
if (procdLuts.find(drv->name) == procdLuts.end()) {
if (can_pack_lutff(ci->name, drv->name)) {
procdLuts.insert(ci->name);
procdLuts.insert(drv->name);
lutPairs[ci->name] = drv->name;
goto paired_inlut;
}
}
} else if (is_ff(ctx, drv) && innet->driver.port == ctx->id("Q")) {
auto fflut = fflutPairs.find(drv->name);
if (fflut != fflutPairs.end() && procdLuts.find(fflut->second) == procdLuts.end()) {
if (can_pack_lutff(ci->name, fflut->second)) {
procdLuts.insert(ci->name);
procdLuts.insert(fflut->second);
lutPairs[ci->name] = fflut->second;
goto paired_inlut;
}
}
}
}
}
if (false) {
paired_inlut:
continue;
}
}
}
}
// Simple "packer" to remove nextpnr IOBUFs, this assumes IOBUFs are manually instantiated
void pack_io()
{
log_info("Packing IOs..\n");
for (auto cell : sorted(ctx->cells)) {
CellInfo *ci = cell.second;
if (is_nextpnr_iob(ctx, ci)) {
CellInfo *trio = nullptr;
if (ci->type == ctx->id("$nextpnr_ibuf") || ci->type == ctx->id("$nextpnr_iobuf")) {
trio = net_only_drives(ctx, ci->ports.at(ctx->id("O")).net, is_trellis_io, ctx->id("B"), true, ci);
} else if (ci->type == ctx->id("$nextpnr_obuf")) {
trio = net_only_drives(ctx, ci->ports.at(ctx->id("I")).net, is_trellis_io, ctx->id("B"), true, ci);
}
if (trio != nullptr) {
// Trivial case, TRELLIS_IO used. Just destroy the net and the
// iobuf
log_info("%s feeds TRELLIS_IO %s, removing %s %s.\n", ci->name.c_str(ctx), trio->name.c_str(ctx),
ci->type.c_str(ctx), ci->name.c_str(ctx));
NetInfo *net = trio->ports.at(ctx->id("B")).net;
if (net != nullptr) {
ctx->nets.erase(net->name);
trio->ports.at(ctx->id("B")).net = nullptr;
}
if (ci->type == ctx->id("$nextpnr_iobuf")) {
NetInfo *net2 = ci->ports.at(ctx->id("I")).net;
if (net2 != nullptr) {
ctx->nets.erase(net2->name);
}
}
} else {
log_error("TRELLIS_IO required on all top level IOs...\n");
}
packed_cells.insert(ci->name);
std::copy(ci->attrs.begin(), ci->attrs.end(), std::inserter(trio->attrs, trio->attrs.begin()));
}
}
flush_cells();
}
// Pass to pack LUT5s into a newly created slice
void pack_lut5s()
{
log_info("Packing LUT5s...\n");
for (auto cell : sorted(ctx->cells)) {
CellInfo *ci = cell.second;
if (is_pfumx(ctx, ci)) {
std::unique_ptr<CellInfo> packed =
create_ecp5_cell(ctx, ctx->id("TRELLIS_SLICE"), ci->name.str(ctx) + "_SLICE");
NetInfo *f0 = ci->ports.at(ctx->id("BLUT")).net;
if (f0 == nullptr)
log_error("PFUMX '%s' has disconnected port 'BLUT'\n", ci->name.c_str(ctx));
NetInfo *f1 = ci->ports.at(ctx->id("ALUT")).net;
if (f1 == nullptr)
log_error("PFUMX '%s' has disconnected port 'ALUT'\n", ci->name.c_str(ctx));
CellInfo *lc0 = net_driven_by(ctx, f0, is_lut, ctx->id("Z"));
CellInfo *lc1 = net_driven_by(ctx, f1, is_lut, ctx->id("Z"));
if (lc0 == nullptr)
log_error("PFUMX '%s' has BLUT driven by cell other than a LUT\n", ci->name.c_str(ctx));
if (lc1 == nullptr)
log_error("PFUMX '%s' has ALUT driven by cell other than a LUT\n", ci->name.c_str(ctx));
replace_port(lc0, ctx->id("A"), packed.get(), ctx->id("A0"));
replace_port(lc0, ctx->id("B"), packed.get(), ctx->id("B0"));
replace_port(lc0, ctx->id("C"), packed.get(), ctx->id("C0"));
replace_port(lc0, ctx->id("D"), packed.get(), ctx->id("D0"));
replace_port(lc1, ctx->id("A"), packed.get(), ctx->id("A1"));
replace_port(lc1, ctx->id("B"), packed.get(), ctx->id("B1"));
replace_port(lc1, ctx->id("C"), packed.get(), ctx->id("C1"));
replace_port(lc1, ctx->id("D"), packed.get(), ctx->id("D1"));
replace_port(ci, ctx->id("C0"), packed.get(), ctx->id("M0"));
replace_port(ci, ctx->id("Z"), packed.get(), ctx->id("OFX0"));
ctx->nets.erase(f0->name);
ctx->nets.erase(f1->name);
sliceUsage[packed->name].lut0_used = true;
sliceUsage[packed->name].lut1_used = true;
sliceUsage[packed->name].mux5_used = true;
if (lutffPairs.find(ci->name) != lutffPairs.end()) {
CellInfo *ff = ctx->cells.at(lutffPairs[ci->name]).get();
ff_to_lc(ctx, ff, packed.get(), 0, true);
packed_cells.insert(ff->name);
sliceUsage[packed->name].ff0_used = true;
}
new_cells.push_back(std::move(packed));
packed_cells.insert(lc0->name);
packed_cells.insert(lc1->name);
packed_cells.insert(ci->name);
}
}
flush_cells();
}
public:
void pack()
{
pack_io();
pack_lut5s();
}
private:
Context *ctx;
std::unordered_set<IdString> packed_cells;
std::vector<std::unique_ptr<CellInfo>> new_cells;
struct SliceUsage
{
bool lut0_used = false, lut1_used = false;
bool ccu2_used = false, dpram_used = false, ramw_used = false;
bool ff0_used = false, ff1_used = false;
bool mux5_used = false, muxx_used = false;
};
std::unordered_map<IdString, SliceUsage> sliceUsage;
std::unordered_map<IdString, IdString> lutffPairs;
std::unordered_map<IdString, IdString> fflutPairs;
};
// Main pack function
bool Arch::pack()
{
Context *ctx = getCtx();
try {
log_break();
Ecp5Packer(ctx).pack();
log_info("Checksum: 0x%08x\n", ctx->checksum());
return true;
} catch (log_execution_error_exception) {
return false;
}
}
NEXTPNR_NAMESPACE_END
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1787
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1145109 by johtaylo@johtaylo-JTBUILDER03-increment on 2015/04/28 03:00:17<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 1788
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/******************************************************************
motorized device control
This object extends Patriot to support motorized devices such as
motorized vents or curtains. It operates in 2 different modes.
In the default mode, the open or close output is held for the
desired percentage of open/close. In pulse mode the open or close
pin is pulsed on for 1 second, then both are pulsed to stop movement.
It is expected that devices will take a fixed amount of time to
open or close. That duration is specified when the device is instantiated.
For example, the roof vent on my RV takes about 5 seconds to go
from closed to fully open. So the vent device will be instantiated
as follows:
Motorized *vent = Motorized(D1, D2, 5, "Roof Vent")
http://www.github.com/rlisle/Patriot
Written by Ron Lisle
BSD license, check license.txt for more information.
All text above must be included in any redistribution.
Changelog:
2017-10-08: Add pulse mode
2017-09-17: Initial version based on fan plugin.
******************************************************************/
#include "PatriotMotorized.h"
/**
* Constructor
* @param openPinNum is the pin number that is connected to the open motor
* @param closePinNum is the pin number that is connected to the close motor
* @param duration is the # seconds to completely open/close
* @param name String name used to address this device.
*/
Motorized::Motorized(int8_t openPinNum, int8_t closePinNum, int8_t duration, String name)
{
_name = name;
_openPinNum = openPinNum;
_closePinNum = closePinNum;
_durationSeconds = duration; // # seconds to go from fully closed to open
_pulseDurationX10msecs = 0; // Duration of pulse in msecs x 10 (eg. 100 = 1 second)
_mode = 0; // 1 = pulse mode, pulse both to stop
_percent = 0; // 0 = closed, 100 = fully open
_state = 0; // 0 = not changing
_stopTimeMsecs = 0;
_pulseTimeMsecs = 0;
pinMode(openPinNum, OUTPUT);
pinMode(closePinNum, OUTPUT);
digitalWrite(openPinNum, LOW);
digitalWrite(closePinNum, LOW);
}
Motorized::setPulseMode(int8_t msecs)
{
_mode = 1; // Pulse either pin to start, pulse both to stop
_pulseMsecs = msecs; // Used to end pulses
}
/**
* Set percent
* This is the method used to start changing position
*
* @param percent Int 0 to 100
*/
void Motorized::setPercent(int percent)
{
Serial.print("setPercent ");
Serial.println(percent);
if(percent == _percent) return;
Serial.println("DEBUG: changing percent to "+String(percent));
_stopTimeMsecs = calcStopTime(percent);
if(percent > _percent) // Are we opening?
{
_state = 1;
digitalWrite(_openPinNum, HIGH);
}
else
{
_state = 2;
digitalWrite(_closePinNum, HIGH);
}
_percent = percent; // Target percent
if(_mode != 0)
{
_pulseTimeMsecs = millis() + ((long)_pulseDurationX10msecs * 10l);
}
}
void Motorized::loop()
{
if(_state == 0) return; // Nothing to do if we're idle
// Has the motor been on long enough?
if(_stopMsecs != 0)
{
if(millis() >= _stopTimeMsecs)
{
turnOffMotor();
}
}
// Has our pulse been on long enough?
if(_pulseTimeMsecs != 0 && millis() >= _pulseTimeMsecs)
{
_pulseTimeMsecs = 0;
digitalWrite(_openPinNum, LOW);
digitalWrite(_closePinNum, LOW);
// Was this the stop pulse?
if(_stopTimeMsecs == 0)
{
_state = 0;
}
}
}
unsigned long Motorized::calcStopTime(int percent)
{
int deltaPercent = percent - _percent;
if(deltaPercent < 0) deltaPercent = -deltaPercent;
unsigned long stopTime = millis();
stopTime += (_durationSeconds * 100000) / deltaPercent;
Serial.println("Current time = "+String(millis())+", stop time = "+String(stopTime));
return stopTime;
}
void Motorized::turnOffMotor()
{
Serial.println("Turning off motor");
if(_mode == 0)
{
_state = 0; // All done
digitalWrite(_openPinNum, LOW);
digitalWrite(_closePinNum, LOW);
} else { // Pulse both pins to "stop"
_pulseTimeMsecs = millis() + ((long)_pulseDurationX10msecs * 10l);
digitalWrite(_openPinNum, HIGH);
digitalWrite(_closePinNum, HIGH);
}
_stopMsecs = 0;
}
<commit_msg>Refactor for readability<commit_after>/******************************************************************
motorized device control
This object extends Patriot to support motorized devices such as
motorized vents or curtains. It operates in 2 different modes.
In the default mode, the open or close output is held for the
desired percentage of open/close. In pulse mode the open or close
pin is pulsed on for 1 second, then both are pulsed to stop movement.
It is expected that devices will take a fixed amount of time to
open or close. That duration is specified when the device is instantiated.
For example, the roof vent on my RV takes about 5 seconds to go
from closed to fully open. So the vent device will be instantiated
as follows:
Motorized *vent = Motorized(D1, D2, 5, "Roof Vent")
http://www.github.com/rlisle/Patriot
Written by Ron Lisle
BSD license, check license.txt for more information.
All text above must be included in any redistribution.
Changelog:
2017-10-08: Add pulse mode
2017-09-17: Initial version based on fan plugin.
******************************************************************/
#include "PatriotMotorized.h"
/**
* Constructor
* @param openPinNum is the pin number that is connected to the open motor
* @param closePinNum is the pin number that is connected to the close motor
* @param duration is the # seconds to completely open/close
* @param name String name used to address this device.
*/
Motorized::Motorized(int8_t openPinNum, int8_t closePinNum, int8_t duration, String name)
{
_name = name;
_openPinNum = openPinNum;
_closePinNum = closePinNum;
_durationSeconds = duration; // # seconds to go from fully closed to open
_pulseDurationX10msecs = 0; // Duration of pulse in msecs x 10 (eg. 100 = 1 second)
_mode = 0; // 1 = pulse mode, pulse both to stop
_percent = 0; // 0 = closed, 100 = fully open
_state = 0; // 0 = not changing
_stopTimeMsecs = 0;
_pulseTimeMsecs = 0;
pinMode(openPinNum, OUTPUT);
pinMode(closePinNum, OUTPUT);
digitalWrite(openPinNum, LOW);
digitalWrite(closePinNum, LOW);
}
void Motorized::setPulseMode(int8_t msecsX10)
{
_mode = 1; // Pulse either pin to start, pulse both to stop
_pulseDurationX10msecs = msecsX10; // Used to end pulses
}
/**
* Set percent
* This is the method used to start changing position
*
* @param percent Int 0 to 100
*/
void Motorized::setPercent(int percent)
{
Serial.print("setPercent ");
Serial.println(percent);
if(percent == _percent) return;
Serial.println("DEBUG: changing percent to "+String(percent));
_stopTimeMsecs = calcStopTime(percent);
if(percent > _percent) // Are we opening?
{
_state = 1;
digitalWrite(_openPinNum, HIGH);
}
else
{
_state = 2;
digitalWrite(_closePinNum, HIGH);
}
_percent = percent; // Target percent
if(_mode != 0)
{
_pulseTimeMsecs = millis() + ((long)_pulseDurationX10msecs * 10l);
}
}
void Motorized::loop()
{
if(_state == 0) return; // Nothing to do if we're idle
// Has the motor been on long enough?
if(_stopTimeMsecs != 0)
{
if(millis() >= _stopTimeMsecs)
{
turnOffMotor();
}
}
// Has our pulse been on long enough?
if(_pulseTimeMsecs != 0 && millis() >= _pulseTimeMsecs)
{
_pulseTimeMsecs = 0;
digitalWrite(_openPinNum, LOW);
digitalWrite(_closePinNum, LOW);
// Was this the stop pulse?
if(_stopTimeMsecs == 0)
{
_state = 0;
}
}
}
unsigned long Motorized::calcStopTime(int percent)
{
int deltaPercent = percent - _percent;
if(deltaPercent < 0) deltaPercent = -deltaPercent;
unsigned long stopTime = millis();
stopTime += (_durationSeconds * 100000) / deltaPercent;
Serial.println("Current time = "+String(millis())+", stop time = "+String(stopTime));
return stopTime;
}
void Motorized::turnOffMotor()
{
Serial.println("Turning off motor");
if(_mode == 0)
{
_state = 0; // All done
digitalWrite(_openPinNum, LOW);
digitalWrite(_closePinNum, LOW);
} else { // Pulse both pins to "stop"
_pulseTimeMsecs = millis() + ((long)_pulseDurationX10msecs * 10l);
digitalWrite(_openPinNum, HIGH);
digitalWrite(_closePinNum, HIGH);
}
_stopTimeMsecs = 0;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2389
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1390685 by johtaylo@johtaylo-jtincrementor-increment on 2017/03/25 03:00:05<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2390
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>#include "mep.hpp"
void out_print_address(op_t &x, ea_t /*pc*/)
{
if (!out_name_expr(x, x.addr))
{
OutValue(x, OOF_ADDR | OOF_NUMBER | OOFS_NOSIGN);
QueueSet(Q_noName, cmd.ea);
}
}
void out_print_spreg(op_t &/*x*/, ea_t /*pc*/)
{
out_register("$sp");
}
void out_print_tpreg(op_t &/*x*/, ea_t /*pc*/)
{
out_register("$tp");
}
void make_stack_var(op_t &x)
{
if (may_create_stkvars())
{
adiff_t sp_off = x.value;
if ( ua_stkvar2(x, sp_off, 0) )
op_stkvar(cmd.ea, x.n);
}
}
//--------------------------------------------------------------------------
static int idaapi notify(processor_t::idp_notify msgid, ...) // Various messages:
{
va_list va;
va_start(va, msgid);
// A well behaving processor module should call invoke_callbacks()
// in his notify() function. If this function returns 0, then
// the processor module should process the notification itself
// Otherwise the code should be returned to the caller:
int code = invoke_callbacks(HT_IDP, msgid, va);
if ( code )
return code;
code = 1;
switch ( msgid )
{
case processor_t::loader_elf_machine:
{
linput_t *li = va_arg(va, linput_t *);
int machine_type = va_arg(va, int);
const char **p_procname = va_arg(va, const char **);
(void)li; // unused variable
if (machine_type == 0xF00D)
{
*p_procname = "Toshiba MeP";
code = 0xF00D;
}
else
{
code = 0;
}
}
break;
default:
break;
}
va_end(va);
return code;
}
//--------------------------------------------------------------------------
static void idaapi header(void)
{
}
//--------------------------------------------------------------------------
static void idaapi segstart(ea_t /*ea*/)
{
}
//--------------------------------------------------------------------------
static void idaapi segend(ea_t /*ea*/)
{
}
//--------------------------------------------------------------------------
static void idaapi footer(void)
{
}
//--------------------------------------------------------------------------
static const asm_t mepasm =
{
0,
0,
"MEP assembler",
0,
NULL,
NULL,
".org",
".end",
";", // comment string
'"', // string delimiter
'\'', // char delimiter (no char consts)
"\\\"'", // special symbols in char and string constants
".ascii", // ascii string directive
".byte", // byte directive
".word", // word directive
".dword", // dword (4 bytes)
".qword", // qword (8 bytes)
NULL, // oword (16 bytes)
".float" // float (4 bytes)
".double", // double (8 bytes)
NULL, // tbyte (10/12 bytes)
NULL, // packed decimal real
NULL, // arrays (#h,#d,#v,#s(...)
".block %s", // uninited arrays
".equ", // Equ
NULL, // seg prefix
// preline, NULL, operdim,
NULL, NULL, NULL,
NULL,
NULL,
NULL, // func_header
NULL, // func_footer
NULL, // public
NULL, // weak
NULL, // extrn
NULL, // comm
NULL, // get_type_name
NULL, // align
0, 0, // lbrace, rbrace
NULL, // mod
NULL, // and
NULL, // or
NULL, // xor
NULL, // not
NULL, // shl
NULL, // shr
NULL, // sizeof
};
static const asm_t *const asms[] = { &mepasm, NULL };
//-----------------------------------------------------------------------
static const uchar retcode_1[] = { 0x02, 0x70 };
static const bytes_t retcodes[] =
{
{ sizeof(retcode_1), retcode_1 },
{ 0, NULL }
};
//-----------------------------------------------------------------------
// use simple translation
static ea_t idaapi mep_translate(ea_t base, adiff_t offset)
{
return base+offset;
}
//--------------------------------------------------------------------------
#define FAMILY "Toshiba MeP family:"
static const char *const shnames[] = { "MeP", NULL };
static const char *const lnames[] = { FAMILY"Toshiba MeP C5 media engine", NULL };
//--------------------------------------------------------------------------
//-----------------------------------------------------------------------
// Processor Definition
//-----------------------------------------------------------------------
#define PLFM_MEP 0xF00D
#include "reg.cpp"
idaman processor_t ida_module_data LPH =
{
IDP_INTERFACE_VERSION, // version
PLFM_MEP, // id
PR_USE32
|PRN_HEX
|PR_WORD_INS
|PR_RNAMESOK // can use register names for byte names
|PR_SEGTRANS // segment translation is supported (codeSeg)
|PR_SGROTHER, // the segment registers don't contain
// the segment selectors, something else
8, // 8 bits in a byte for code segments
8, // 8 bits in a byte for other segments
shnames, // short processor names (null term)
lnames, // long processor names (null term)
asms, // array of enabled assemblers
notify, // Various messages:
header, // produce start of text file
footer, // produce end of text file
segstart, // produce start of segment
segend, // produce end of segment
NULL,
ana,
emu,
out,
outop,
mep_data, //intel_data,
NULL, // compare operands
NULL, // can have type
qnumber(RegNames), // Number of registers
RegNames, // Register names
NULL, // get abstract register
0, // Number of register files
NULL, // Register file names
NULL, // Register descriptions
NULL, // Pointer to CPU registers
0,0,
4, // size of a segment register
0,0,
NULL, // No known code start sequences
retcodes,
0, MEP_INSN_RI_26+1,
Instructions,
NULL, // int (*is_far_jump)(int icode);
mep_translate, // Translation function for offsets
0, // int tbyte_size; -- doesn't exist
NULL, // int (*realcvt)(void *m, ushort *e, ushort swt);
{ 0, 0, 0, 0 }, // char real_width[4];
// number of symbols after decimal point
// 2byte float (0-does not exist)
// normal float
// normal double
// long double
NULL, // int (*is_switch)(switch_info_t *si);
NULL, // int32 (*gen_map_file)(FILE *fp);
NULL, // ea_t (*extract_address)(ea_t ea,const char *string,int x);
NULL, // int (*is_sp_based)(op_t &x); -- always, so leave it NULL
NULL, // int (*create_func_frame)(func_t *pfn);
NULL, // int (*get_frame_retsize(func_t *pfn)
NULL, // void (*gen_stkvar_def)(char *buf,const member_t *mptr,int32 v);
gen_spcdef, // Generate text representation of an item in a special segment
MEP_INSN_RET, // Icode of return instruction. It is ok to give any of possible return instructions
NULL, // const char *(*set_idp_options)(const char *keyword,int value_type,const void *value);
NULL, // int (*is_align_insn)(ea_t ea);
NULL, // mvm_t *mvm;
};
<commit_msg>Add error color to bad addresses<commit_after>#include "mep.hpp"
void out_print_address(op_t &x, ea_t /*pc*/)
{
if (!out_name_expr(x, x.addr))
{
out_tagon(COLOR_ERROR);
OutValue(x, OOF_ADDR | OOF_NUMBER | OOFS_NOSIGN);
out_tagoff(COLOR_ERROR);
QueueSet(Q_noName, cmd.ea);
}
}
void out_print_spreg(op_t &/*x*/, ea_t /*pc*/)
{
out_register("$sp");
}
void out_print_tpreg(op_t &/*x*/, ea_t /*pc*/)
{
out_register("$tp");
}
void make_stack_var(op_t &x)
{
if (may_create_stkvars())
{
adiff_t sp_off = x.value;
if ( ua_stkvar2(x, sp_off, 0) )
op_stkvar(cmd.ea, x.n);
}
}
//--------------------------------------------------------------------------
static int idaapi notify(processor_t::idp_notify msgid, ...) // Various messages:
{
va_list va;
va_start(va, msgid);
// A well behaving processor module should call invoke_callbacks()
// in his notify() function. If this function returns 0, then
// the processor module should process the notification itself
// Otherwise the code should be returned to the caller:
int code = invoke_callbacks(HT_IDP, msgid, va);
if ( code )
return code;
code = 1;
switch ( msgid )
{
case processor_t::loader_elf_machine:
{
linput_t *li = va_arg(va, linput_t *);
int machine_type = va_arg(va, int);
const char **p_procname = va_arg(va, const char **);
(void)li; // unused variable
if (machine_type == 0xF00D)
{
*p_procname = "Toshiba MeP";
code = 0xF00D;
}
else
{
code = 0;
}
}
break;
default:
break;
}
va_end(va);
return code;
}
//--------------------------------------------------------------------------
static void idaapi header(void)
{
}
//--------------------------------------------------------------------------
static void idaapi segstart(ea_t /*ea*/)
{
}
//--------------------------------------------------------------------------
static void idaapi segend(ea_t /*ea*/)
{
}
//--------------------------------------------------------------------------
static void idaapi footer(void)
{
}
//--------------------------------------------------------------------------
static const asm_t mepasm =
{
0,
0,
"MEP assembler",
0,
NULL,
NULL,
".org",
".end",
";", // comment string
'"', // string delimiter
'\'', // char delimiter (no char consts)
"\\\"'", // special symbols in char and string constants
".ascii", // ascii string directive
".byte", // byte directive
".word", // word directive
".dword", // dword (4 bytes)
".qword", // qword (8 bytes)
NULL, // oword (16 bytes)
".float" // float (4 bytes)
".double", // double (8 bytes)
NULL, // tbyte (10/12 bytes)
NULL, // packed decimal real
NULL, // arrays (#h,#d,#v,#s(...)
".block %s", // uninited arrays
".equ", // Equ
NULL, // seg prefix
// preline, NULL, operdim,
NULL, NULL, NULL,
NULL,
NULL,
NULL, // func_header
NULL, // func_footer
NULL, // public
NULL, // weak
NULL, // extrn
NULL, // comm
NULL, // get_type_name
NULL, // align
0, 0, // lbrace, rbrace
NULL, // mod
NULL, // and
NULL, // or
NULL, // xor
NULL, // not
NULL, // shl
NULL, // shr
NULL, // sizeof
};
static const asm_t *const asms[] = { &mepasm, NULL };
//-----------------------------------------------------------------------
static const uchar retcode_1[] = { 0x02, 0x70 };
static const bytes_t retcodes[] =
{
{ sizeof(retcode_1), retcode_1 },
{ 0, NULL }
};
//-----------------------------------------------------------------------
// use simple translation
static ea_t idaapi mep_translate(ea_t base, adiff_t offset)
{
return base+offset;
}
//--------------------------------------------------------------------------
#define FAMILY "Toshiba MeP family:"
static const char *const shnames[] = { "MeP", NULL };
static const char *const lnames[] = { FAMILY"Toshiba MeP C5 media engine", NULL };
//--------------------------------------------------------------------------
//-----------------------------------------------------------------------
// Processor Definition
//-----------------------------------------------------------------------
#define PLFM_MEP 0xF00D
#include "reg.cpp"
idaman processor_t ida_module_data LPH =
{
IDP_INTERFACE_VERSION, // version
PLFM_MEP, // id
PR_USE32
|PRN_HEX
|PR_WORD_INS
|PR_RNAMESOK // can use register names for byte names
|PR_SEGTRANS // segment translation is supported (codeSeg)
|PR_SGROTHER, // the segment registers don't contain
// the segment selectors, something else
8, // 8 bits in a byte for code segments
8, // 8 bits in a byte for other segments
shnames, // short processor names (null term)
lnames, // long processor names (null term)
asms, // array of enabled assemblers
notify, // Various messages:
header, // produce start of text file
footer, // produce end of text file
segstart, // produce start of segment
segend, // produce end of segment
NULL,
ana,
emu,
out,
outop,
mep_data, //intel_data,
NULL, // compare operands
NULL, // can have type
qnumber(RegNames), // Number of registers
RegNames, // Register names
NULL, // get abstract register
0, // Number of register files
NULL, // Register file names
NULL, // Register descriptions
NULL, // Pointer to CPU registers
0,0,
4, // size of a segment register
0,0,
NULL, // No known code start sequences
retcodes,
0, MEP_INSN_RI_26+1,
Instructions,
NULL, // int (*is_far_jump)(int icode);
mep_translate, // Translation function for offsets
0, // int tbyte_size; -- doesn't exist
NULL, // int (*realcvt)(void *m, ushort *e, ushort swt);
{ 0, 0, 0, 0 }, // char real_width[4];
// number of symbols after decimal point
// 2byte float (0-does not exist)
// normal float
// normal double
// long double
NULL, // int (*is_switch)(switch_info_t *si);
NULL, // int32 (*gen_map_file)(FILE *fp);
NULL, // ea_t (*extract_address)(ea_t ea,const char *string,int x);
NULL, // int (*is_sp_based)(op_t &x); -- always, so leave it NULL
NULL, // int (*create_func_frame)(func_t *pfn);
NULL, // int (*get_frame_retsize(func_t *pfn)
NULL, // void (*gen_stkvar_def)(char *buf,const member_t *mptr,int32 v);
gen_spcdef, // Generate text representation of an item in a special segment
MEP_INSN_RET, // Icode of return instruction. It is ok to give any of possible return instructions
NULL, // const char *(*set_idp_options)(const char *keyword,int value_type,const void *value);
NULL, // int (*is_align_insn)(ea_t ea);
NULL, // mvm_t *mvm;
};
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <arpa/inet.h>
#include <znc/FileUtils.h>
#include <znc/Server.h>
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <znc/IRCSock.h>
#include <syslog.h>
class CAdminLogMod : public CModule {
public:
MODCONSTRUCTOR(CAdminLogMod) {
AddHelpCommand();
AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnShowCommand), "", "Show the logging target");
AddCommand("Target", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnTargetCommand), "<file|syslog|both>", "Set the logging target");
openlog("znc", LOG_PID, LOG_DAEMON);
}
virtual ~CAdminLogMod() {
Log("Logging ended.");
closelog();
}
CString ResolveIp(const CString ip)
{
struct hostent *hent = nullptr;
struct in_addr addr;
struct in6_addr addr6;
if(inet_pton(AF_INET, ip.c_str(), &addr))
if((hent = gethostbyaddr((char *)&(addr.s_addr), sizeof(addr.s_addr), AF_INET))) {
char *hostname = (char*) malloc(sizeof(char)*strlen(hent->h_name));
strcpy(hostname, hent->h_name);
CString str = CString(hostname);
//free(hostname);
return str;
}
if(inet_pton(AF_INET6, ip.c_str(), &addr6))
if((hent = gethostbyaddr((char *)&(addr6.s6_addr), sizeof(addr6.s6_addr), AF_INET6))) {
char *hostname = (char*) malloc(sizeof(char)*strlen(hent->h_name));
strcpy(hostname, hent->h_name);
CString str = CString(hostname);
//free(hostname);
return str;
}
return ip;
}
bool OnLoad(const CString & sArgs, CString & sMessage) override {
CString sTarget = GetNV("target");
if (sTarget.Equals("syslog"))
m_eLogMode = LOG_TO_SYSLOG;
else if (sTarget.Equals("both"))
m_eLogMode = LOG_TO_BOTH;
else if (sTarget.Equals("file"))
m_eLogMode = LOG_TO_FILE;
else
m_eLogMode = LOG_TO_FILE;
m_sLogFile = GetSavePath() + "/znc.log";
Log("Logging started. ZNC PID[" + CString(getpid()) + "] UID/GID[" + CString(getuid()) + ":" + CString(getgid()) + "]");
return true;
}
void OnIRCConnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] connected to IRC - Host: " + GetNetwork()->GetCurrentServer()->GetName() + " IP: " + CString(GetNetwork()->GetIRCSock()->GetRemoteIP()) + " RDNS: " + ResolveIp(GetNetwork()->GetIRCSock()->GetRemoteIP()));
}
void OnIRCDisconnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC");
}
EModRet OnRaw(CString& sLine) override {
if (sLine.StartsWith("ERROR ")) {
//ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
//ERROR :Closing Link: nick[24.24.24.24] Killer (Local kill by Killer (reason))
CString sError(sLine.substr(6));
if (sError.Left(1) == ":")
sError.LeftChomp();
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC: " +
GetNetwork()->GetCurrentServer()->GetName() + " [" + sError + "]", LOG_NOTICE);
}
return CONTINUE;
}
void OnClientLogin() override {
Log("[" + GetUser()->GetUserName() + "] connected to ZNC from " + GetClient()->GetRemoteIP());
}
void OnClientDisconnect() override {
Log("[" + GetUser()->GetUserName() + "] disconnected from ZNC from " + GetClient()->GetRemoteIP());
}
void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) override {
Log("[" + sUsername + "] failed to login from " + sRemoteIP, LOG_WARNING);
}
void Log(CString sLine, int iPrio = LOG_INFO) {
if (m_eLogMode & LOG_TO_SYSLOG)
syslog(iPrio, "%s", sLine.c_str());
if (m_eLogMode & LOG_TO_FILE) {
time_t curtime;
tm* timeinfo;
char buf[23];
time(&curtime);
timeinfo = localtime(&curtime);
strftime(buf,sizeof(buf),"[%Y-%m-%d %H:%M:%S] ",timeinfo);
CFile LogFile(m_sLogFile);
if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
LogFile.Write(buf + sLine + "\n");
else
DEBUG("Failed to write to [" << m_sLogFile << "]: " << strerror(errno));
}
}
void OnModCommand(const CString& sCommand) override {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
} else {
HandleCommand(sCommand);
}
}
void OnTargetCommand(const CString& sCommand) {
CString sArg = sCommand.Token(1, true);
CString sTarget;
CString sMessage;
LogMode mode;
if (sArg.Equals("file")) {
sTarget = "file";
sMessage = "Now only logging to file";
mode = LOG_TO_FILE;
} else if (sArg.Equals("syslog")) {
sTarget = "syslog";
sMessage = "Now only logging to syslog";
mode = LOG_TO_SYSLOG;
} else if (sArg.Equals("both")) {
sTarget = "both";
sMessage = "Now logging to file and syslog";
mode = LOG_TO_BOTH;
} else {
if (sArg.empty()) {
PutModule("Usage: Target <file|syslog|both>");
} else {
PutModule("Unknown target");
}
return;
}
Log(sMessage);
SetNV("target", sTarget);
m_eLogMode = mode;
PutModule(sMessage);
}
void OnShowCommand(const CString& sCommand) {
CString sTarget;
switch (m_eLogMode)
{
case LOG_TO_FILE:
sTarget = "file";
break;
case LOG_TO_SYSLOG:
sTarget = "syslog";
break;
case LOG_TO_BOTH:
sTarget = "both, file and syslog";
break;
}
PutModule("Logging is enabled for " + sTarget);
if (m_eLogMode != LOG_TO_SYSLOG)
PutModule("Log file will be written to [" + m_sLogFile + "]");
}
private:
enum LogMode {
LOG_TO_FILE = 1 << 0,
LOG_TO_SYSLOG = 1 << 1,
LOG_TO_BOTH = LOG_TO_FILE | LOG_TO_SYSLOG
};
LogMode m_eLogMode;
CString m_sLogFile;
};
template<> void TModInfo<CAdminLogMod>(CModInfo& Info) {
Info.SetWikiPage("adminlog");
}
GLOBALMODULEDEFS(CAdminLogMod, "Log ZNC events to file and/or syslog.")
<commit_msg>Reverted adminlog to upstream<commit_after>/*
* Copyright (C) 2004-2015 ZNC, see the NOTICE file for details.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/FileUtils.h>
#include <znc/Server.h>
#include <znc/IRCNetwork.h>
#include <znc/User.h>
#include <syslog.h>
class CAdminLogMod : public CModule {
public:
MODCONSTRUCTOR(CAdminLogMod) {
AddHelpCommand();
AddCommand("Show", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnShowCommand), "", "Show the logging target");
AddCommand("Target", static_cast<CModCommand::ModCmdFunc>(&CAdminLogMod::OnTargetCommand), "<file|syslog|both>", "Set the logging target");
openlog("znc", LOG_PID, LOG_DAEMON);
}
virtual ~CAdminLogMod() {
Log("Logging ended.");
closelog();
}
bool OnLoad(const CString & sArgs, CString & sMessage) override {
CString sTarget = GetNV("target");
if (sTarget.Equals("syslog"))
m_eLogMode = LOG_TO_SYSLOG;
else if (sTarget.Equals("both"))
m_eLogMode = LOG_TO_BOTH;
else if (sTarget.Equals("file"))
m_eLogMode = LOG_TO_FILE;
else
m_eLogMode = LOG_TO_FILE;
m_sLogFile = GetSavePath() + "/znc.log";
Log("Logging started. ZNC PID[" + CString(getpid()) + "] UID/GID[" + CString(getuid()) + ":" + CString(getgid()) + "]");
return true;
}
void OnIRCConnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] connected to IRC: " + GetNetwork()->GetCurrentServer()->GetName());
}
void OnIRCDisconnected() override {
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC");
}
EModRet OnRaw(CString& sLine) override {
if (sLine.StartsWith("ERROR ")) {
//ERROR :Closing Link: nick[24.24.24.24] (Excess Flood)
//ERROR :Closing Link: nick[24.24.24.24] Killer (Local kill by Killer (reason))
CString sError(sLine.substr(6));
if (sError.Left(1) == ":")
sError.LeftChomp();
Log("[" + GetUser()->GetUserName() + "/" + GetNetwork()->GetName() + "] disconnected from IRC: " +
GetNetwork()->GetCurrentServer()->GetName() + " [" + sError + "]", LOG_NOTICE);
}
return CONTINUE;
}
void OnClientLogin() override {
Log("[" + GetUser()->GetUserName() + "] connected to ZNC from " + GetClient()->GetRemoteIP());
}
void OnClientDisconnect() override {
Log("[" + GetUser()->GetUserName() + "] disconnected from ZNC from " + GetClient()->GetRemoteIP());
}
void OnFailedLogin(const CString& sUsername, const CString& sRemoteIP) override {
Log("[" + sUsername + "] failed to login from " + sRemoteIP, LOG_WARNING);
}
void Log(CString sLine, int iPrio = LOG_INFO) {
if (m_eLogMode & LOG_TO_SYSLOG)
syslog(iPrio, "%s", sLine.c_str());
if (m_eLogMode & LOG_TO_FILE) {
time_t curtime;
tm* timeinfo;
char buf[23];
time(&curtime);
timeinfo = localtime(&curtime);
strftime(buf,sizeof(buf),"[%Y-%m-%d %H:%M:%S] ",timeinfo);
CFile LogFile(m_sLogFile);
if (LogFile.Open(O_WRONLY | O_APPEND | O_CREAT))
LogFile.Write(buf + sLine + "\n");
else
DEBUG("Failed to write to [" << m_sLogFile << "]: " << strerror(errno));
}
}
void OnModCommand(const CString& sCommand) override {
if (!GetUser()->IsAdmin()) {
PutModule("Access denied");
} else {
HandleCommand(sCommand);
}
}
void OnTargetCommand(const CString& sCommand) {
CString sArg = sCommand.Token(1, true);
CString sTarget;
CString sMessage;
LogMode mode;
if (sArg.Equals("file")) {
sTarget = "file";
sMessage = "Now only logging to file";
mode = LOG_TO_FILE;
} else if (sArg.Equals("syslog")) {
sTarget = "syslog";
sMessage = "Now only logging to syslog";
mode = LOG_TO_SYSLOG;
} else if (sArg.Equals("both")) {
sTarget = "both";
sMessage = "Now logging to file and syslog";
mode = LOG_TO_BOTH;
} else {
if (sArg.empty()) {
PutModule("Usage: Target <file|syslog|both>");
} else {
PutModule("Unknown target");
}
return;
}
Log(sMessage);
SetNV("target", sTarget);
m_eLogMode = mode;
PutModule(sMessage);
}
void OnShowCommand(const CString& sCommand) {
CString sTarget;
switch (m_eLogMode)
{
case LOG_TO_FILE:
sTarget = "file";
break;
case LOG_TO_SYSLOG:
sTarget = "syslog";
break;
case LOG_TO_BOTH:
sTarget = "both, file and syslog";
break;
}
PutModule("Logging is enabled for " + sTarget);
if (m_eLogMode != LOG_TO_SYSLOG)
PutModule("Log file will be written to [" + m_sLogFile + "]");
}
private:
enum LogMode {
LOG_TO_FILE = 1 << 0,
LOG_TO_SYSLOG = 1 << 1,
LOG_TO_BOTH = LOG_TO_FILE | LOG_TO_SYSLOG
};
LogMode m_eLogMode;
CString m_sLogFile;
};
template<> void TModInfo<CAdminLogMod>(CModInfo& Info) {
Info.SetWikiPage("adminlog");
}
GLOBALMODULEDEFS(CAdminLogMod, "Log ZNC events to file and/or syslog.")
<|endoftext|> |
<commit_before>#pragma once
#include <type_traits>
#include <iterator>
#include <utility>
namespace helene
{
namespace detail
{
template <class Iterator, class IteratorTag>
constexpr bool is_iterator_of_category_v =
std::is_same<typename std::iterator_traits<Iterator>::iterator_category,
IteratorTag>::value;
template <class Iterator, class IteratorTag>
constexpr bool is_at_least_iterator_of_category_v = std::is_base_of<
IteratorTag,
typename std::iterator_traits<Iterator>::iterator_category>::value;
} // namespace detail
/** \class circular_iterator circular_iterator.hpp <circular_iterator.hpp>
*
* \brief An iterator adaptor that adapts any iterator to wrap around when
* incremented beyond a range determined on construction
*/
template <class UnderlyingIterator>
class circular_iterator
{
public:
static_assert(
detail::is_at_least_iterator_of_category_v<UnderlyingIterator,
std::forward_iterator_tag>,
"UnderlyingIterator needs to at least satisfy ForwardIterator for its "
"multipass ability");
private:
};
} // namespace helene
<commit_msg>Add base class for circular_iterator. modified: include/circular_iterator.hpp<commit_after>#pragma once
#include <type_traits>
#include <iterator>
#include <utility>
namespace helene
{
namespace detail
{
template <class Iterator, class IteratorTag>
constexpr bool is_iterator_of_category_v =
std::is_same<typename std::iterator_traits<Iterator>::iterator_category,
IteratorTag>::value;
template <class Iterator, class IteratorTag>
constexpr bool is_at_least_iterator_of_category_v = std::is_base_of<
IteratorTag,
typename std::iterator_traits<Iterator>::iterator_category>::value;
// undefined base, specialized for each iterator category
template <class UnderlyingIterator, class = void>
class circular_iterator_base;
} // namespace detail
/** \class circular_iterator circular_iterator.hpp <circular_iterator.hpp>
*
* \brief An iterator adaptor that adapts any iterator to wrap around when
* incremented beyond a range determined on construction
*/
template <class UnderlyingIterator>
class circular_iterator
: public detail::circular_iterator_base<UnderlyingIterator>
{
public:
static_assert(
detail::is_at_least_iterator_of_category_v<UnderlyingIterator,
std::forward_iterator_tag>,
"UnderlyingIterator needs to at least satisfy ForwardIterator for its "
"multipass ability");
private:
};
} // namespace helene
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2151
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1286316 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/07/01 03:00:08<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2152
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_CLEMENTI_DIHEDRAL_POTENTIAL
#define MJOLNIR_CLEMENTI_DIHEDRAL_POTENTIAL
#include <mjolnir/core/LocalPotentialBase.hpp>
#include <cmath>
namespace mjolnir
{
/*! @brief Clementi-Go dihedral modified-triple-cosine potential *
* V(phi) = k1 * (1-cos(phi-phi0)) + k3 * (1-cos(3(phi-phi0))) *
* dV/dphi = k1 * sin(phi-phi0) + k3 * 3 * sin(3(phi-phi0)) */
template<typename traitsT>
class ClementiDihedralPotential : public LocalPotentialBase<traitsT>
{
public:
typedef traitsT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
public:
ClementiDihedralPotential(
const real_type k1, const real_type k3, const real_type native_val)
: k1_(k1), k3_(k3), native_val_(native_val)
{}
~ClementiDihedralPotential() override = default;
real_type potential(const real_type val) const override
{
const real_type dphi = val - native_val_;
return k1_ * (1. - cos(dphi)) + k3_ * (1. - cos(3. * dphi));
}
real_type derivative(const real_type val) const override
{
const real_type dphi = val - native_val_;
return k1_ * sin(dphi) + 3. * k3_ * sin(3. * dphi);
}
private:
const real_type k1_;
const real_type k3_;
const real_type native_val_;
};
}
#endif /* MJOLNIR_CLEMENTI_DIHEDRAL_POTENTIAL */
<commit_msg>add namespace std:: to ClementiDihedralPotential<commit_after>#ifndef MJOLNIR_CLEMENTI_DIHEDRAL_POTENTIAL
#define MJOLNIR_CLEMENTI_DIHEDRAL_POTENTIAL
#include <mjolnir/core/LocalPotentialBase.hpp>
#include <cmath>
namespace mjolnir
{
/*! @brief Clementi-Go dihedral modified-triple-cosine potential *
* V(phi) = k1 * (1-cos(phi-phi0)) + k3 * (1-cos(3(phi-phi0))) *
* dV/dphi = k1 * sin(phi-phi0) + k3 * 3 * sin(3(phi-phi0)) */
template<typename traitsT>
class ClementiDihedralPotential : public LocalPotentialBase<traitsT>
{
public:
typedef traitsT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
public:
ClementiDihedralPotential(
const real_type k1, const real_type k3, const real_type native_val)
: k1_(k1), k3_(k3), native_val_(native_val)
{}
~ClementiDihedralPotential() override = default;
real_type potential(const real_type val) const override
{
const real_type dphi = val - native_val_;
return k1_ * (1. - std::cos(dphi)) + k3_ * (1. - std::cos(3. * dphi));
}
real_type derivative(const real_type val) const override
{
const real_type dphi = val - native_val_;
return k1_ * std::sin(dphi) + 3. * k3_ * std::sin(3. * dphi);
}
private:
const real_type k1_;
const real_type k3_;
const real_type native_val_;
};
}
#endif /* MJOLNIR_CLEMENTI_DIHEDRAL_POTENTIAL */
<|endoftext|> |
<commit_before>#pragma once
#include "CSingleton.hpp"
#include "sdk.hpp"
#include <string>
#include <unordered_set>
#include <memory>
using std::string;
using std::unordered_set;
#include "CError.hpp"
using Callback_t = std::shared_ptr<class CCallback>;
class CCallback
{
public: //type definitions
enum class Error
{
NONE,
INVALID_AMX,
INVALID_PARAMETERS,
INVALID_PARAM_COUNT,
INVALID_FORMAT_SPECIFIER,
EMPTY_NAME,
NOT_FOUND,
EXPECTED_ARRAY_SIZE,
INVALID_ARRAY_SIZE,
NO_ARRAY_SIZE,
};
static const string ModuleName;
public: //constructor / destructor
CCallback(AMX *amx, int cb_idx) :
m_AmxInstance(amx),
m_AmxCallbackIndex(cb_idx)
{ }
~CCallback() = default;
private: //variables
AMX *m_AmxInstance = nullptr;
int m_AmxCallbackIndex = -1;
cell m_AmxPushAddress = -1;
private: // functions
// cell
template<typename... Tv>
void PushArgs(cell value, Tv... other_values)
{
PushArgs(other_values...);
amx_Push(m_AmxInstance, value);
}
// C string
template<typename... Tv>
void PushArgs(const char *value, Tv... other_values)
{
PushArgs(other_values...);
cell tmp_addr;
amx_PushString(m_AmxInstance, &tmp_addr, nullptr, value, 0, 0);
if (m_AmxPushAddress < 0)
m_AmxPushAddress = tmp_addr;
}
// std string
template<typename... Tv>
void PushArgs(std::string const &value, Tv... other_values)
{
PushArgs(other_values...);
cell tmp_addr;
amx_PushString(m_AmxInstance, &tmp_addr, nullptr, value.c_str(), 0, 0);
if (m_AmxPushAddress < 0)
m_AmxPushAddress = tmp_addr;
}
// cell array
template<size_t N, typename... Tv>
void PushArgs(const cell(&array)[N], Tv... other_values)
{
PushArgs(other_values...);
cell tmp_addr;
amx_PushArray(m_AmxInstance, &tmp_addr, nullptr, array, N);
if (m_AmxPushAddress < 0)
m_AmxPushAddress = tmp_addr;
}
// reference
template<size_t N, typename... Tv>
void PushArgs(cell *value, Tv... other_values)
{
PushArgs(other_values...);
amx_PushAddress(m_AmxInstance, value);
}
void PushArgs()
{ }
public: //functions
bool Execute();
template<typename... Tv>
bool Execute(Tv... params)
{
PushArgs(params...);
return Execute();
}
public: //factory functions
static Callback_t Create(CError<CCallback> &error, AMX *amx, const char *name);
};
class CCallbackManager : public CSingleton<CCallbackManager>
{
friend class CSingleton<CCallbackManager>;
private: //constructor / destructor
CCallbackManager() = default;
~CCallbackManager() = default;
private: //variables
unordered_set<const AMX *> m_AmxInstances;
public: //functions
inline bool IsValidAmx(const AMX *amx)
{
return m_AmxInstances.count(amx) == 1;
}
inline void AddAmx(const AMX *amx)
{
m_AmxInstances.insert(amx);
}
inline void RemoveAmx(const AMX *amx)
{
m_AmxInstances.erase(amx);
}
};
<commit_msg>fix forwarding<commit_after>#pragma once
#include "CSingleton.hpp"
#include "sdk.hpp"
#include <string>
#include <unordered_set>
#include <memory>
using std::string;
using std::unordered_set;
#include "CError.hpp"
using Callback_t = std::shared_ptr<class CCallback>;
class CCallback
{
public: //type definitions
enum class Error
{
NONE,
INVALID_AMX,
INVALID_PARAMETERS,
INVALID_PARAM_COUNT,
INVALID_FORMAT_SPECIFIER,
EMPTY_NAME,
NOT_FOUND,
EXPECTED_ARRAY_SIZE,
INVALID_ARRAY_SIZE,
NO_ARRAY_SIZE,
};
static const string ModuleName;
public: //constructor / destructor
CCallback(AMX *amx, int cb_idx) :
m_AmxInstance(amx),
m_AmxCallbackIndex(cb_idx)
{ }
~CCallback() = default;
private: //variables
AMX *m_AmxInstance = nullptr;
int m_AmxCallbackIndex = -1;
cell m_AmxPushAddress = -1;
private: // functions
// cell
template<typename... Tv>
void PushArgs(cell value, Tv&&... other_values)
{
PushArgs(std::forward<Tv>(other_values)...);
amx_Push(m_AmxInstance, value);
}
// C string
template<typename... Tv>
void PushArgs(const char *value, Tv&&... other_values)
{
PushArgs(std::forward<Tv>(other_values)...);
cell tmp_addr;
amx_PushString(m_AmxInstance, &tmp_addr, nullptr, value, 0, 0);
if (m_AmxPushAddress < 0)
m_AmxPushAddress = tmp_addr;
}
// std string
template<typename... Tv>
void PushArgs(std::string const &value, Tv&&... other_values)
{
PushArgs(std::forward<Tv>(other_values)...);
cell tmp_addr;
amx_PushString(m_AmxInstance, &tmp_addr, nullptr, value.c_str(), 0, 0);
if (m_AmxPushAddress < 0)
m_AmxPushAddress = tmp_addr;
}
// cell array
template<size_t N, typename... Tv>
void PushArgs(const cell(&array)[N], Tv&&... other_values)
{
PushArgs(std::forward<Tv>(other_values)...);
cell tmp_addr;
amx_PushArray(m_AmxInstance, &tmp_addr, nullptr, array, N);
if (m_AmxPushAddress < 0)
m_AmxPushAddress = tmp_addr;
}
// reference
template<size_t N, typename... Tv>
void PushArgs(cell *value, Tv&&... other_values)
{
PushArgs(std::forward<Tv>(other_values)...);
amx_PushAddress(m_AmxInstance, value);
}
void PushArgs()
{ }
public: //functions
bool Execute();
template<typename... Tv>
bool Execute(Tv&&... params)
{
PushArgs(std::forward<Tv>(params)...);
return Execute();
}
public: //factory functions
static Callback_t Create(CError<CCallback> &error, AMX *amx, const char *name);
};
class CCallbackManager : public CSingleton<CCallbackManager>
{
friend class CSingleton<CCallbackManager>;
private: //constructor / destructor
CCallbackManager() = default;
~CCallbackManager() = default;
private: //variables
unordered_set<const AMX *> m_AmxInstances;
public: //functions
inline bool IsValidAmx(const AMX *amx)
{
return m_AmxInstances.count(amx) == 1;
}
inline void AddAmx(const AMX *amx)
{
m_AmxInstances.insert(amx);
}
inline void RemoveAmx(const AMX *amx)
{
m_AmxInstances.erase(amx);
}
};
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "runtime/indexing/value_index_builder.h"
namespace zorba {
bool ValueIndexInsertSessionOpener::nextImpl(store::Item_t& result, PlanState& planState) const
{
bool status;
ValueIndex_t index;
PlanIteratorState *state;
ValueIndexInsertSession_t session;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
status = consumeNext(result, theChild, planState);
ZORBA_ASSERT(status);
index = planState.sctx()->lookup_index(result->getStringValueP());
session = index->createBulkInsertSession();
// TODO - Add to dynamic context.
STACK_END (state);
}
bool ValueIndexInsertSessionCloser::nextImpl(store::Item_t& result, PlanState& planState) const
{
bool status;
ValueIndexInsertSession_t index;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
status = consumeNext(result, theChild, planState);
ZORBA_ASSERT(status);
// TODO - look in dynamic context
//index = planState.sctx()->lookup_index(result->getStringValueP());
//index->commitBulkInsertSession();
STACK_END (state);
}
void ValueIndexBuilderState::init(PlanState& state)
{
PlanIteratorState::init(state);
theSession = NULL;
}
void ValueIndexBuilderState::reset(PlanState& state)
{
PlanIteratorState::reset(state);
theSession = NULL;
}
bool ValueIndexBuilder::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t dValue;
store::IndexKey key;
ValueIndexBuilderState *state;
DEFAULT_STACK_INIT(ValueIndexBuilderState, state, planState);
if (state->theSession == NULL) {
store::Item_t iName;
consumeNext(iName, theChildren[0], planState);
// TODO Look in dynamic context for the session
// state->theIndex = planState.sctx()->lookup_index(iName->getStringValueP());
}
consumeNext(dValue, theChildren[1], planState);
for(unsigned int i = 1; i < theChildren.size(); ++i) {
store::Item_t cValue;
key.push_back(consumeNext(cValue, theChildren[i], planState) ? cValue : NULL);
}
state->theSession->getBulkInsertSession()->receive(key, dValue);
STACK_END (state);
}
}
/* vim:set ts=2 sw=2: */
<commit_msg>Fixed runtime for indexing to manipulate the dynamic context<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "runtime/indexing/value_index_builder.h"
namespace zorba {
bool ValueIndexInsertSessionOpener::nextImpl(store::Item_t& result, PlanState& planState) const
{
bool status;
ValueIndex_t index;
PlanIteratorState *state;
ValueIndexInsertSession_t session;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
status = consumeNext(result, theChild, planState);
ZORBA_ASSERT(status);
index = planState.sctx()->lookup_index(result->getStringValueP());
session = index->createBulkInsertSession();
planState.dctx()->set_val_idx_insert_session(result->getStringValueP(), session);
STACK_END (state);
}
bool ValueIndexInsertSessionCloser::nextImpl(store::Item_t& result, PlanState& planState) const
{
bool status;
ValueIndexInsertSession_t session;
PlanIteratorState *state;
DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
status = consumeNext(result, theChild, planState);
ZORBA_ASSERT(status);
session = planState.dctx()->get_val_idx_insert_session(result->getStringValueP());
session->commitBulkInsertSession();
STACK_END (state);
}
void ValueIndexBuilderState::init(PlanState& state)
{
PlanIteratorState::init(state);
theSession = NULL;
}
void ValueIndexBuilderState::reset(PlanState& state)
{
PlanIteratorState::reset(state);
theSession = NULL;
}
bool ValueIndexBuilder::nextImpl(store::Item_t& result, PlanState& planState) const
{
store::Item_t dValue;
store::IndexKey key;
ValueIndexBuilderState *state;
DEFAULT_STACK_INIT(ValueIndexBuilderState, state, planState);
if (state->theSession == NULL) {
store::Item_t iName;
consumeNext(iName, theChildren[0], planState);
state->theSession = planState.dctx()->get_val_idx_insert_session(iName->getStringValueP());
}
consumeNext(dValue, theChildren[1], planState);
for(unsigned int i = 1; i < theChildren.size(); ++i) {
store::Item_t cValue;
key.push_back(consumeNext(cValue, theChildren[i], planState) ? cValue : NULL);
}
state->theSession->getBulkInsertSession()->receive(key, dValue);
STACK_END (state);
}
}
/* vim:set ts=2 sw=2: */
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include <realm/db.hpp>
#include <future>
#include <windows.h>
namespace realm {
namespace _impl {
class RealmCoordinator;
namespace win32 {
// #if REALM_WINDOWS
#define OpenFileMappingInternal(dwDesiredAccess, bInheritHandle, lpName)\
OpenFileMappingW(dwDesiredAccess, bInheritHandle, lpName);
#define CreateFileMappingInternal(hFile, lpFileMappingAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName)\
CreateFileMappingW(hFile, lpFileMappingAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName);
#define MapViewOfFileInternal(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap)\
MapViewOfFile(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap);
// // #elif REALM_UWP
// // #define OpenFileMappingInternal(dwDesiredAccess, bInheritHandle, lpName)\
// // OpenFileMappingFromApp(dwDesiredAccess, bInheritHandle, lpName);
// // #define CreateFileMappingInternal(hFile, lpFileMappingAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName)\
// // CreateFileMappingFromApp(hFile, lpFileMappingAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName);
// // #define MapViewOfFileInternal(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap)\
// // MapViewOfFileFromApp(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap);
// #elif
// #error Unknown win32 platform
// #endif
template <class T, void (*Initializer)(T&)>
class SharedMemory {
public:
SharedMemory(LPCWSTR name) {
//assume another process have already initialzied the shared memory
bool shouldInit = false;
HANDLE mapping = OpenFileMappingInternal(FILE_MAP_ALL_ACCESS, FALSE, name);
auto error = GetLastError();
if (mapping == NULL) {
mapping = CreateFileMappingInternal(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(T), name);
error = GetLastError();
//init since this is the first process creating the shared memory
shouldInit = true;
}
if (mapping == NULL) {
throw std::system_error(error, std::system_category());
}
LPVOID view = MapViewOfFileInternal(mapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(T));
error = GetLastError();
if (view == NULL) {
throw std::system_error(error, std::system_category());
}
m_memory = reinterpret_cast<T*>(view);
if (shouldInit) {
try {
Initializer(get());
}
catch (...) {
UnmapViewOfFile(m_memory);
throw;
}
}
}
T& get() const noexcept { return *m_memory; }
~SharedMemory() {
if (m_memory) {
UnmapViewOfFile(m_memory);
m_memory = nullptr;
}
}
private:
T* m_memory = nullptr;
};
}
class ExternalCommitHelper {
public:
ExternalCommitHelper(RealmCoordinator& parent);
~ExternalCommitHelper();
void notify_others();
private:
void listen();
RealmCoordinator& m_parent;
// The listener thread
std::future<void> m_thread;
win32::SharedMemory<util::InterprocessCondVar::SharedPart, util::InterprocessCondVar::init_shared_part> m_condvar_shared;
util::InterprocessCondVar m_commit_available;
util::InterprocessMutex m_mutex;
bool m_keep_listening = true;
};
} // namespace _impl
} // namespace realm
<commit_msg>remove platform defines<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include <realm/db.hpp>
#include <future>
#include <windows.h>
namespace realm {
namespace _impl {
class RealmCoordinator;
namespace win32 {
template <class T, void (*Initializer)(T&)>
class SharedMemory {
public:
SharedMemory(LPCWSTR name) {
//assume another process have already initialzied the shared memory
bool shouldInit = false;
HANDLE mapping = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, name);
auto error = GetLastError();
if (mapping == NULL) {
mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(T), name);
error = GetLastError();
//init since this is the first process creating the shared memory
shouldInit = true;
}
if (mapping == NULL) {
throw std::system_error(error, std::system_category());
}
LPVOID view = MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(T));
error = GetLastError();
if (view == NULL) {
throw std::system_error(error, std::system_category());
}
m_memory = reinterpret_cast<T*>(view);
if (shouldInit) {
try {
Initializer(get());
}
catch (...) {
UnmapViewOfFile(m_memory);
throw;
}
}
}
T& get() const noexcept { return *m_memory; }
~SharedMemory() {
if (m_memory) {
UnmapViewOfFile(m_memory);
m_memory = nullptr;
}
}
private:
T* m_memory = nullptr;
};
}
class ExternalCommitHelper {
public:
ExternalCommitHelper(RealmCoordinator& parent);
~ExternalCommitHelper();
void notify_others();
private:
void listen();
RealmCoordinator& m_parent;
// The listener thread
std::future<void> m_thread;
win32::SharedMemory<util::InterprocessCondVar::SharedPart, util::InterprocessCondVar::init_shared_part> m_condvar_shared;
util::InterprocessCondVar m_commit_available;
util::InterprocessMutex m_mutex;
bool m_keep_listening = true;
};
} // namespace _impl
} // namespace realm
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2350
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1367051 by johtaylo@johtaylo-jtincrementor-increment on 2017/01/30 03:00:06<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2351
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/*
* simple_parser.hpp - Parser that only splits the command arguments and
* supports quoted strings
*
* Copyright 2010-2011 Jesús Torres <jmtorres@ull.es>
*
* 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.
*/
#ifndef SIMPLE_PARSER_HPP_
#define SIMPLE_PARSER_HPP_
#include <ostream>
#include <string>
#include <vector>
#include <libintl.h> // TODO: To use Boost.Locale when available
#define translate(str) ::gettext(str)
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/home/phoenix/object/construct.hpp>
#include <boost/spirit/home/phoenix/operator/if_else.hpp>
#include <boost/spirit/include/qi.hpp>
#include <cli/boost_parser_base.hpp>
namespace cli { namespace parser
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
//
// Class SimpleParser
//
template <typename Iterator>
struct SimpleParser
: BoostParserBase<Iterator, std::vector<std::string>(), ascii::space_type>
{
typedef SimpleParser<Iterator> Type;
SimpleParser() : SimpleParser::base_type(start)
{
using qi::_2;
using qi::_3;
using qi::_4;
using qi::eoi;
using qi::fail;
using qi::lexeme;
using qi::on_error;
using ascii::char_;
using ascii::space;
using phoenix::construct;
using phoenix::val;
eol = eoi;
character %= char_;
escape %= '\\' > character;
word %= lexeme[+(escape | (char_ - space))];
quotedString %= lexeme['\'' >> *(char_ - '\'') > '\''];
doubleQuotedString %= lexeme['"' >> *(char_ - '"') > '"'];
argument %= quotedString | doubleQuotedString | word;
start = +argument > eol;
character.name(translate("character"));
eol.name(translate("end-of-line"));
on_error<fail>(
start,
std::cerr
<< val(translate("parse error, expecting"))
<< val(" ")
<< _4
<< val(" ")
<< val(translate("at"))
<< val(": ")
<< if_else(_3 == _2, val(translate("<end-of-line>")),
construct<std::string>(_3, _2))
<< std::endl
);
// BOOST_SPIRIT_DEBUG_NODE(word);
// BOOST_SPIRIT_DEBUG_NODE(quotedString);
// BOOST_SPIRIT_DEBUG_NODE(doubleQuotedString);
// BOOST_SPIRIT_DEBUG_NODE(argument);
BOOST_SPIRIT_DEBUG_NODE(start);
}
qi::rule<Iterator> eol;
qi::rule<Iterator, char()> character;
qi::rule<Iterator, char()> escape;
qi::rule<Iterator, std::string(), ascii::space_type> word;
qi::rule<Iterator, std::string(), ascii::space_type> quotedString;
qi::rule<Iterator, std::string(), ascii::space_type> doubleQuotedString;
qi::rule<Iterator, std::string(), ascii::space_type> argument;
qi::rule<Iterator, std::vector<std::string>(), ascii::space_type> start;
};
}}
#endif /* SIMPLE_PARSER_HPP_ */
<commit_msg>fix bug compiling using SimpleParser parser<commit_after>/*
* simple_parser.hpp - Parser that only splits the command arguments and
* supports quoted strings
*
* Copyright 2010-2011 Jesús Torres <jmtorres@ull.es>
*
* 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.
*/
#ifndef SIMPLE_PARSER_HPP_
#define SIMPLE_PARSER_HPP_
#include <cerrno>
#include <iostream>
#include <string>
#include <vector>
#include <libintl.h> // TODO: To use Boost.Locale when available
#define translate(str) ::gettext(str)
//#define BOOST_SPIRIT_DEBUG
#include <boost/spirit/home/phoenix/object/construct.hpp>
#include <boost/spirit/home/phoenix/operator/if_else.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/qi.hpp>
#include <cli/boost_parser_base.hpp>
namespace cli { namespace parser
{
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;
//
// Class SimpleParser
//
template <typename Iterator>
struct SimpleParser
: BoostParserBase<Iterator, std::vector<std::string>(), ascii::space_type>
{
typedef SimpleParser<Iterator> Type;
SimpleParser() : SimpleParser::base_type(start)
{
using qi::_2;
using qi::_3;
using qi::_4;
using qi::eoi;
using qi::fail;
using qi::lexeme;
using qi::on_error;
using ascii::char_;
using ascii::space;
using phoenix::construct;
using phoenix::val;
eol = eoi;
character %= char_;
escape %= '\\' > character;
word %= lexeme[+(escape | (char_ - space))];
quotedString %= lexeme['\'' >> *(char_ - '\'') > '\''];
doubleQuotedString %= lexeme['"' >> *(char_ - '"') > '"'];
argument %= quotedString | doubleQuotedString | word;
start = +argument > eol;
character.name(translate("character"));
eol.name(translate("end-of-line"));
on_error<fail>(
start,
std::cerr
<< val(::program_invocation_short_name)
<< val(": ")
<< val(translate("parse error, expecting"))
<< val(" ")
<< _4
<< val(" ")
<< val(translate("at"))
<< val(": ")
<< if_else(_3 == _2, val(translate("<end-of-line>")),
construct<std::string>(_3, _2))
<< std::endl
);
// BOOST_SPIRIT_DEBUG_NODE(word);
// BOOST_SPIRIT_DEBUG_NODE(quotedString);
// BOOST_SPIRIT_DEBUG_NODE(doubleQuotedString);
// BOOST_SPIRIT_DEBUG_NODE(argument);
BOOST_SPIRIT_DEBUG_NODE(start);
}
qi::rule<Iterator> eol;
qi::rule<Iterator, char()> character;
qi::rule<Iterator, char()> escape;
qi::rule<Iterator, std::string(), ascii::space_type> word;
qi::rule<Iterator, std::string(), ascii::space_type> quotedString;
qi::rule<Iterator, std::string(), ascii::space_type> doubleQuotedString;
qi::rule<Iterator, std::string(), ascii::space_type> argument;
qi::rule<Iterator, std::vector<std::string>(), ascii::space_type> start;
};
}}
#endif /* SIMPLE_PARSER_HPP_ */
<|endoftext|> |
<commit_before>/*
* ArcScripts for ArcEmu MMORPG Server
* Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/>
* Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/>
* Copyright (C) 2008 WEmu Team
* Copyright (C) 2009 WhyScripts Team <http://www.whydb.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
class Lady_Jaina : public GossipScript
{
public:
void GossipHello(Object* pObject, Player* plr)
{
GossipMenu* Menu;
if(plr->GetQuestLogForEntry(558))
{
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7012, plr);
Menu->AddItem(0, "Lady Jaina, this may sound like an odd request... but I have a young ward who is quite shy. You are a hero to him, and he asked me to get your autograph.", 1);
Menu->SendTo(plr);
}
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* Code)
{
Creature* pCreature = (pObject->IsCreature()) ? (TO_CREATURE(pObject)) : NULL;
if(pObject == NULL)
return;
switch(IntId)
{
case 0: // Return to start
GossipHello(pCreature, plr);
break;
case 1: // Give Item
{
plr->CastSpell(plr, dbcSpell.LookupEntry(23122), true);
plr->Gossip_Complete();
break;
}
break;
}
}
};
class Cairne : public GossipScript
{
public:
void GossipHello(Object* pObject, Player* plr)
{
GossipMenu* Menu;
if(plr->GetQuestLogForEntry(925))
{
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7013, plr);
Menu->AddItem(0, "Give me hoofprint.", 1);
Menu->SendTo(plr);
}
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* Code)
{
GossipMenu* Menu;
Creature* pCreature = (pObject->IsCreature()) ? (TO_CREATURE(pObject)) : NULL;
if(pObject == NULL)
return;
switch(IntId)
{
case 0: // Return to start
GossipHello(pCreature, plr);
break;
case 1: // Give Item
{
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7014, plr);
Menu->SendTo(plr);
plr->CastSpell(plr, dbcSpell.LookupEntry(23123), true);
break;
}
break;
}
}
};
#define TELEPORT_SPELL 68328
class TeleportQ_Gossip : public GossipScript
{
public:
void GossipHello( Object* pObject, Player* plr )
{
uint32 Text = objmgr.GetGossipTextForNpc(TO_CREATURE(pObject)->GetEntry());
// check if there is a entry in the db
if ( NpcTextStorage.LookupEntry(Text) == NULL ) { return; }
Arcemu::Gossip::Menu menu(pObject->GetGUID(), Text, plr->GetSession()->language);
sQuestMgr.FillQuestMenu(TO_CREATURE(pObject), plr, menu);
// Requirements:
// one of these quests: 12791, 12794, 12796
// and item 39740: Kirin Tor Signet
if ( ( plr->HasQuest(12791) || plr->HasQuest(12794) || plr->HasQuest(12796) ) && plr->HasItemCount(39740, 1, false) )
{
menu.AddItem(0, "Teleport me to dalaran.", 1);
}
menu.Send(plr);
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* Code)
{
if( IntId == 1 )
{
plr->CastSpell(plr, TELEPORT_SPELL, true);
}
plr->Gossip_Complete();
}
};
void SetupQuestGossip(ScriptMgr* mgr)
{
GossipScript* LJ = new Lady_Jaina();
GossipScript* CB = new Cairne();
mgr->register_gossip_script(4968, LJ);
mgr->register_gossip_script(3057, CB);
// **** Dalaran quests start **** //
GossipScript* TeleportQGossip = new TeleportQ_Gossip;
// Horde
mgr->register_gossip_script(26471, TeleportQGossip);
mgr->register_gossip_script(29155, TeleportQGossip);
mgr->register_gossip_script(29159, TeleportQGossip);
mgr->register_gossip_script(29160, TeleportQGossip);
mgr->register_gossip_script(29162, TeleportQGossip);
// Alliance
mgr->register_gossip_script(23729, TeleportQGossip);
mgr->register_gossip_script(26673, TeleportQGossip);
mgr->register_gossip_script(27158, TeleportQGossip);
mgr->register_gossip_script(29158, TeleportQGossip);
mgr->register_gossip_script(29161, TeleportQGossip);
// Both
mgr->register_gossip_script(29169, TeleportQGossip);
// **** Dalaran Quests end **** //
}
<commit_msg>Dalaran not dalaran<commit_after>/*
* ArcScripts for ArcEmu MMORPG Server
* Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/>
* Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/>
* Copyright (C) 2008 WEmu Team
* Copyright (C) 2009 WhyScripts Team <http://www.whydb.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Setup.h"
class Lady_Jaina : public GossipScript
{
public:
void GossipHello(Object* pObject, Player* plr)
{
GossipMenu* Menu;
if(plr->GetQuestLogForEntry(558))
{
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7012, plr);
Menu->AddItem(0, "Lady Jaina, this may sound like an odd request... but I have a young ward who is quite shy. You are a hero to him, and he asked me to get your autograph.", 1);
Menu->SendTo(plr);
}
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* Code)
{
Creature* pCreature = (pObject->IsCreature()) ? (TO_CREATURE(pObject)) : NULL;
if(pObject == NULL)
return;
switch(IntId)
{
case 0: // Return to start
GossipHello(pCreature, plr);
break;
case 1: // Give Item
{
plr->CastSpell(plr, dbcSpell.LookupEntry(23122), true);
plr->Gossip_Complete();
break;
}
break;
}
}
};
class Cairne : public GossipScript
{
public:
void GossipHello(Object* pObject, Player* plr)
{
GossipMenu* Menu;
if(plr->GetQuestLogForEntry(925))
{
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7013, plr);
Menu->AddItem(0, "Give me hoofprint.", 1);
Menu->SendTo(plr);
}
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* Code)
{
GossipMenu* Menu;
Creature* pCreature = (pObject->IsCreature()) ? (TO_CREATURE(pObject)) : NULL;
if(pObject == NULL)
return;
switch(IntId)
{
case 0: // Return to start
GossipHello(pCreature, plr);
break;
case 1: // Give Item
{
objmgr.CreateGossipMenuForPlayer(&Menu, pObject->GetGUID(), 7014, plr);
Menu->SendTo(plr);
plr->CastSpell(plr, dbcSpell.LookupEntry(23123), true);
break;
}
break;
}
}
};
#define TELEPORT_SPELL 68328
class TeleportQ_Gossip : public GossipScript
{
public:
void GossipHello( Object* pObject, Player* plr )
{
uint32 Text = objmgr.GetGossipTextForNpc(TO_CREATURE(pObject)->GetEntry());
// check if there is a entry in the db
if ( NpcTextStorage.LookupEntry(Text) == NULL ) { return; }
Arcemu::Gossip::Menu menu(pObject->GetGUID(), Text, plr->GetSession()->language);
sQuestMgr.FillQuestMenu(TO_CREATURE(pObject), plr, menu);
// Requirements:
// one of these quests: 12791, 12794, 12796
// and item 39740: Kirin Tor Signet
if ( ( plr->HasQuest(12791) || plr->HasQuest(12794) || plr->HasQuest(12796) ) && plr->HasItemCount(39740, 1, false) )
{
menu.AddItem(0, "Teleport me to Dalaran.", 1);
}
menu.Send(plr);
}
void GossipSelectOption(Object* pObject, Player* plr, uint32 Id, uint32 IntId, const char* Code)
{
if( IntId == 1 )
{
plr->CastSpell(plr, TELEPORT_SPELL, true);
}
plr->Gossip_Complete();
}
};
void SetupQuestGossip(ScriptMgr* mgr)
{
GossipScript* LJ = new Lady_Jaina();
GossipScript* CB = new Cairne();
mgr->register_gossip_script(4968, LJ);
mgr->register_gossip_script(3057, CB);
// **** Dalaran quests start **** //
GossipScript* TeleportQGossip = new TeleportQ_Gossip;
// Horde
mgr->register_gossip_script(26471, TeleportQGossip);
mgr->register_gossip_script(29155, TeleportQGossip);
mgr->register_gossip_script(29159, TeleportQGossip);
mgr->register_gossip_script(29160, TeleportQGossip);
mgr->register_gossip_script(29162, TeleportQGossip);
// Alliance
mgr->register_gossip_script(23729, TeleportQGossip);
mgr->register_gossip_script(26673, TeleportQGossip);
mgr->register_gossip_script(27158, TeleportQGossip);
mgr->register_gossip_script(29158, TeleportQGossip);
mgr->register_gossip_script(29161, TeleportQGossip);
// Both
mgr->register_gossip_script(29169, TeleportQGossip);
// **** Dalaran Quests end **** //
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <Context.h>
#include <A3t.h>
Context context;
////////////////////////////////////////////////////////////////////////////////
int main (int argc, const char** argv)
{
try
{
// Prepare the Context object.
A3t a3t;
a3t.initialize (argc, argv);
// Reports.
a3t.entity ("report", "list");
a3t.entity ("report", "next");
// Read-only commands.
a3t.entity ("readcmd", "export");
a3t.entity ("readcmd", "info");
a3t.entity ("readcmd", "list");
a3t.entity ("readcmd", "next");
a3t.entity ("readcmd", "projects");
// Write commands.
a3t.entity ("writecmd", "add");
a3t.entity ("writecmd", "annotate");
a3t.entity ("writecmd", "delete");
a3t.entity ("writecmd", "denotate");
a3t.entity ("writecmd", "done");
a3t.entity ("writecmd", "modify");
a3t.entity ("writecmd", "start");
a3t.entity ("writecmd", "stop");
// Special commands.
a3t.entity ("specialcmd", "calendar");
a3t.entity ("specialcmd", "edit");
a3t.entity ("writecmd", "import");
// Helper commands.
a3t.entity ("helper", "_get");
a3t.entity ("helper", "_query");
a3t.entity ("helper", "_ids");
a3t.entity ("helper", "_uuids");
a3t.entity ("helper", "_zshids");
a3t.entity ("helper", "_zshuuids");
// Attributes (columns).
a3t.entity ("attribute", "description");
a3t.entity ("attribute", "due");
a3t.entity ("attribute", "duration"); // UDAs are included.
a3t.entity ("attribute", "end");
a3t.entity ("attribute", "entry");
a3t.entity ("attribute", "priority");
a3t.entity ("attribute", "project");
a3t.entity ("attribute", "scheduled");
a3t.entity ("attribute", "start");
a3t.entity ("attribute", "uuid");
a3t.entity ("attribute", "wait");
// Pseudo-attributes.
a3t.entity ("pseudo", "limit");
// UDAs.
a3t.entity ("uda", "duration");
// Modifiers.
a3t.entity ("modifier", "before");
a3t.entity ("modifier", "under");
a3t.entity ("modifier", "below");
a3t.entity ("modifier", "after");
a3t.entity ("modifier", "over");
a3t.entity ("modifier", "above");
a3t.entity ("modifier", "none");
a3t.entity ("modifier", "any");
a3t.entity ("modifier", "is");
a3t.entity ("modifier", "equals");
a3t.entity ("modifier", "isnt");
a3t.entity ("modifier", "not");
a3t.entity ("modifier", "has");
a3t.entity ("modifier", "contains");
a3t.entity ("modifier", "hasnt");
a3t.entity ("modifier", "startswith");
a3t.entity ("modifier", "left");
a3t.entity ("modifier", "endswith");
a3t.entity ("modifier", "right");
a3t.entity ("modifier", "word");
a3t.entity ("modifier", "noword");
// Operators.
a3t.entity ("operator", "and");
a3t.entity ("operator", "or");
a3t.entity ("operator", "xor");
a3t.entity ("operator", "<=");
a3t.entity ("operator", ">=");
a3t.entity ("operator", "!~");
a3t.entity ("operator", "!=");
a3t.entity ("operator", "==");
a3t.entity ("operator", "=");
a3t.entity ("operator", ">");
a3t.entity ("operator", "~");
a3t.entity ("operator", "!");
a3t.entity ("operator", "_hastag_");
a3t.entity ("operator", "_notag_");
a3t.entity ("operator", "-");
a3t.entity ("operator", "*");
a3t.entity ("operator", "/");
a3t.entity ("operator", "+");
a3t.entity ("operator", "-");
a3t.entity ("operator", "<");
a3t.entity ("operator", "(");
a3t.entity ("operator", ")");
a3t.entity ("operator", "%");
a3t.entity ("operator", "^");
a3t.entity ("operator", "!");
Tree* tree = a3t.parse ();
if (tree)
std::cout << tree->dump ();
}
catch (const std::string& error)
{
std::cout << "Error: " << error << std::endl;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Args<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <Context.h>
#include <A3t.h>
Context context;
////////////////////////////////////////////////////////////////////////////////
int main (int argc, const char** argv)
{
try
{
// Prepare the Context object.
A3t a3t;
a3t.initialize (argc, argv);
// Reports.
a3t.entity ("report", "list");
a3t.entity ("report", "next");
// Read-only commands.
a3t.entity ("readcmd", "export");
a3t.entity ("readcmd", "info");
a3t.entity ("readcmd", "list");
a3t.entity ("readcmd", "next");
a3t.entity ("readcmd", "projects");
// Write commands.
a3t.entity ("writecmd", "add");
a3t.entity ("writecmd", "annotate");
a3t.entity ("writecmd", "delete");
a3t.entity ("writecmd", "denotate");
a3t.entity ("writecmd", "done");
a3t.entity ("writecmd", "modify");
a3t.entity ("writecmd", "start");
a3t.entity ("writecmd", "stop");
// Special commands.
a3t.entity ("specialcmd", "calendar");
a3t.entity ("specialcmd", "edit");
a3t.entity ("writecmd", "import");
// Helper commands.
a3t.entity ("helper", "_get");
a3t.entity ("helper", "_query");
a3t.entity ("helper", "_ids");
a3t.entity ("helper", "_uuids");
a3t.entity ("helper", "_zshids");
a3t.entity ("helper", "_zshuuids");
// Attributes (columns).
a3t.entity ("attribute", "description");
a3t.entity ("attribute", "due");
a3t.entity ("attribute", "duration"); // UDAs are included.
a3t.entity ("attribute", "end");
a3t.entity ("attribute", "entry");
a3t.entity ("attribute", "priority");
a3t.entity ("attribute", "project");
a3t.entity ("attribute", "scheduled");
a3t.entity ("attribute", "start");
a3t.entity ("attribute", "uuid");
a3t.entity ("attribute", "wait");
// Pseudo-attributes.
a3t.entity ("pseudo", "limit");
// UDAs.
a3t.entity ("uda", "duration");
// Modifiers.
a3t.entity ("modifier", "before");
a3t.entity ("modifier", "under");
a3t.entity ("modifier", "below");
a3t.entity ("modifier", "after");
a3t.entity ("modifier", "over");
a3t.entity ("modifier", "above");
a3t.entity ("modifier", "none");
a3t.entity ("modifier", "any");
a3t.entity ("modifier", "is");
a3t.entity ("modifier", "equals");
a3t.entity ("modifier", "isnt");
a3t.entity ("modifier", "not");
a3t.entity ("modifier", "has");
a3t.entity ("modifier", "contains");
a3t.entity ("modifier", "hasnt");
a3t.entity ("modifier", "startswith");
a3t.entity ("modifier", "left");
a3t.entity ("modifier", "endswith");
a3t.entity ("modifier", "right");
a3t.entity ("modifier", "word");
a3t.entity ("modifier", "noword");
// Operators.
a3t.entity ("operator", "and");
a3t.entity ("operator", "or");
a3t.entity ("operator", "xor");
a3t.entity ("operator", "<=");
a3t.entity ("operator", ">=");
a3t.entity ("operator", "!~");
a3t.entity ("operator", "!=");
a3t.entity ("operator", "==");
a3t.entity ("operator", "=");
a3t.entity ("operator", ">");
a3t.entity ("operator", "~");
a3t.entity ("operator", "!");
a3t.entity ("operator", "_hastag_");
a3t.entity ("operator", "_notag_");
a3t.entity ("operator", "-");
a3t.entity ("operator", "*");
a3t.entity ("operator", "/");
a3t.entity ("operator", "+");
a3t.entity ("operator", "-");
a3t.entity ("operator", "<");
a3t.entity ("operator", "(");
a3t.entity ("operator", ")");
a3t.entity ("operator", "%");
a3t.entity ("operator", "^");
a3t.entity ("operator", "!");
a3t.findFileOverride ();
a3t.findConfigOverride ();
Tree* tree = a3t.parse ();
if (tree)
std::cout << tree->dump ();
}
catch (const std::string& error)
{
std::cout << "Error: " << error << std::endl;
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2161
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1289621 by johtaylo@johtaylo-JTBUILDER03-increment on 2016/07/11 03:00:08<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2162
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
#include <vw/Core/Exception.h>
#include <vw/Math/Vector.h>
#include <asp/IsisIO/IsisInterface.h>
#include <asp/IsisIO/IsisInterfaceMapFrame.h>
#include <asp/IsisIO/IsisInterfaceFrame.h>
#include <asp/IsisIO/IsisInterfaceMapLineScan.h>
#include <asp/IsisIO/IsisInterfaceLineScan.h>
#include <boost/filesystem.hpp>
#include <iomanip>
#include <ostream>
#include <Cube.h>
#include <Distance.h>
#include <Pvl.h>
#include <Camera.h>
#include <Target.h>
#include <FileName.h>
#include <CameraFactory.h>
#include <SerialNumber.h>
#include <iTime.h>
using namespace vw;
using namespace asp;
using namespace asp::isis;
IsisInterface::IsisInterface( std::string const& file ) {
// Opening labels and camera
Isis::FileName ifilename( QString::fromStdString(file) );
m_label.reset( new Isis::Pvl() );
m_label->read( ifilename.expanded() );
// Opening Isis::Camera
m_cube.reset( new Isis::Cube(QString::fromStdString(file)) );
m_camera.reset(Isis::CameraFactory::Create( *m_cube ));
}
IsisInterface::~IsisInterface() {}
IsisInterface* IsisInterface::open( std::string const& filename ) {
// Opening Labels (This should be done somehow though labels)
Isis::FileName ifilename( QString::fromStdString(filename) );
Isis::Pvl label;
label.read( ifilename.expanded() );
Isis::Cube tempCube(QString::fromStdString(filename));
Isis::Camera* camera = Isis::CameraFactory::Create( tempCube );
IsisInterface* result;
// Instantiate the correct class type
switch ( camera->GetCameraType() ) {
case 0:
// Framing Camera
if ( camera->HasProjection() )
result = new IsisInterfaceMapFrame( filename );
else
result = new IsisInterfaceFrame( filename );
break;
case 2:
// Linescan Camera
if ( camera->HasProjection() )
result = new IsisInterfaceMapLineScan( filename );
else
result = new IsisInterfaceLineScan( filename );
break;
default:
vw_throw( NoImplErr() << "Don't support Isis Camera Type " << camera->GetCameraType() << " at this moment" );
}
return result;
}
int IsisInterface::lines() const {
return m_camera->Lines();
}
int IsisInterface::samples() const {
return m_camera->Samples();
}
std::string IsisInterface::serial_number() const {
Isis::Pvl copy( *m_label );
return Isis::SerialNumber::Compose( copy, true ).toStdString();
}
double IsisInterface::ephemeris_time( vw::Vector2 const& pix ) const {
m_camera->SetImage( pix[0]+1, pix[1]+1 );
return m_camera->time().Et();
}
vw::Vector3 IsisInterface::sun_position( vw::Vector2 const& pix ) const {
m_camera->SetImage( pix[0]+1, pix[1]+1 );
Vector3 sun;
m_camera->sunPosition( &sun[0] );
return sun * 1000;
}
vw::Vector3 IsisInterface::target_radii() const {
Isis::Distance radii[3];
m_camera->radii(radii);
return Vector3( radii[0].meters(),
radii[1].meters(),
radii[2].meters() );
}
std::string IsisInterface::target_name() const {
return m_camera->target()->name().toStdString();
}
std::ostream& asp::isis::operator<<( std::ostream& os, IsisInterface* i ) {
os << "IsisInterface" << i->type()
<< "( Serial=" << i->serial_number()
<< std::setprecision(9)
<< ", f=" << i->m_camera->FocalLength()
<< " mm, pitch=" << i->m_camera->PixelPitch()
<< " mm/px," << std::setprecision(6)
<< "Center=" << i->camera_center() << " )";
return os;
}
// Check if ISISROOT and ISISDATA was set
bool asp::isis::IsisEnv() {
char * isisroot_ptr = getenv("ISISROOT");
char * isisdata_ptr = getenv("ISISDATA");
if (isisroot_ptr == NULL || isisdata_ptr == NULL ||
std::string(isisroot_ptr) == "" ||
std::string(isisdata_ptr) == "" ||
!boost::filesystem::exists(std::string(isisroot_ptr) + "/IsisPreferences") )
return false;
return true;
}
<commit_msg>IsisInterface: Hookup the SAR camera<commit_after>// __BEGIN_LICENSE__
// Copyright (c) 2009-2013, United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration. All
// rights reserved.
//
// The NGT platform is 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.
// __END_LICENSE__
#include <vw/Core/Exception.h>
#include <vw/Math/Vector.h>
#include <asp/IsisIO/IsisInterface.h>
#include <asp/IsisIO/IsisInterfaceMapFrame.h>
#include <asp/IsisIO/IsisInterfaceFrame.h>
#include <asp/IsisIO/IsisInterfaceMapLineScan.h>
#include <asp/IsisIO/IsisInterfaceLineScan.h>
#include <asp/IsisIO/IsisInterfaceSAR.h>
#include <boost/filesystem.hpp>
#include <iomanip>
#include <ostream>
#include <Cube.h>
#include <Distance.h>
#include <Pvl.h>
#include <Camera.h>
#include <Target.h>
#include <FileName.h>
#include <CameraFactory.h>
#include <SerialNumber.h>
#include <iTime.h>
using namespace vw;
using namespace asp;
using namespace asp::isis;
IsisInterface::IsisInterface(std::string const& file) {
// Opening labels and camera
Isis::FileName ifilename(QString::fromStdString(file));
m_label.reset(new Isis::Pvl());
m_label->read(ifilename.expanded());
// Opening Isis::Camera
m_cube.reset(new Isis::Cube(QString::fromStdString(file)));
m_camera.reset(Isis::CameraFactory::Create(*m_cube));
}
IsisInterface::~IsisInterface() {}
IsisInterface* IsisInterface::open(std::string const& filename) {
// Opening Labels (This should be done somehow though labels)
Isis::FileName ifilename(QString::fromStdString(filename));
Isis::Pvl label;
label.read(ifilename.expanded());
Isis::Cube tempCube(QString::fromStdString(filename));
Isis::Camera* camera = Isis::CameraFactory::Create(tempCube);
IsisInterface* result;
// Instantiate the correct class type
switch (camera->GetCameraType()) {
case 0:
// Framing camera
if (camera->HasProjection())
result = new IsisInterfaceMapFrame(filename);
else
result = new IsisInterfaceFrame(filename);
break;
case 2:
// Linescan camera
if (camera->HasProjection())
result = new IsisInterfaceMapLineScan(filename);
else
result = new IsisInterfaceLineScan(filename);
break;
case 3:
// SAR camera (such as MiniRF)
if (camera->HasProjection())
vw_throw(NoImplErr() << "Isis SAR cameras with projected images are not supported yet.");
else
result = new IsisInterfaceSAR(filename);
break;
default:
vw_throw(NoImplErr() << "Don't support Isis camera type "
<< camera->GetCameraType() << " at this moment");
}
return result;
}
int IsisInterface::lines() const {
return m_camera->Lines();
}
int IsisInterface::samples() const {
return m_camera->Samples();
}
std::string IsisInterface::serial_number() const {
Isis::Pvl copy(*m_label);
return Isis::SerialNumber::Compose(copy, true).toStdString();
}
double IsisInterface::ephemeris_time(vw::Vector2 const& pix) const {
m_camera->SetImage(pix[0]+1, pix[1]+1);
return m_camera->time().Et();
}
vw::Vector3 IsisInterface::sun_position(vw::Vector2 const& pix) const {
m_camera->SetImage(pix[0]+1, pix[1]+1);
Vector3 sun;
m_camera->sunPosition(&sun[0]);
return sun * 1000;
}
vw::Vector3 IsisInterface::target_radii() const {
Isis::Distance radii[3];
m_camera->radii(radii);
return Vector3(radii[0].meters(),
radii[1].meters(),
radii[2].meters());
}
std::string IsisInterface::target_name() const {
return m_camera->target()->name().toStdString();
}
std::ostream& asp::isis::operator<<(std::ostream& os, IsisInterface* i) {
os << "IsisInterface" << i->type()
<< "(Serial=" << i->serial_number()
<< std::setprecision(9)
<< ", f=" << i->m_camera->FocalLength()
<< " mm, pitch=" << i->m_camera->PixelPitch()
<< " mm/px," << std::setprecision(6)
<< "Center=" << i->camera_center() << ")";
return os;
}
// Check if ISISROOT and ISISDATA was set
bool asp::isis::IsisEnv() {
char * isisroot_ptr = getenv("ISISROOT");
char * isisdata_ptr = getenv("ISISDATA");
if (isisroot_ptr == NULL || isisdata_ptr == NULL ||
std::string(isisroot_ptr) == "" ||
std::string(isisdata_ptr) == "" ||
!boost::filesystem::exists(std::string(isisroot_ptr) + "/IsisPreferences"))
return false;
return true;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgraphicsanchorlayout_p.h"
QGraphicsAnchorLayout::QGraphicsAnchorLayout(QGraphicsLayoutItem *parent)
: QGraphicsLayout(*new QGraphicsAnchorLayoutPrivate(), parent)
{
Q_D(QGraphicsAnchorLayout);
d->createLayoutEdges();
}
QGraphicsAnchorLayout::~QGraphicsAnchorLayout()
{
Q_D(QGraphicsAnchorLayout);
for (int i = count() - 1; i >= 0; --i) {
QGraphicsLayoutItem *item = d->items.at(i);
removeAt(i);
if (item) {
if (item->ownedByLayout())
delete item;
}
}
d->deleteLayoutEdges();
// ### make something better here
qDeleteAll(d->itemCenterConstraints[0]);
d->itemCenterConstraints[0].clear();
qDeleteAll(d->itemCenterConstraints[1]);
d->itemCenterConstraints[1].clear();
Q_ASSERT(d->items.isEmpty());
Q_ASSERT(d->m_vertexList.isEmpty());
// ### Remove when integrated into Qt
delete d_ptr;
}
void QGraphicsAnchorLayout::anchor(QGraphicsLayoutItem *firstItem,
Edge firstEdge,
QGraphicsLayoutItem *secondItem,
Edge secondEdge, qreal spacing)
{
Q_D(QGraphicsAnchorLayout);
if ((firstItem == 0) || (secondItem == 0)) {
qWarning("QGraphicsAnchorLayout::anchor: "
"Cannot anchor NULL items");
return;
}
if (firstItem == secondItem) {
qWarning("QGraphicsAnchorLayout::anchor: "
"Cannot anchor the item to itself");
return;
}
if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) {
qWarning("QGraphicsAnchorLayout::anchor: "
"Cannot anchor edges of different orientations");
return;
}
// In QGraphicsAnchorLayout, items are represented in its internal
// graph as four anchors that connect:
// - Left -> HCenter
// - HCenter-> Right
// - Top -> VCenter
// - VCenter -> Bottom
// Ensure that the internal anchors have been created for both items.
if (firstItem != this && !d->items.contains(firstItem)) {
d->createItemEdges(firstItem);
d->addChildItem(firstItem);
}
if (secondItem != this && !d->items.contains(secondItem)) {
d->createItemEdges(secondItem);
d->addChildItem(secondItem);
}
// Use heuristics to find out what the user meant with this anchor.
d->correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge);
// Create actual anchor between firstItem and secondItem.
AnchorData *data;
if (spacing >= 0) {
data = new AnchorData(spacing);
d->addAnchor(firstItem, firstEdge, secondItem, secondEdge, data);
} else {
data = new AnchorData(-spacing);
d->addAnchor(secondItem, secondEdge, firstItem, firstEdge, data);
}
invalidate();
}
void QGraphicsAnchorLayout::removeAnchor(QGraphicsLayoutItem *firstItem, Edge firstEdge,
QGraphicsLayoutItem *secondItem, Edge secondEdge)
{
Q_D(QGraphicsAnchorLayout);
if ((firstItem == 0) || (secondItem == 0)) {
qWarning("QGraphicsAnchorLayout::removeAnchor: "
"Cannot remove anchor between NULL items");
return;
}
if (firstItem == secondItem) {
qWarning("QGraphicsAnchorLayout::removeAnchor: "
"Cannot remove anchor from the item to itself");
return;
}
if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) {
qWarning("QGraphicsAnchorLayout::removeAnchor: "
"Cannot remove anchor from edges of different orientations");
return;
}
d->removeAnchor(firstItem, firstEdge, secondItem, secondEdge);
invalidate();
}
void QGraphicsAnchorLayout::setSpacing(qreal spacing, Qt::Orientations orientations /*= Qt::Horizontal|Qt::Vertical*/)
{
Q_D(QGraphicsAnchorLayout);
if (orientations & Qt::Horizontal)
d->spacing[0] = spacing;
if (orientations & Qt::Vertical)
d->spacing[1] = spacing;
}
qreal QGraphicsAnchorLayout::spacing(Qt::Orientation orientation) const
{
Q_D(const QGraphicsAnchorLayout);
// Qt::Horizontal == 0x1, Qt::Vertical = 0x2
return d->spacing[orientation - 1];
}
void QGraphicsAnchorLayout::setGeometry(const QRectF &geom)
{
Q_D(QGraphicsAnchorLayout);
QGraphicsLayout::setGeometry(geom);
d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Horizontal);
d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Vertical);
d->setItemsGeometries();
}
void QGraphicsAnchorLayout::removeAt(int index)
{
Q_D(QGraphicsAnchorLayout);
QGraphicsLayoutItem *item = d->items.value(index);
if (item) {
d->items.remove(index);
d->removeAnchors(item);
item->setParentLayoutItem(0);
}
invalidate();
}
int QGraphicsAnchorLayout::count() const
{
Q_D(const QGraphicsAnchorLayout);
return d->items.size();
}
QGraphicsLayoutItem *QGraphicsAnchorLayout::itemAt(int index) const
{
Q_D(const QGraphicsAnchorLayout);
return d->items.value(index);
}
void QGraphicsAnchorLayout::invalidate()
{
Q_D(QGraphicsAnchorLayout);
QGraphicsLayout::invalidate();
d->calculateGraphCacheDirty = 1;
}
QSizeF QGraphicsAnchorLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_UNUSED(which);
Q_UNUSED(constraint);
Q_D(const QGraphicsAnchorLayout);
// Some setup calculations are delayed until the information is
// actually needed, avoiding unnecessary recalculations when
// adding multiple anchors.
// sizeHint() / effectiveSizeHint() already have a cache
// mechanism, using invalidate() to force recalculation. However
// sizeHint() is called three times after invalidation (for max,
// min and pref), but we just need do our setup once.
const_cast<QGraphicsAnchorLayoutPrivate *>(d)->calculateGraphs();
// ### apply constraint!
QSizeF engineSizeHint(
d->sizeHints[QGraphicsAnchorLayoutPrivate::Horizontal][which],
d->sizeHints[QGraphicsAnchorLayoutPrivate::Vertical][which]);
qreal left, top, right, bottom;
getContentsMargins(&left, &top, &right, &bottom);
return engineSizeHint + QSizeF(left + right, top + bottom);
}
//////// DEBUG /////////
#include <QFile>
void QGraphicsAnchorLayout::dumpGraph()
{
Q_D(QGraphicsAnchorLayout);
QFile file(QString::fromAscii("anchorlayout.dot"));
if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
qWarning("Could not write to %s", file.fileName().toLocal8Bit().constData());
QString dotContents = d->graph[0].serializeToDot();
file.write(dotContents.toLocal8Bit());
dotContents = d->graph[1].serializeToDot();
file.write(dotContents.toLocal8Bit());
file.close();
}
<commit_msg>QGraphicsAnchorLayout: Removing delete d_ptr<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgraphicsanchorlayout_p.h"
QGraphicsAnchorLayout::QGraphicsAnchorLayout(QGraphicsLayoutItem *parent)
: QGraphicsLayout(*new QGraphicsAnchorLayoutPrivate(), parent)
{
Q_D(QGraphicsAnchorLayout);
d->createLayoutEdges();
}
QGraphicsAnchorLayout::~QGraphicsAnchorLayout()
{
Q_D(QGraphicsAnchorLayout);
for (int i = count() - 1; i >= 0; --i) {
QGraphicsLayoutItem *item = d->items.at(i);
removeAt(i);
if (item) {
if (item->ownedByLayout())
delete item;
}
}
d->deleteLayoutEdges();
// ### make something better here
qDeleteAll(d->itemCenterConstraints[0]);
d->itemCenterConstraints[0].clear();
qDeleteAll(d->itemCenterConstraints[1]);
d->itemCenterConstraints[1].clear();
Q_ASSERT(d->items.isEmpty());
Q_ASSERT(d->m_vertexList.isEmpty());
}
void QGraphicsAnchorLayout::anchor(QGraphicsLayoutItem *firstItem,
Edge firstEdge,
QGraphicsLayoutItem *secondItem,
Edge secondEdge, qreal spacing)
{
Q_D(QGraphicsAnchorLayout);
if ((firstItem == 0) || (secondItem == 0)) {
qWarning("QGraphicsAnchorLayout::anchor: "
"Cannot anchor NULL items");
return;
}
if (firstItem == secondItem) {
qWarning("QGraphicsAnchorLayout::anchor: "
"Cannot anchor the item to itself");
return;
}
if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) {
qWarning("QGraphicsAnchorLayout::anchor: "
"Cannot anchor edges of different orientations");
return;
}
// In QGraphicsAnchorLayout, items are represented in its internal
// graph as four anchors that connect:
// - Left -> HCenter
// - HCenter-> Right
// - Top -> VCenter
// - VCenter -> Bottom
// Ensure that the internal anchors have been created for both items.
if (firstItem != this && !d->items.contains(firstItem)) {
d->createItemEdges(firstItem);
d->addChildItem(firstItem);
}
if (secondItem != this && !d->items.contains(secondItem)) {
d->createItemEdges(secondItem);
d->addChildItem(secondItem);
}
// Use heuristics to find out what the user meant with this anchor.
d->correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge);
// Create actual anchor between firstItem and secondItem.
AnchorData *data;
if (spacing >= 0) {
data = new AnchorData(spacing);
d->addAnchor(firstItem, firstEdge, secondItem, secondEdge, data);
} else {
data = new AnchorData(-spacing);
d->addAnchor(secondItem, secondEdge, firstItem, firstEdge, data);
}
invalidate();
}
void QGraphicsAnchorLayout::removeAnchor(QGraphicsLayoutItem *firstItem, Edge firstEdge,
QGraphicsLayoutItem *secondItem, Edge secondEdge)
{
Q_D(QGraphicsAnchorLayout);
if ((firstItem == 0) || (secondItem == 0)) {
qWarning("QGraphicsAnchorLayout::removeAnchor: "
"Cannot remove anchor between NULL items");
return;
}
if (firstItem == secondItem) {
qWarning("QGraphicsAnchorLayout::removeAnchor: "
"Cannot remove anchor from the item to itself");
return;
}
if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) {
qWarning("QGraphicsAnchorLayout::removeAnchor: "
"Cannot remove anchor from edges of different orientations");
return;
}
d->removeAnchor(firstItem, firstEdge, secondItem, secondEdge);
invalidate();
}
void QGraphicsAnchorLayout::setSpacing(qreal spacing, Qt::Orientations orientations /*= Qt::Horizontal|Qt::Vertical*/)
{
Q_D(QGraphicsAnchorLayout);
if (orientations & Qt::Horizontal)
d->spacing[0] = spacing;
if (orientations & Qt::Vertical)
d->spacing[1] = spacing;
}
qreal QGraphicsAnchorLayout::spacing(Qt::Orientation orientation) const
{
Q_D(const QGraphicsAnchorLayout);
// Qt::Horizontal == 0x1, Qt::Vertical = 0x2
return d->spacing[orientation - 1];
}
void QGraphicsAnchorLayout::setGeometry(const QRectF &geom)
{
Q_D(QGraphicsAnchorLayout);
QGraphicsLayout::setGeometry(geom);
d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Horizontal);
d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Vertical);
d->setItemsGeometries();
}
void QGraphicsAnchorLayout::removeAt(int index)
{
Q_D(QGraphicsAnchorLayout);
QGraphicsLayoutItem *item = d->items.value(index);
if (item) {
d->items.remove(index);
d->removeAnchors(item);
item->setParentLayoutItem(0);
}
invalidate();
}
int QGraphicsAnchorLayout::count() const
{
Q_D(const QGraphicsAnchorLayout);
return d->items.size();
}
QGraphicsLayoutItem *QGraphicsAnchorLayout::itemAt(int index) const
{
Q_D(const QGraphicsAnchorLayout);
return d->items.value(index);
}
void QGraphicsAnchorLayout::invalidate()
{
Q_D(QGraphicsAnchorLayout);
QGraphicsLayout::invalidate();
d->calculateGraphCacheDirty = 1;
}
QSizeF QGraphicsAnchorLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const
{
Q_UNUSED(which);
Q_UNUSED(constraint);
Q_D(const QGraphicsAnchorLayout);
// Some setup calculations are delayed until the information is
// actually needed, avoiding unnecessary recalculations when
// adding multiple anchors.
// sizeHint() / effectiveSizeHint() already have a cache
// mechanism, using invalidate() to force recalculation. However
// sizeHint() is called three times after invalidation (for max,
// min and pref), but we just need do our setup once.
const_cast<QGraphicsAnchorLayoutPrivate *>(d)->calculateGraphs();
// ### apply constraint!
QSizeF engineSizeHint(
d->sizeHints[QGraphicsAnchorLayoutPrivate::Horizontal][which],
d->sizeHints[QGraphicsAnchorLayoutPrivate::Vertical][which]);
qreal left, top, right, bottom;
getContentsMargins(&left, &top, &right, &bottom);
return engineSizeHint + QSizeF(left + right, top + bottom);
}
//////// DEBUG /////////
#include <QFile>
void QGraphicsAnchorLayout::dumpGraph()
{
Q_D(QGraphicsAnchorLayout);
QFile file(QString::fromAscii("anchorlayout.dot"));
if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
qWarning("Could not write to %s", file.fileName().toLocal8Bit().constData());
QString dotContents = d->graph[0].serializeToDot();
file.write(dotContents.toLocal8Bit());
dotContents = d->graph[1].serializeToDot();
file.write(dotContents.toLocal8Bit());
file.close();
}
<|endoftext|> |
<commit_before>/**
* @file llsearcheditor.cpp
* @brief LLSearchEditor implementation
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
// Text editor widget to let users enter a single line.
#include "linden_common.h"
#include "llsearcheditor.h"
LLSearchEditor::LLSearchEditor(const LLSearchEditor::Params& p)
: LLUICtrl(p),
mSearchButton(NULL),
mClearButton(NULL)
{
S32 srch_btn_top = p.search_button.top_pad + p.search_button.rect.height;
S32 srch_btn_right = p.search_button.rect.width + p.search_button.left_pad;
LLRect srch_btn_rect(p.search_button.left_pad, srch_btn_top, srch_btn_right, p.search_button.top_pad);
S32 text_pad_left = p.text_pad_left;
if (p.search_button_visible)
text_pad_left += srch_btn_rect.getWidth();
// Set up line editor.
LLLineEditor::Params line_editor_params(p);
line_editor_params.name("filter edit box");
line_editor_params.rect(getLocalRect());
line_editor_params.follows.flags(FOLLOWS_ALL);
line_editor_params.text_pad_left(text_pad_left);
line_editor_params.revert_on_esc(false);
line_editor_params.commit_callback.function(boost::bind(&LLUICtrl::onCommit, this));
line_editor_params.keystroke_callback(boost::bind(&LLSearchEditor::handleKeystroke, this));
mSearchEditor = LLUICtrlFactory::create<LLLineEditor>(line_editor_params);
mSearchEditor->setPassDelete(TRUE);
addChild(mSearchEditor);
if (p.search_button_visible)
{
// Set up search button.
LLButton::Params srch_btn_params(p.search_button);
srch_btn_params.name(std::string("search button"));
srch_btn_params.rect(srch_btn_rect) ;
srch_btn_params.follows.flags(FOLLOWS_LEFT|FOLLOWS_TOP);
srch_btn_params.tab_stop(false);
srch_btn_params.click_callback.function(boost::bind(&LLUICtrl::onCommit, this));
mSearchButton = LLUICtrlFactory::create<LLButton>(srch_btn_params);
mSearchEditor->addChild(mSearchButton);
}
if (p.clear_button_visible)
{
// Set up clear button.
LLButton::Params clr_btn_params(p.clear_button);
clr_btn_params.name(std::string("clear button"));
S32 clr_btn_top = clr_btn_params.rect.bottom + clr_btn_params.rect.height;
S32 clr_btn_right = getRect().getWidth() - clr_btn_params.pad_right;
S32 clr_btn_left = clr_btn_right - clr_btn_params.rect.width;
LLRect clear_btn_rect(clr_btn_left, clr_btn_top, clr_btn_right, p.clear_button.rect.bottom);
clr_btn_params.rect(clear_btn_rect) ;
clr_btn_params.follows.flags(FOLLOWS_RIGHT|FOLLOWS_TOP);
clr_btn_params.tab_stop(false);
clr_btn_params.click_callback.function(boost::bind(&LLSearchEditor::onClearButtonClick, this, _2));
mClearButton = LLUICtrlFactory::create<LLButton>(clr_btn_params);
mSearchEditor->addChild(mClearButton);
}
}
//virtual
void LLSearchEditor::draw()
{
if (mClearButton)
mClearButton->setVisible(!mSearchEditor->getWText().empty());
LLUICtrl::draw();
}
//virtual
void LLSearchEditor::setValue(const LLSD& value )
{
mSearchEditor->setValue(value);
}
//virtual
LLSD LLSearchEditor::getValue() const
{
return mSearchEditor->getValue();
}
//virtual
BOOL LLSearchEditor::setTextArg( const std::string& key, const LLStringExplicit& text )
{
return mSearchEditor->setTextArg(key, text);
}
//virtual
BOOL LLSearchEditor::setLabelArg( const std::string& key, const LLStringExplicit& text )
{
return mSearchEditor->setLabelArg(key, text);
}
//virtual
void LLSearchEditor::setLabel( const LLStringExplicit &new_label )
{
mSearchEditor->setLabel(new_label);
}
//virtual
void LLSearchEditor::clear()
{
if (mSearchEditor)
{
mSearchEditor->clear();
}
}
//virtual
void LLSearchEditor::setFocus( BOOL b )
{
if (mSearchEditor)
{
mSearchEditor->setFocus(b);
}
}
void LLSearchEditor::onClearButtonClick(const LLSD& data)
{
setText(LLStringUtil::null);
mSearchEditor->doDelete(); // force keystroke callback
}
void LLSearchEditor::handleKeystroke()
{
if (mKeystrokeCallback)
{
mKeystrokeCallback(this, getValue());
}
}
<commit_msg>EXT-5560 - filter clear button was calling doDelete which had many more gyrations than onCommit, and only onCommit was needed<commit_after>/**
* @file llsearcheditor.cpp
* @brief LLSearchEditor implementation
*
* $LicenseInfo:firstyear=2001&license=viewergpl$
*
* Copyright (c) 2001-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
// Text editor widget to let users enter a single line.
#include "linden_common.h"
#include "llsearcheditor.h"
LLSearchEditor::LLSearchEditor(const LLSearchEditor::Params& p)
: LLUICtrl(p),
mSearchButton(NULL),
mClearButton(NULL)
{
S32 srch_btn_top = p.search_button.top_pad + p.search_button.rect.height;
S32 srch_btn_right = p.search_button.rect.width + p.search_button.left_pad;
LLRect srch_btn_rect(p.search_button.left_pad, srch_btn_top, srch_btn_right, p.search_button.top_pad);
S32 text_pad_left = p.text_pad_left;
if (p.search_button_visible)
text_pad_left += srch_btn_rect.getWidth();
// Set up line editor.
LLLineEditor::Params line_editor_params(p);
line_editor_params.name("filter edit box");
line_editor_params.rect(getLocalRect());
line_editor_params.follows.flags(FOLLOWS_ALL);
line_editor_params.text_pad_left(text_pad_left);
line_editor_params.revert_on_esc(false);
line_editor_params.commit_callback.function(boost::bind(&LLUICtrl::onCommit, this));
line_editor_params.keystroke_callback(boost::bind(&LLSearchEditor::handleKeystroke, this));
mSearchEditor = LLUICtrlFactory::create<LLLineEditor>(line_editor_params);
mSearchEditor->setPassDelete(TRUE);
addChild(mSearchEditor);
if (p.search_button_visible)
{
// Set up search button.
LLButton::Params srch_btn_params(p.search_button);
srch_btn_params.name(std::string("search button"));
srch_btn_params.rect(srch_btn_rect) ;
srch_btn_params.follows.flags(FOLLOWS_LEFT|FOLLOWS_TOP);
srch_btn_params.tab_stop(false);
srch_btn_params.click_callback.function(boost::bind(&LLUICtrl::onCommit, this));
mSearchButton = LLUICtrlFactory::create<LLButton>(srch_btn_params);
mSearchEditor->addChild(mSearchButton);
}
if (p.clear_button_visible)
{
// Set up clear button.
LLButton::Params clr_btn_params(p.clear_button);
clr_btn_params.name(std::string("clear button"));
S32 clr_btn_top = clr_btn_params.rect.bottom + clr_btn_params.rect.height;
S32 clr_btn_right = getRect().getWidth() - clr_btn_params.pad_right;
S32 clr_btn_left = clr_btn_right - clr_btn_params.rect.width;
LLRect clear_btn_rect(clr_btn_left, clr_btn_top, clr_btn_right, p.clear_button.rect.bottom);
clr_btn_params.rect(clear_btn_rect) ;
clr_btn_params.follows.flags(FOLLOWS_RIGHT|FOLLOWS_TOP);
clr_btn_params.tab_stop(false);
clr_btn_params.click_callback.function(boost::bind(&LLSearchEditor::onClearButtonClick, this, _2));
mClearButton = LLUICtrlFactory::create<LLButton>(clr_btn_params);
mSearchEditor->addChild(mClearButton);
}
}
//virtual
void LLSearchEditor::draw()
{
if (mClearButton)
mClearButton->setVisible(!mSearchEditor->getWText().empty());
LLUICtrl::draw();
}
//virtual
void LLSearchEditor::setValue(const LLSD& value )
{
mSearchEditor->setValue(value);
}
//virtual
LLSD LLSearchEditor::getValue() const
{
return mSearchEditor->getValue();
}
//virtual
BOOL LLSearchEditor::setTextArg( const std::string& key, const LLStringExplicit& text )
{
return mSearchEditor->setTextArg(key, text);
}
//virtual
BOOL LLSearchEditor::setLabelArg( const std::string& key, const LLStringExplicit& text )
{
return mSearchEditor->setLabelArg(key, text);
}
//virtual
void LLSearchEditor::setLabel( const LLStringExplicit &new_label )
{
mSearchEditor->setLabel(new_label);
}
//virtual
void LLSearchEditor::clear()
{
if (mSearchEditor)
{
mSearchEditor->clear();
}
}
//virtual
void LLSearchEditor::setFocus( BOOL b )
{
if (mSearchEditor)
{
mSearchEditor->setFocus(b);
}
}
void LLSearchEditor::onClearButtonClick(const LLSD& data)
{
setText(LLStringUtil::null);
mSearchEditor->onCommit(); // force keystroke callback
}
void LLSearchEditor::handleKeystroke()
{
if (mKeystrokeCallback)
{
mKeystrokeCallback(this, getValue());
}
}
<|endoftext|> |
<commit_before>#include "pdbformat.h"
#include <avogadro/core/elements.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/utilities.h>
#include <avogadro/core/vector.h>
#include <istream>
#include <string>
using Avogadro::Core::Atom;
using Avogadro::Core::Bond;
using Avogadro::Core::Elements;
using Avogadro::Core::Molecule;
using Avogadro::Core::lexicalCast;
using Avogadro::Core::startsWith;
using Avogadro::Core::trimmed;
using std::string;
using std::istringstream;
using std::getline;
using std::vector;
namespace Avogadro {
namespace Io {
PdbFormat::PdbFormat()
{
}
PdbFormat::~PdbFormat()
{
}
bool PdbFormat::read(std::istream& in, Core::Molecule& mol)
{
string buffer;
int atomCount = 0;
std::vector<int> terList;
while (getline(in, buffer)) { // Read Each line one by one
if (startsWith(buffer, "ENDMDL"))
break;
else if (startsWith(buffer, "ATOM") || startsWith(buffer, "HETATM")) {
Vector3 pos; // Coordinates
bool ok(false);
pos.x() = lexicalCast<Real>(buffer.substr(30, 8), ok);
if (!ok) {
appendError("Failed to parse x coordinate: " + buffer.substr(30, 8));
return false;
}
pos.y() = lexicalCast<Real>(buffer.substr(38, 8), ok);
if (!ok) {
appendError("Failed to parse y coordinate: " + buffer.substr(38, 8));
return false;
}
pos.z() = lexicalCast<Real>(buffer.substr(46, 8), ok);
if (!ok) {
appendError("Failed to parse z coordinate: " + buffer.substr(46, 8));
return false;
}
string element; // Element symbol, right justififed
element = buffer.substr(76, 2);
element = trimmed(element);
if(element == "SE") //For Sulphur
element = 'S';
unsigned char atomicNum = Elements::atomicNumberFromSymbol(element);
if(atomicNum == 255)
appendError("Invalid element");
Atom newAtom = mol.addAtom(atomicNum);
newAtom.setPosition3d(pos);
atomCount++;
}
else if(startsWith(buffer, "TER"))
{ // This is very important, each TER record also counts in the serial.
// Need to account for that when comparing with CONECT
bool ok(false);
terList.push_back(lexicalCast<int>(buffer.substr(6, 5), ok));
if(!ok)
{
appendError ("Failed to parse TER serial");
return false;
}
}
else if(startsWith(buffer, "CONECT"))
{
bool ok(false);
int a = lexicalCast<int>(buffer.substr(6, 5), ok);
if (!ok)
{
appendError ("Failed to parse coordinate a " + buffer.substr(6, 5));
return false;
}
--a;
int terCount;
for (terCount = 0; terCount < terList.size() && a > terList[terCount]; ++terCount); // semicolon is intentional
a = a - terCount;
int b1 = lexicalCast<int>(buffer.substr(11, 5), ok);
if (!ok)
{
appendError ("Failed to parse coordinate b1 " + buffer.substr(11, 5));
return false;
}
--b1;
for (terCount = 0; terCount < terList.size() && b1 > terList[terCount]; ++terCount); // semicolon is intentional
b1 = b1 - terCount;
if(a < b1){
mol.Avogadro::Core::Molecule::addBond(a, b1, 1);
}
if(trimmed(buffer.substr(16, 5)) != "") // Futher bonds may be absent
{
int b2 = lexicalCast<int>(buffer.substr(16, 5), ok);
if(!ok)
{
appendError ("Failed to parse coordinate b2" + buffer.substr(16, 5));
return false;
}
--b2;
for (terCount = 0; terCount < terList.size() && b2 > terList[terCount]; ++terCount); // semicolon is intentional
b2 = b2 - terCount;
if(a < b2){
mol.Avogadro::Core::Molecule::addBond(a, b2, 1);
}
}
if(trimmed(buffer.substr(21, 5)) != "") // Futher bonds may be absent
{
int b3 = lexicalCast<int>(buffer.substr(21, 5), ok);
if(!ok)
{
appendError ("Failed to parse coordinate b3" + buffer.substr(21, 5));
return false;
}
--b3;
for (terCount = 0; terCount < terList.size() && b3 > terList[terCount]; ++terCount); // semicolon is intentional
b3 = b3 - terCount;
if(a < b3){
mol.Avogadro::Core::Molecule::addBond(a, b3, 1);
}
}
if(trimmed(buffer.substr(26, 5)) != "") // Futher bonds may be absent
{
int b4 = lexicalCast<int>(buffer.substr(26, 5), ok);
if(!ok)
{
appendError ("Failed to parse coordinate b4" + buffer.substr(26, 5));
return false;
}
--b4;
for (terCount = 0; terCount < terList.size() && b4 > terList[terCount]; ++terCount); // semicolon is intentional
b4 = b4 - terCount;
if(a < b4){
mol.Avogadro::Core::Molecule::addBond(a, b4, 1);
}
}
}
} // End while loop
return true;
} // End read
std::vector<std::string> PdbFormat::fileExtensions() const
{
std::vector<std::string> ext;
ext.push_back("pdb");
return ext;
}
std::vector<std::string> PdbFormat::mimeTypes() const
{
std::vector<std::string> mime;
mime.push_back("chemical/x-pdb");
return mime;
}
} // end Io namespace
} // end Avogadro namespace<commit_msg>Made code cleaner<commit_after>#include "pdbformat.h"
#include <avogadro/core/elements.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/utilities.h>
#include <avogadro/core/vector.h>
#include <istream>
#include <string>
using Avogadro::Core::Atom;
using Avogadro::Core::Bond;
using Avogadro::Core::Elements;
using Avogadro::Core::Molecule;
using Avogadro::Core::lexicalCast;
using Avogadro::Core::startsWith;
using Avogadro::Core::trimmed;
using std::string;
using std::istringstream;
using std::getline;
using std::vector;
namespace Avogadro {
namespace Io {
PdbFormat::PdbFormat()
{
}
PdbFormat::~PdbFormat()
{
}
bool PdbFormat::read(std::istream& in, Core::Molecule& mol)
{
string buffer;
int atomCount = 0;
std::vector<int> terList;
while (getline(in, buffer)) { // Read Each line one by one
if (startsWith(buffer, "ENDMDL"))
break;
else if (startsWith(buffer, "ATOM") || startsWith(buffer, "HETATM")) {
Vector3 pos; // Coordinates
bool ok(false);
pos.x() = lexicalCast<Real>(buffer.substr(30, 8), ok);
if (!ok) {
appendError("Failed to parse x coordinate: " + buffer.substr(30, 8));
return false;
}
pos.y() = lexicalCast<Real>(buffer.substr(38, 8), ok);
if (!ok) {
appendError("Failed to parse y coordinate: " + buffer.substr(38, 8));
return false;
}
pos.z() = lexicalCast<Real>(buffer.substr(46, 8), ok);
if (!ok) {
appendError("Failed to parse z coordinate: " + buffer.substr(46, 8));
return false;
}
string element; // Element symbol, right justififed
element = buffer.substr(76, 2);
element = trimmed(element);
if(element == "SE") //For Sulphur
element = 'S';
unsigned char atomicNum = Elements::atomicNumberFromSymbol(element);
if(atomicNum == 255)
appendError("Invalid element");
Atom newAtom = mol.addAtom(atomicNum);
newAtom.setPosition3d(pos);
atomCount++;
}
else if(startsWith(buffer, "TER"))
{ // This is very important, each TER record also counts in the serial.
// Need to account for that when comparing with CONECT
bool ok(false);
terList.push_back(lexicalCast<int>(buffer.substr(6, 5), ok));
if(!ok)
{
appendError ("Failed to parse TER serial");
return false;
}
}
else if(startsWith(buffer, "CONECT"))
{
bool ok(false);
int a = lexicalCast<int>(buffer.substr(6, 5), ok);
if (!ok)
{
appendError ("Failed to parse coordinate a " + buffer.substr(6, 5));
return false;
}
--a;
int terCount;
for (terCount = 0; terCount < terList.size() && a > terList[terCount]; ++terCount); // semicolon is intentional
a = a - terCount;
int bCoords[] = {11, 16, 21, 26};
for (int i = 0; i < 4; i++)
{
if (trimmed(buffer.substr(bCoords[i], 5)) == "")
break;
else{
bool ok(false);
int b = lexicalCast<int>(buffer.substr(bCoords[i], 5), ok) - 1;
if (!ok)
{
appendError ("Failed to parse coordinate b" + std::to_string(i) + " " + buffer.substr(bCoords[i], 5));
return false;
}
for (terCount = 0; terCount < terList.size() && b > terList[terCount]; ++terCount); // semicolon is intentional
b = b - terCount;
if(a < b){
mol.Avogadro::Core::Molecule::addBond(a, b, 1);
}
}
}
}
} // End while loop
return true;
} // End read
std::vector<std::string> PdbFormat::fileExtensions() const
{
std::vector<std::string> ext;
ext.push_back("pdb");
return ext;
}
std::vector<std::string> PdbFormat::mimeTypes() const
{
std::vector<std::string> mime;
mime.push_back("chemical/x-pdb");
return mime;
}
} // end Io namespace
} // end Avogadro namespace<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 "net/base/network_change_notifier_helper.h"
#include <algorithm>
#include "base/logging.h"
namespace net {
namespace internal {
NetworkChangeNotifierHelper::NetworkChangeNotifierHelper()
: is_notifying_observers_(false) {}
NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() {
DCHECK(observers_.empty());
}
void NetworkChangeNotifierHelper::AddObserver(Observer* observer) {
DCHECK(!is_notifying_observers_);
observers_.push_back(observer);
}
void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) {
DCHECK(!is_notifying_observers_);
observers_.erase(std::remove(observers_.begin(), observers_.end(), observer));
}
void NetworkChangeNotifierHelper::OnIPAddressChanged() {
DCHECK(!is_notifying_observers_);
is_notifying_observers_ = true;
for (std::vector<Observer*>::iterator it = observers_.begin();
it != observers_.end(); ++it) {
(*it)->OnIPAddressChanged();
}
is_notifying_observers_ = false;
}
} // namespace internal
} // namespace net
<commit_msg>Disable DCHECK'ing that all NetworkChangeNotifiers are removed. BUG=34391<commit_after>// Copyright (c) 2009 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 "net/base/network_change_notifier_helper.h"
#include <algorithm>
#include "base/logging.h"
namespace net {
namespace internal {
NetworkChangeNotifierHelper::NetworkChangeNotifierHelper()
: is_notifying_observers_(false) {}
NetworkChangeNotifierHelper::~NetworkChangeNotifierHelper() {
// TODO(willchan): Re-enable this DCHECK after fixing http://crbug.com/34391
// since we're leaking URLRequestContextGetters that cause this DCHECK to
// fire.
// DCHECK(observers_.empty());
}
void NetworkChangeNotifierHelper::AddObserver(Observer* observer) {
DCHECK(!is_notifying_observers_);
observers_.push_back(observer);
}
void NetworkChangeNotifierHelper::RemoveObserver(Observer* observer) {
DCHECK(!is_notifying_observers_);
observers_.erase(std::remove(observers_.begin(), observers_.end(), observer));
}
void NetworkChangeNotifierHelper::OnIPAddressChanged() {
DCHECK(!is_notifying_observers_);
is_notifying_observers_ = true;
for (std::vector<Observer*>::iterator it = observers_.begin();
it != observers_.end(); ++it) {
(*it)->OnIPAddressChanged();
}
is_notifying_observers_ = false;
}
} // namespace internal
} // namespace net
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2561
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1496636 by johtaylo@johtaylo-jtincrementor2-increment on 2017/12/20 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2562
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file KeyWords.cxx
** Colourise for particular languages.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <vector>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "LexerModule.h"
#include "Catalogue.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static std::vector<LexerModule *> lexerCatalogue;
static int nextLanguage = SCLEX_AUTOMATIC+1;
const LexerModule *Catalogue::Find(int language) {
for (std::vector<LexerModule *>::iterator it=lexerCatalogue.begin();
it != lexerCatalogue.end(); ++it) {
if ((*it)->GetLanguage() == language) {
return *it;
}
}
return 0;
}
const LexerModule *Catalogue::Find(const char *languageName) {
if (languageName) {
for (std::vector<LexerModule *>::iterator it=lexerCatalogue.begin();
it != lexerCatalogue.end(); ++it) {
if ((*it)->languageName && (0 == strcmp((*it)->languageName, languageName))) {
return *it;
}
}
}
return 0;
}
void Catalogue::AddLexerModule(LexerModule *plm) {
if (plm->GetLanguage() == SCLEX_AUTOMATIC) {
plm->language = nextLanguage;
nextLanguage++;
}
lexerCatalogue.push_back(plm);
}
// Alternative historical name for Scintilla_LinkLexers
int wxForceScintillaLexers(void) {
return Scintilla_LinkLexers();
}
// To add or remove a lexer, add or remove its file and run LexGen.py.
// Force a reference to all of the Scintilla lexers so that the linker will
// not remove the code of the lexers.
int Scintilla_LinkLexers() {
static int initialised = 0;
if (initialised)
return 0;
initialised = 1;
// Shorten the code that declares a lexer and ensures it is linked in by calling a method.
#define LINK_LEXER(lexer) extern LexerModule lexer; Catalogue::AddLexerModule(&lexer);
//++Autogenerated -- run src/LexGen.py to regenerate
//**\(\tLINK_LEXER(\*);\n\)
LINK_LEXER(lmAbaqus);
LINK_LEXER(lmAda);
LINK_LEXER(lmAns1);
LINK_LEXER(lmAPDL);
LINK_LEXER(lmAsm);
LINK_LEXER(lmASY);
LINK_LEXER(lmAU3);
LINK_LEXER(lmAVE);
LINK_LEXER(lmBaan);
LINK_LEXER(lmBash);
LINK_LEXER(lmBatch);
LINK_LEXER(lmBlitzBasic);
LINK_LEXER(lmBullant);
LINK_LEXER(lmCaml);
LINK_LEXER(lmClw);
LINK_LEXER(lmClwNoCase);
LINK_LEXER(lmCmake);
LINK_LEXER(lmCOBOL);
LINK_LEXER(lmConf);
LINK_LEXER(lmCPP);
LINK_LEXER(lmCPPNoCase);
LINK_LEXER(lmCsound);
LINK_LEXER(lmCss);
LINK_LEXER(lmD);
LINK_LEXER(lmDiff);
LINK_LEXER(lmEiffel);
LINK_LEXER(lmEiffelkw);
LINK_LEXER(lmErlang);
LINK_LEXER(lmErrorList);
LINK_LEXER(lmESCRIPT);
LINK_LEXER(lmF77);
LINK_LEXER(lmFlagShip);
LINK_LEXER(lmForth);
LINK_LEXER(lmFortran);
LINK_LEXER(lmFreeBasic);
LINK_LEXER(lmGAP);
LINK_LEXER(lmGui4Cli);
LINK_LEXER(lmHaskell);
LINK_LEXER(lmHTML);
LINK_LEXER(lmInno);
LINK_LEXER(lmKix);
LINK_LEXER(lmLatex);
LINK_LEXER(lmLISP);
LINK_LEXER(lmLot);
LINK_LEXER(lmLout);
LINK_LEXER(lmLua);
LINK_LEXER(lmMagikSF);
LINK_LEXER(lmMake);
LINK_LEXER(lmMarkdown);
LINK_LEXER(lmMatlab);
LINK_LEXER(lmMETAPOST);
LINK_LEXER(lmMMIXAL);
LINK_LEXER(lmMSSQL);
LINK_LEXER(lmMySQL);
LINK_LEXER(lmNimrod);
LINK_LEXER(lmNncrontab);
LINK_LEXER(lmNsis);
LINK_LEXER(lmNull);
LINK_LEXER(lmOctave);
LINK_LEXER(lmOpal);
LINK_LEXER(lmPascal);
LINK_LEXER(lmPB);
LINK_LEXER(lmPerl);
LINK_LEXER(lmPHPSCRIPT);
LINK_LEXER(lmPLM);
LINK_LEXER(lmPo);
LINK_LEXER(lmPOV);
LINK_LEXER(lmPowerPro);
LINK_LEXER(lmPowerShell);
LINK_LEXER(lmProgress);
LINK_LEXER(lmProps);
LINK_LEXER(lmPS);
LINK_LEXER(lmPureBasic);
LINK_LEXER(lmPython);
LINK_LEXER(lmR);
LINK_LEXER(lmREBOL);
LINK_LEXER(lmRuby);
LINK_LEXER(lmScriptol);
LINK_LEXER(lmSmalltalk);
LINK_LEXER(lmSML);
LINK_LEXER(lmSorc);
LINK_LEXER(lmSpecman);
LINK_LEXER(lmSpice);
LINK_LEXER(lmSQL);
LINK_LEXER(lmTACL);
LINK_LEXER(lmTADS3);
LINK_LEXER(lmTAL);
LINK_LEXER(lmTCL);
LINK_LEXER(lmTeX);
LINK_LEXER(lmTxt2tags);
LINK_LEXER(lmVB);
LINK_LEXER(lmVBScript);
LINK_LEXER(lmVerilog);
LINK_LEXER(lmVHDL);
LINK_LEXER(lmXML);
LINK_LEXER(lmYAML);
//--Autogenerated -- end of automatically generated section
return 1;
}
<commit_msg>Ensure lexers linked in whenever asked to find a lexer.<commit_after>// Scintilla source code edit control
/** @file KeyWords.cxx
** Colourise for particular languages.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <vector>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "LexerModule.h"
#include "Catalogue.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static std::vector<LexerModule *> lexerCatalogue;
static int nextLanguage = SCLEX_AUTOMATIC+1;
const LexerModule *Catalogue::Find(int language) {
Scintilla_LinkLexers();
for (std::vector<LexerModule *>::iterator it=lexerCatalogue.begin();
it != lexerCatalogue.end(); ++it) {
if ((*it)->GetLanguage() == language) {
return *it;
}
}
return 0;
}
const LexerModule *Catalogue::Find(const char *languageName) {
Scintilla_LinkLexers();
if (languageName) {
for (std::vector<LexerModule *>::iterator it=lexerCatalogue.begin();
it != lexerCatalogue.end(); ++it) {
if ((*it)->languageName && (0 == strcmp((*it)->languageName, languageName))) {
return *it;
}
}
}
return 0;
}
void Catalogue::AddLexerModule(LexerModule *plm) {
if (plm->GetLanguage() == SCLEX_AUTOMATIC) {
plm->language = nextLanguage;
nextLanguage++;
}
lexerCatalogue.push_back(plm);
}
// Alternative historical name for Scintilla_LinkLexers
int wxForceScintillaLexers(void) {
return Scintilla_LinkLexers();
}
// To add or remove a lexer, add or remove its file and run LexGen.py.
// Force a reference to all of the Scintilla lexers so that the linker will
// not remove the code of the lexers.
int Scintilla_LinkLexers() {
static int initialised = 0;
if (initialised)
return 0;
initialised = 1;
// Shorten the code that declares a lexer and ensures it is linked in by calling a method.
#define LINK_LEXER(lexer) extern LexerModule lexer; Catalogue::AddLexerModule(&lexer);
//++Autogenerated -- run src/LexGen.py to regenerate
//**\(\tLINK_LEXER(\*);\n\)
LINK_LEXER(lmAbaqus);
LINK_LEXER(lmAda);
LINK_LEXER(lmAns1);
LINK_LEXER(lmAPDL);
LINK_LEXER(lmAsm);
LINK_LEXER(lmASY);
LINK_LEXER(lmAU3);
LINK_LEXER(lmAVE);
LINK_LEXER(lmBaan);
LINK_LEXER(lmBash);
LINK_LEXER(lmBatch);
LINK_LEXER(lmBlitzBasic);
LINK_LEXER(lmBullant);
LINK_LEXER(lmCaml);
LINK_LEXER(lmClw);
LINK_LEXER(lmClwNoCase);
LINK_LEXER(lmCmake);
LINK_LEXER(lmCOBOL);
LINK_LEXER(lmConf);
LINK_LEXER(lmCPP);
LINK_LEXER(lmCPPNoCase);
LINK_LEXER(lmCsound);
LINK_LEXER(lmCss);
LINK_LEXER(lmD);
LINK_LEXER(lmDiff);
LINK_LEXER(lmEiffel);
LINK_LEXER(lmEiffelkw);
LINK_LEXER(lmErlang);
LINK_LEXER(lmErrorList);
LINK_LEXER(lmESCRIPT);
LINK_LEXER(lmF77);
LINK_LEXER(lmFlagShip);
LINK_LEXER(lmForth);
LINK_LEXER(lmFortran);
LINK_LEXER(lmFreeBasic);
LINK_LEXER(lmGAP);
LINK_LEXER(lmGui4Cli);
LINK_LEXER(lmHaskell);
LINK_LEXER(lmHTML);
LINK_LEXER(lmInno);
LINK_LEXER(lmKix);
LINK_LEXER(lmLatex);
LINK_LEXER(lmLISP);
LINK_LEXER(lmLot);
LINK_LEXER(lmLout);
LINK_LEXER(lmLua);
LINK_LEXER(lmMagikSF);
LINK_LEXER(lmMake);
LINK_LEXER(lmMarkdown);
LINK_LEXER(lmMatlab);
LINK_LEXER(lmMETAPOST);
LINK_LEXER(lmMMIXAL);
LINK_LEXER(lmMSSQL);
LINK_LEXER(lmMySQL);
LINK_LEXER(lmNimrod);
LINK_LEXER(lmNncrontab);
LINK_LEXER(lmNsis);
LINK_LEXER(lmNull);
LINK_LEXER(lmOctave);
LINK_LEXER(lmOpal);
LINK_LEXER(lmPascal);
LINK_LEXER(lmPB);
LINK_LEXER(lmPerl);
LINK_LEXER(lmPHPSCRIPT);
LINK_LEXER(lmPLM);
LINK_LEXER(lmPo);
LINK_LEXER(lmPOV);
LINK_LEXER(lmPowerPro);
LINK_LEXER(lmPowerShell);
LINK_LEXER(lmProgress);
LINK_LEXER(lmProps);
LINK_LEXER(lmPS);
LINK_LEXER(lmPureBasic);
LINK_LEXER(lmPython);
LINK_LEXER(lmR);
LINK_LEXER(lmREBOL);
LINK_LEXER(lmRuby);
LINK_LEXER(lmScriptol);
LINK_LEXER(lmSmalltalk);
LINK_LEXER(lmSML);
LINK_LEXER(lmSorc);
LINK_LEXER(lmSpecman);
LINK_LEXER(lmSpice);
LINK_LEXER(lmSQL);
LINK_LEXER(lmTACL);
LINK_LEXER(lmTADS3);
LINK_LEXER(lmTAL);
LINK_LEXER(lmTCL);
LINK_LEXER(lmTeX);
LINK_LEXER(lmTxt2tags);
LINK_LEXER(lmVB);
LINK_LEXER(lmVBScript);
LINK_LEXER(lmVerilog);
LINK_LEXER(lmVHDL);
LINK_LEXER(lmXML);
LINK_LEXER(lmYAML);
//--Autogenerated -- end of automatically generated section
return 1;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <map>
#include <mutex>
#include <netinet/in.h>
#include <signal.h>
#include <stdlib.h>
#include <thread>
#include <unistd.h>
#include <string.h>
#include "metacard.h"
#include "utils.h"
using namespace std;
// GLOBAL VARIABLES
int listener_socket;
map<string, uint64_t> balances;
mutex balance_guard;
//Close socket on ^C
void handle_control_c(int s) {
(void)s; // silence -Wunused-parameter
close(listener_socket);
exit(EXIT_SUCCESS);
}
const unsigned char* get_cryptkey(const char* name) {
if(!strcmp(name, "Alice")) { return Alice_cryptkey; }
if(!strcmp(name, "Bob")) { return Bob_cryptkey; }
if(!strcmp(name, "Eve")) { return Eve_cryptkey; }
return 0;
}
const unsigned char* get_signkey(const char* name) {
if(!strcmp(name, "Alice")) { return Alice_signkey; }
if(!strcmp(name, "Bob")) { return Bob_signkey; }
if(!strcmp(name, "Eve")) { return Eve_signkey; }
return 0;
}
// handle_nonce populates the nonce, all the others zero the nonce after checking it
void handle_nonce(nonce_t* nonce, stc_payload* dst) {
}
void handle_balance(nonce_t* nonce, const char* username, const cts_payload* src, stc_payload* dst) {
}
void handle_withdrawl(nonce_t* nonce, const char* username, const cts_payload* src, stc_payload* dst) {
}
void handle_transfer(nonce_t* nonce, const char* username, const cts_payload* src, stc_payload* dst) {
}
void handle_connection(int fd) {
//cout << "handle_connection(" << fd << ")" << endl;
cts_payload in_payload;
client_to_server incoming;
stc_payload out_payload;
server_to_client outgoing;
nonce_t nonce;
const unsigned char *cryptkey, *signkey;
do {
if(read_synchronized(fd, (char*)&incoming, sizeof incoming)) { break; }
// TODO: handle errors with replies
if(!(cryptkey = get_cryptkey(incoming.src.username))) { break; }
if(!(signkey = get_signkey(incoming.src.username))) { break; }
if(deserialcrypt_cts(cryptkey, signkey, &incoming, &in_payload)) { break; }
//cout << endl; hexdump(1, &in_payload, sizeof in_payload); cout << endl;
switch(in_payload.tag) {
case requestNonce: handle_nonce(&nonce, &out_payload); break;
case requestBalance: handle_balance(&nonce, incoming.src.username, &in_payload, &out_payload); break;
case requestWithdrawl: handle_withdrawl(&nonce, incoming.src.username, &in_payload, &out_payload); break;
case requestTransfer: handle_transfer(&nonce, incoming.src.username, &in_payload, &out_payload); break;
case requestLogout: goto skip_reply; break;
}
reply:
if(enserialcrypt_stc(cryptkey, signkey, &out_payload, &outgoing)) { break; }
if(write_synchronized(fd, (char*)&outgoing, sizeof outgoing)) { break; }
skip_reply:
} while(in_payload.tag != requestLogout);
close(fd);
}
int bindloop(unsigned short listen_port) {
//Create listener socket
listener_socket = socket( AF_INET, SOCK_STREAM, 0 );
if ( listener_socket < 0 ) {
cerr << "Socket creation failed" << endl;
return EXIT_FAILURE;
}
signal(SIGINT, &handle_control_c);
//Bind socket
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(listen_port);
int len = sizeof(server);
if ( bind( listener_socket, (struct sockaddr *) &server, len ) < 0 ) {
cerr << "Bind failed" << endl;
return EXIT_FAILURE;
}
//Start listening
listen(listener_socket, MAX_CLIENTS);
struct sockaddr_in client;
int fromlen = sizeof(client);
while(true) {
int atm_sd = accept(listener_socket, (struct sockaddr *) &client, (socklen_t*) &fromlen);
if(atm_sd < 0) {
cerr << "Failed to accept connection" << endl;
continue;
}
thread client_thread(handle_connection, atm_sd);
client_thread.detach();
}
}
void print_bankshell_menu() {
cout << endl;
cout << "Please enter your desired command" << endl;
cout << "deposit [username] [amount]" << endl;
cout << "balance [username]" << endl;
cout << endl;
}
void handle_deposit(vector<string> tokens) {
if(tokens.size() != 3) {
cout << "Expected 2 parameters to 'deposit'." << endl;
return;
}
string username = tokens[1];
uint64_t amount = strtol(tokens[2].c_str(), NULL, 10);
lock_guard<mutex> lock(balance_guard);
balances[username] += amount; // No overflow checking since shell is trusted
}
void handle_balance(vector<string> tokens) {
if(tokens.size() != 2) {
cout << "Expected 1 parameter to 'balance'." << endl;
return;
}
string username = tokens[1];
lock_guard<mutex> lock(balance_guard);
cout << "Balance for user '" << username << "': " << balances[username] << " cents" << endl;
}
void bankshell() {
vector<string> tokens;
while(true){
print_bankshell_menu();
prompt:
print_prompt();
tokens = get_tokenized_line();
if(tokens.size() == 0){
goto prompt;
}
if(tokens[0] == "deposit") {
handle_deposit(tokens);
}
else if(tokens[0] == "balance") {
handle_balance(tokens);
}
else if(tokens[0] == "easteregg") {
cout << "Merry nondenominational seasonal holiday!" << endl;
}
else{
cout << "Unknown command '" << tokens[0] << "'" << endl;
}
}
}
int main(int argc, char** argv) {
// Display a usage message
if(argc != 2) {
cout << "Usage: " << argv[0] << " LISTEN_PORT" << endl;
return EXIT_FAILURE;
}
// Get ports
unsigned short listen_port = (unsigned short) atoi(argv[1]);
// Assign default balances
// (doesn't need a mutex since this is before threads are started)
balances["Alice"] = 100 * CENTS_PER_DOLLAR;
balances["Bob"] = 50 * CENTS_PER_DOLLAR;
balances["Eve"] = 0 * CENTS_PER_DOLLAR;
thread shell = thread(bankshell);
shell.detach();
return bindloop(listen_port);
}
<commit_msg>Handle errors (including nonce checking and cleanup) inside handle_connections.<commit_after>#include <iostream>
#include <map>
#include <mutex>
#include <netinet/in.h>
#include <signal.h>
#include <stdlib.h>
#include <thread>
#include <unistd.h>
#include <string.h>
#include "metacard.h"
#include "utils.h"
using namespace std;
// GLOBAL VARIABLES
int listener_socket;
map<string, uint64_t> balances;
mutex balance_guard;
//Close socket on ^C
void handle_control_c(int s) {
(void)s; // silence -Wunused-parameter
close(listener_socket);
exit(EXIT_SUCCESS);
}
const unsigned char* get_cryptkey(const char* name) {
if(!strcmp(name, "Alice")) { return Alice_cryptkey; }
if(!strcmp(name, "Bob")) { return Bob_cryptkey; }
if(!strcmp(name, "Eve")) { return Eve_cryptkey; }
return 0;
}
const unsigned char* get_signkey(const char* name) {
if(!strcmp(name, "Alice")) { return Alice_signkey; }
if(!strcmp(name, "Bob")) { return Bob_signkey; }
if(!strcmp(name, "Eve")) { return Eve_signkey; }
return 0;
}
void handle_nonce(nonce_t* nonce, stc_payload* dst) {
}
void handle_balance(const char* username, const cts_payload* src, stc_payload* dst) {
}
void handle_withdrawl(const char* username, const cts_payload* src, stc_payload* dst) {
}
void handle_transfer(const char* username, const cts_payload* src, stc_payload* dst) {
}
void handle_connection(int fd) {
//cout << "handle_connection(" << fd << ")" << endl;
cts_payload in_payload;
client_to_server incoming;
stc_payload out_payload;
server_to_client outgoing;
nonce_t nonce;
const unsigned char *cryptkey, *signkey;
do {
if(read_synchronized(fd, (char*)&incoming, sizeof incoming)) { break; }
memset(&out_payload, 0, sizeof out_payload);
if(!(cryptkey = get_cryptkey(incoming.src.username)) ||
!(signkey = get_signkey(incoming.src.username))) {
out_payload.tag = invalidUser;
goto reply;
}
if(deserialcrypt_cts(cryptkey, signkey, &incoming, &in_payload)) {
out_payload.tag = invalidNonce; // technically invalid HMAC, but why leak info?
goto reply;
}
//cout << endl; hexdump(1, &in_payload, sizeof in_payload); cout << endl;
if((in_payload.tag != requestNonce) && (in_payload.tag != requestLogout) &&
CRYPTO_memcmp(nonce.nonce, in_payload.nonce.nonce, sizeof nonce)) {
out_payload.tag = invalidNonce;
goto reply;
}
switch(in_payload.tag) {
case requestNonce: handle_nonce(&nonce, &out_payload); break;
case requestBalance: handle_balance(incoming.src.username, &in_payload, &out_payload); break;
case requestWithdrawl: handle_withdrawl(incoming.src.username, &in_payload, &out_payload); break;
case requestTransfer: handle_transfer(incoming.src.username, &in_payload, &out_payload); break;
case requestLogout: goto skip_reply; break;
}
if(in_payload.tag != requestNonce) {
memset(&nonce, 0, sizeof nonce);
}
reply:
if(enserialcrypt_stc(cryptkey, signkey, &out_payload, &outgoing)) { break; }
if(write_synchronized(fd, (char*)&outgoing, sizeof outgoing)) { break; }
skip_reply:
(void)0;
} while(in_payload.tag != requestLogout);
close(fd);
}
int bindloop(unsigned short listen_port) {
//Create listener socket
listener_socket = socket( AF_INET, SOCK_STREAM, 0 );
if ( listener_socket < 0 ) {
cerr << "Socket creation failed" << endl;
return EXIT_FAILURE;
}
signal(SIGINT, &handle_control_c);
//Bind socket
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(listen_port);
int len = sizeof(server);
if ( bind( listener_socket, (struct sockaddr *) &server, len ) < 0 ) {
cerr << "Bind failed" << endl;
return EXIT_FAILURE;
}
//Start listening
listen(listener_socket, MAX_CLIENTS);
struct sockaddr_in client;
int fromlen = sizeof(client);
while(true) {
int atm_sd = accept(listener_socket, (struct sockaddr *) &client, (socklen_t*) &fromlen);
if(atm_sd < 0) {
cerr << "Failed to accept connection" << endl;
continue;
}
thread client_thread(handle_connection, atm_sd);
client_thread.detach();
}
}
void print_bankshell_menu() {
cout << endl;
cout << "Please enter your desired command" << endl;
cout << "deposit [username] [amount]" << endl;
cout << "balance [username]" << endl;
cout << endl;
}
void handle_deposit(vector<string> tokens) {
if(tokens.size() != 3) {
cout << "Expected 2 parameters to 'deposit'." << endl;
return;
}
string username = tokens[1];
uint64_t amount = strtol(tokens[2].c_str(), NULL, 10);
lock_guard<mutex> lock(balance_guard);
balances[username] += amount; // No overflow checking since shell is trusted
}
void handle_balance(vector<string> tokens) {
if(tokens.size() != 2) {
cout << "Expected 1 parameter to 'balance'." << endl;
return;
}
string username = tokens[1];
lock_guard<mutex> lock(balance_guard);
cout << "Balance for user '" << username << "': " << balances[username] << " cents" << endl;
}
void bankshell() {
vector<string> tokens;
while(true){
print_bankshell_menu();
prompt:
print_prompt();
tokens = get_tokenized_line();
if(tokens.size() == 0){
goto prompt;
}
if(tokens[0] == "deposit") {
handle_deposit(tokens);
}
else if(tokens[0] == "balance") {
handle_balance(tokens);
}
else if(tokens[0] == "easteregg") {
cout << "Merry nondenominational seasonal holiday!" << endl;
}
else{
cout << "Unknown command '" << tokens[0] << "'" << endl;
}
}
}
int main(int argc, char** argv) {
// Display a usage message
if(argc != 2) {
cout << "Usage: " << argv[0] << " LISTEN_PORT" << endl;
return EXIT_FAILURE;
}
// Get ports
unsigned short listen_port = (unsigned short) atoi(argv[1]);
// Assign default balances
// (doesn't need a mutex since this is before threads are started)
balances["Alice"] = 100 * CENTS_PER_DOLLAR;
balances["Bob"] = 50 * CENTS_PER_DOLLAR;
balances["Eve"] = 0 * CENTS_PER_DOLLAR;
thread shell = thread(bankshell);
shell.detach();
return bindloop(listen_port);
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2527
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1475035 by johtaylo@johtaylo-jtincrementor2-increment on 2017/10/26 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2528
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/*
* SolverLamg.cpp
*
* Created on: 12.01.2015
* Author: Michael
*/
#include "SolverLamg.h"
#include "LAMGSettings.h"
#include "../CG.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include "../../io/LineFileReader.h"
#include "../../auxiliary/Enforce.h"
#include "../../auxiliary/Timer.h"
namespace NetworKit {
#ifndef NPROFILE
count SolverLamg::minResTime = 0;
count SolverLamg::interpolationTime = 0;
count SolverLamg::restrictionTime = 0;
count SolverLamg::coarsestSolve = 0;
#endif
SolverLamg::SolverLamg(LevelHierarchy &hierarchy, const Smoother &smoother) : hierarchy(hierarchy), smoother(smoother) {
}
void SolverLamg::solve(Vector &x, const Vector &b, LAMGSolverStatus &status) {
if (hierarchy.size() >= 2) {
Vector bc = b;
Vector xc = x;
int finest = 0;
if (hierarchy.getType(1) == ELIMINATION) {
#ifndef NPROFILE
Aux::Timer t; t.start();
#endif
hierarchy.at(1).restrict(b, bc);
if (hierarchy.at(1).getLaplacian().numberOfRows() == 1) {
x = 0.0;
return;
} else {
hierarchy.at(1).coarseType(x, xc);
finest = 1;
}
#ifndef NPROFILE
t.stop();
restrictionTime += t.elapsedMicroseconds();
#endif
}
solveCycle(xc, bc, finest, status);
if (finest == 1) { // interpolate from finest == ELIMINATION level back to actual finest level
#ifndef NPROFILE
Aux::Timer t; t.start();
#endif
hierarchy.at(1).interpolate(xc, x);
#ifndef NPROFILE
t.stop();
interpolationTime += t.elapsedMicroseconds();
#endif
} else {
x = xc;
}
} else {
solveCycle(x, b, 0, status);
}
double residual = (b - hierarchy.at(0).getLaplacian() * x).length();
status.residual = residual;
DEBUG("final residual\t ", residual);
#ifndef NPROFILE
DEBUG("minResTime: ", minResTime / 1000);
DEBUG("interpolationTime: ", interpolationTime / 1000);
DEBUG("restrictionTime: ", restrictionTime / 1000);
DEBUG("coarsestSolve: ", coarsestSolve / 1000);
#endif
}
void SolverLamg::solveCycle(Vector &x, const Vector &b, int finest, LAMGSolverStatus &status) {
Aux::Timer timer;
timer.start();
// data structures for iterate recombination
history = std::vector<std::vector<Vector>>(hierarchy.size());
rHistory = std::vector<std::vector<Vector>>(hierarchy.size());
latestIterate = std::vector<index>(hierarchy.size(), 0);
numActiveIterates = std::vector<count>(hierarchy.size(), 0);
int coarsest = hierarchy.size() - 1;
std::vector<count> numVisits(coarsest);
std::vector<Vector> X(hierarchy.size());
std::vector<Vector> B(hierarchy.size());
for (index i = 0; i < hierarchy.size(); ++i) {
history[i] = std::vector<Vector>(MAX_COMBINED_ITERATES, Vector(hierarchy.at(i).getNumberOfNodes()));
rHistory[i] = std::vector<Vector>(MAX_COMBINED_ITERATES, Vector(hierarchy.at(i).getNumberOfNodes()));
}
Vector r = b - hierarchy.at(finest).getLaplacian() * x;
double residual = r.length();
double finalResidual = residual * status.desiredResidualReduction;
double lastResidual = std::numeric_limits<double>::max();
count iterations = 0;
status.residualHistory.emplace_back(residual);
while (residual > finalResidual && residual < lastResidual && iterations < status.maxIters && timer.elapsedMilliseconds() <= status.maxConvergenceTime ) {
DEBUG("iter ", iterations, " r=", residual);
lastResidual = residual;
cycle(x, b, finest, coarsest, numVisits, X, B, status);
r = b - hierarchy.at(finest).getLaplacian() * x;
residual = r.length();
status.residualHistory.emplace_back(residual);
iterations++;
}
timer.stop();
status.numIters = iterations;
status.residual = r.length();
status.converged = r.length() <= finalResidual;
DEBUG("nIter\t ", iterations);
}
void SolverLamg::cycle(Vector &x, const Vector &b, int finest, int coarsest, std::vector<count> &numVisits, std::vector<Vector> &X, std::vector<Vector> &B, const LAMGSolverStatus &status) {
std::fill(numVisits.begin(), numVisits.end(), 0);
X[finest] = x;
B[finest] = b;
#ifndef NPROFILE
Aux::Timer t;
#endif
int currLvl = finest;
int nextLvl = finest;
double maxVisits = 0.0;
saveIterate(currLvl, X[currLvl], B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl]);
while (true) {
if (currLvl == coarsest) {
#ifndef NPROFILE
t.start();
#endif
nextLvl = currLvl - 1;
if (currLvl == finest) { // finest level
X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], status.numPreSmoothIters);
} else {
X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], 50);
}
#ifndef NPROFILE
t.stop();
coarsestSolve += t.elapsedMicroseconds();
#endif
} else {
if (currLvl == finest) {
maxVisits = 1.0;
} else {
maxVisits = hierarchy.cycleIndex(currLvl) * numVisits[currLvl-1];
}
if (numVisits[currLvl] < maxVisits) {
nextLvl = currLvl + 1;
} else {
nextLvl = currLvl - 1;
}
}
if (nextLvl < finest) break;
if (nextLvl > currLvl) { // preProcess
#ifndef NPROFILE
t.start();
#endif
numVisits[currLvl]++;
if (hierarchy.getType(nextLvl) != ELIMINATION) {
X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], status.numPreSmoothIters);
}
if (hierarchy.getType(nextLvl) == ELIMINATION) {
hierarchy.at(nextLvl).restrict(B[currLvl], B[nextLvl]);
} else {
hierarchy.at(nextLvl).restrict(B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl], B[nextLvl]);
}
hierarchy.at(nextLvl).coarseType(X[currLvl], X[nextLvl]);
clearHistory(nextLvl);
if (currLvl > finest) {
clearHistory(currLvl);
}
#ifndef NPROFILE
t.stop();
restrictionTime += t.elapsedMicroseconds();
#endif
} else { // postProcess
#ifndef NPROFILE
t.start();
#endif
if (currLvl == coarsest || hierarchy.getType(currLvl+1) != ELIMINATION) {
minRes(currLvl, X[currLvl], B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl]);
}
if (nextLvl > finest) {
saveIterate(nextLvl, X[nextLvl], B[nextLvl] - hierarchy.at(nextLvl).getLaplacian() * X[nextLvl]);
}
if (hierarchy.getType(currLvl) == ELIMINATION) {
hierarchy.at(currLvl).interpolate(X[currLvl], X[nextLvl]);
} else {
Vector xf = X[nextLvl];
hierarchy.at(currLvl).interpolate(X[currLvl], xf);
X[nextLvl] += xf;
}
if (hierarchy.getType(currLvl) != ELIMINATION) {
X[nextLvl] = smoother.relax(hierarchy.at(nextLvl).getLaplacian(), B[nextLvl], X[nextLvl], status.numPostSmoothIters);
}
#ifndef NPROFILE
t.stop();
interpolationTime += t.elapsedMicroseconds();
#endif
}
currLvl = nextLvl;
} // while
// post-cycle finest
if (hierarchy.size() > finest + 1 && hierarchy.getType(finest+1) != ELIMINATION) { // do an iterate recombination on calculated solutions
minRes(finest, X[finest], B[finest] - hierarchy.at(finest).getLaplacian() * X[finest]);
}
X[finest] -= X[finest].mean();
x = X[finest];
}
void SolverLamg::saveIterate(index level, const Vector &x, const Vector &r) {
// update latest pointer
index i = latestIterate[level];
latestIterate[level] = (i+1) % MAX_COMBINED_ITERATES;
// update numIterates
if (numActiveIterates[level] < MAX_COMBINED_ITERATES) {
numActiveIterates[level]++;
}
// update history array
history[level][i] = x;
rHistory[level][i] = r;
}
void SolverLamg::clearHistory(index level) {
latestIterate[level] = 0;
numActiveIterates[level] = 0;
}
void SolverLamg::minRes(index level, Vector &x, const Vector &r) {
#ifndef NPROFILE
Aux::Timer t;
t.start();
#endif
if (numActiveIterates[level] > 0) {
count n = numActiveIterates[level];
std::vector<std::pair<index, index>> AEpos;
std::vector<double> AEvalues;
std::vector<std::pair<index, index>> Epos;
std::vector<double> Evalues;
for (index i = 0; i < r.getDimension(); ++i) {
for (index k = 0; k < n; ++k) {
double AEvalue = r[i] - rHistory[level][k][i];
if (std::abs(AEvalue) > 1e-9) {
AEpos.push_back(std::make_pair(i, k));
AEvalues.push_back(AEvalue);
}
double Eval = history[level][k][i] - x[i];
if (std::abs(Eval) > 1e-9) {
Epos.push_back(std::make_pair(i, k));
Evalues.push_back(Eval);
}
}
}
CSRMatrix AE(r.getDimension(), n, AEpos, AEvalues);
CSRMatrix E(r.getDimension(), n, Epos, Evalues);
Vector alpha = smoother.relax(CSRMatrix::mTmMultiply(AE, AE), CSRMatrix::mTvMultiply(AE, r), Vector(n, 0.0), 10);
x += E * alpha;
}
#ifndef NPROFILE
t.stop();
minResTime += t.elapsedMicroseconds();
#endif
}
} /* namespace NetworKit */
<commit_msg>fixed comparison between signed and unsigned integer warning<commit_after>/*
* SolverLamg.cpp
*
* Created on: 12.01.2015
* Author: Michael
*/
#include "SolverLamg.h"
#include "LAMGSettings.h"
#include "../CG.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include "../../io/LineFileReader.h"
#include "../../auxiliary/Enforce.h"
#include "../../auxiliary/Timer.h"
namespace NetworKit {
#ifndef NPROFILE
count SolverLamg::minResTime = 0;
count SolverLamg::interpolationTime = 0;
count SolverLamg::restrictionTime = 0;
count SolverLamg::coarsestSolve = 0;
#endif
SolverLamg::SolverLamg(LevelHierarchy &hierarchy, const Smoother &smoother) : hierarchy(hierarchy), smoother(smoother) {
}
void SolverLamg::solve(Vector &x, const Vector &b, LAMGSolverStatus &status) {
if (hierarchy.size() >= 2) {
Vector bc = b;
Vector xc = x;
int finest = 0;
if (hierarchy.getType(1) == ELIMINATION) {
#ifndef NPROFILE
Aux::Timer t; t.start();
#endif
hierarchy.at(1).restrict(b, bc);
if (hierarchy.at(1).getLaplacian().numberOfRows() == 1) {
x = 0.0;
return;
} else {
hierarchy.at(1).coarseType(x, xc);
finest = 1;
}
#ifndef NPROFILE
t.stop();
restrictionTime += t.elapsedMicroseconds();
#endif
}
solveCycle(xc, bc, finest, status);
if (finest == 1) { // interpolate from finest == ELIMINATION level back to actual finest level
#ifndef NPROFILE
Aux::Timer t; t.start();
#endif
hierarchy.at(1).interpolate(xc, x);
#ifndef NPROFILE
t.stop();
interpolationTime += t.elapsedMicroseconds();
#endif
} else {
x = xc;
}
} else {
solveCycle(x, b, 0, status);
}
double residual = (b - hierarchy.at(0).getLaplacian() * x).length();
status.residual = residual;
DEBUG("final residual\t ", residual);
#ifndef NPROFILE
DEBUG("minResTime: ", minResTime / 1000);
DEBUG("interpolationTime: ", interpolationTime / 1000);
DEBUG("restrictionTime: ", restrictionTime / 1000);
DEBUG("coarsestSolve: ", coarsestSolve / 1000);
#endif
}
void SolverLamg::solveCycle(Vector &x, const Vector &b, int finest, LAMGSolverStatus &status) {
Aux::Timer timer;
timer.start();
// data structures for iterate recombination
history = std::vector<std::vector<Vector>>(hierarchy.size());
rHistory = std::vector<std::vector<Vector>>(hierarchy.size());
latestIterate = std::vector<index>(hierarchy.size(), 0);
numActiveIterates = std::vector<count>(hierarchy.size(), 0);
int coarsest = hierarchy.size() - 1;
std::vector<count> numVisits(coarsest);
std::vector<Vector> X(hierarchy.size());
std::vector<Vector> B(hierarchy.size());
for (index i = 0; i < hierarchy.size(); ++i) {
history[i] = std::vector<Vector>(MAX_COMBINED_ITERATES, Vector(hierarchy.at(i).getNumberOfNodes()));
rHistory[i] = std::vector<Vector>(MAX_COMBINED_ITERATES, Vector(hierarchy.at(i).getNumberOfNodes()));
}
Vector r = b - hierarchy.at(finest).getLaplacian() * x;
double residual = r.length();
double finalResidual = residual * status.desiredResidualReduction;
double lastResidual = std::numeric_limits<double>::max();
count iterations = 0;
status.residualHistory.emplace_back(residual);
while (residual > finalResidual && residual < lastResidual && iterations < status.maxIters && timer.elapsedMilliseconds() <= status.maxConvergenceTime ) {
DEBUG("iter ", iterations, " r=", residual);
lastResidual = residual;
cycle(x, b, finest, coarsest, numVisits, X, B, status);
r = b - hierarchy.at(finest).getLaplacian() * x;
residual = r.length();
status.residualHistory.emplace_back(residual);
iterations++;
}
timer.stop();
status.numIters = iterations;
status.residual = r.length();
status.converged = r.length() <= finalResidual;
DEBUG("nIter\t ", iterations);
}
void SolverLamg::cycle(Vector &x, const Vector &b, int finest, int coarsest, std::vector<count> &numVisits, std::vector<Vector> &X, std::vector<Vector> &B, const LAMGSolverStatus &status) {
std::fill(numVisits.begin(), numVisits.end(), 0);
X[finest] = x;
B[finest] = b;
#ifndef NPROFILE
Aux::Timer t;
#endif
int currLvl = finest;
int nextLvl = finest;
double maxVisits = 0.0;
saveIterate(currLvl, X[currLvl], B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl]);
while (true) {
if (currLvl == coarsest) {
#ifndef NPROFILE
t.start();
#endif
nextLvl = currLvl - 1;
if (currLvl == finest) { // finest level
X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], status.numPreSmoothIters);
} else {
X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], 50);
}
#ifndef NPROFILE
t.stop();
coarsestSolve += t.elapsedMicroseconds();
#endif
} else {
if (currLvl == finest) {
maxVisits = 1.0;
} else {
maxVisits = hierarchy.cycleIndex(currLvl) * numVisits[currLvl-1];
}
if (numVisits[currLvl] < maxVisits) {
nextLvl = currLvl + 1;
} else {
nextLvl = currLvl - 1;
}
}
if (nextLvl < finest) break;
if (nextLvl > currLvl) { // preProcess
#ifndef NPROFILE
t.start();
#endif
numVisits[currLvl]++;
if (hierarchy.getType(nextLvl) != ELIMINATION) {
X[currLvl] = smoother.relax(hierarchy.at(currLvl).getLaplacian(), B[currLvl], X[currLvl], status.numPreSmoothIters);
}
if (hierarchy.getType(nextLvl) == ELIMINATION) {
hierarchy.at(nextLvl).restrict(B[currLvl], B[nextLvl]);
} else {
hierarchy.at(nextLvl).restrict(B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl], B[nextLvl]);
}
hierarchy.at(nextLvl).coarseType(X[currLvl], X[nextLvl]);
clearHistory(nextLvl);
if (currLvl > finest) {
clearHistory(currLvl);
}
#ifndef NPROFILE
t.stop();
restrictionTime += t.elapsedMicroseconds();
#endif
} else { // postProcess
#ifndef NPROFILE
t.start();
#endif
if (currLvl == coarsest || hierarchy.getType(currLvl+1) != ELIMINATION) {
minRes(currLvl, X[currLvl], B[currLvl] - hierarchy.at(currLvl).getLaplacian() * X[currLvl]);
}
if (nextLvl > finest) {
saveIterate(nextLvl, X[nextLvl], B[nextLvl] - hierarchy.at(nextLvl).getLaplacian() * X[nextLvl]);
}
if (hierarchy.getType(currLvl) == ELIMINATION) {
hierarchy.at(currLvl).interpolate(X[currLvl], X[nextLvl]);
} else {
Vector xf = X[nextLvl];
hierarchy.at(currLvl).interpolate(X[currLvl], xf);
X[nextLvl] += xf;
}
if (hierarchy.getType(currLvl) != ELIMINATION) {
X[nextLvl] = smoother.relax(hierarchy.at(nextLvl).getLaplacian(), B[nextLvl], X[nextLvl], status.numPostSmoothIters);
}
#ifndef NPROFILE
t.stop();
interpolationTime += t.elapsedMicroseconds();
#endif
}
currLvl = nextLvl;
} // while
// post-cycle finest
if ((int64_t) hierarchy.size() > finest + 1 && hierarchy.getType(finest+1) != ELIMINATION) { // do an iterate recombination on calculated solutions
minRes(finest, X[finest], B[finest] - hierarchy.at(finest).getLaplacian() * X[finest]);
}
X[finest] -= X[finest].mean();
x = X[finest];
}
void SolverLamg::saveIterate(index level, const Vector &x, const Vector &r) {
// update latest pointer
index i = latestIterate[level];
latestIterate[level] = (i+1) % MAX_COMBINED_ITERATES;
// update numIterates
if (numActiveIterates[level] < MAX_COMBINED_ITERATES) {
numActiveIterates[level]++;
}
// update history array
history[level][i] = x;
rHistory[level][i] = r;
}
void SolverLamg::clearHistory(index level) {
latestIterate[level] = 0;
numActiveIterates[level] = 0;
}
void SolverLamg::minRes(index level, Vector &x, const Vector &r) {
#ifndef NPROFILE
Aux::Timer t;
t.start();
#endif
if (numActiveIterates[level] > 0) {
count n = numActiveIterates[level];
std::vector<std::pair<index, index>> AEpos;
std::vector<double> AEvalues;
std::vector<std::pair<index, index>> Epos;
std::vector<double> Evalues;
for (index i = 0; i < r.getDimension(); ++i) {
for (index k = 0; k < n; ++k) {
double AEvalue = r[i] - rHistory[level][k][i];
if (std::abs(AEvalue) > 1e-9) {
AEpos.push_back(std::make_pair(i, k));
AEvalues.push_back(AEvalue);
}
double Eval = history[level][k][i] - x[i];
if (std::abs(Eval) > 1e-9) {
Epos.push_back(std::make_pair(i, k));
Evalues.push_back(Eval);
}
}
}
CSRMatrix AE(r.getDimension(), n, AEpos, AEvalues);
CSRMatrix E(r.getDimension(), n, Epos, Evalues);
Vector alpha = smoother.relax(CSRMatrix::mTmMultiply(AE, AE), CSRMatrix::mTvMultiply(AE, r), Vector(n, 0.0), 10);
x += E * alpha;
}
#ifndef NPROFILE
t.stop();
minResTime += t.elapsedMicroseconds();
#endif
}
} /* namespace NetworKit */
<|endoftext|> |
<commit_before>// Windowmenu.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef WINDOWMENU_HH
#define WINDOWMENU_HH
// forward declaration
class Windowmenu;
class SendtoWorkspaceMenu;
class Fluxbox;
class FluxboxWindow;
class Toolbar;
#include "Basemenu.hh"
class Windowmenu : public Basemenu {
private:
FluxboxWindow *window;
BScreen *screen;
class SendtoWorkspacemenu : public Basemenu {
private:
Windowmenu *windowmenu;
protected:
virtual void itemSelected(int button, unsigned int index);
public:
SendtoWorkspacemenu(Windowmenu *);
inline Windowmenu *getWindowMenu() const { return windowmenu; }
void update(void);
virtual void show(void);
};
class SendGroupToWorkspacemenu : public SendtoWorkspacemenu {
protected:
virtual void itemSelected(int button, unsigned int index);
public:
SendGroupToWorkspacemenu(Windowmenu *winmenu);
};
SendtoWorkspacemenu *sendToMenu;
SendGroupToWorkspacemenu *sendGroupToMenu;
friend class SendtoWorkspacemenu;
friend class SendGroupToWorkspacemenu;
protected:
virtual void itemSelected(int button, unsigned int index);
public:
Windowmenu(FluxboxWindow *);
virtual ~Windowmenu(void);
inline Basemenu *getSendToMenu(void) { return static_cast<Basemenu *>(sendToMenu); }
inline Basemenu *getSendGroupToMenu(void) { return static_cast<Basemenu *>(sendGroupToMenu); }
void reconfigure(void);
void setClosable(void);
virtual void show(void);
};
#endif // __Windowmenu_hh
<commit_msg>changed some pointer to referenses<commit_after>// Windowmenu.hh for Blackbox - an X11 Window manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef WINDOWMENU_HH
#define WINDOWMENU_HH
#include "Basemenu.hh"
class FluxboxWindow;
class Windowmenu : public Basemenu {
public:
Windowmenu(FluxboxWindow &fbwin);
virtual ~Windowmenu();
const Basemenu &getSendToMenu() const { return sendToMenu; }
Basemenu &getSendToMenu() { return sendToMenu; }
const Basemenu &getSendGroupToMenu() const { return sendGroupToMenu; }
Basemenu &getSendGroupToMenu() { return sendGroupToMenu; }
void reconfigure();
void setClosable();
virtual void show();
protected:
virtual void itemSelected(int button, unsigned int index);
private:
FluxboxWindow &window;
BScreen *screen;
class SendtoWorkspacemenu : public Basemenu {
public:
SendtoWorkspacemenu(Windowmenu *);
inline Windowmenu *getWindowMenu() const { return windowmenu; }
void update();
virtual void show();
protected:
virtual void itemSelected(int button, unsigned int index);
private:
Windowmenu *windowmenu;
};
class SendGroupToWorkspacemenu : public SendtoWorkspacemenu {
public:
SendGroupToWorkspacemenu(Windowmenu *winmenu);
protected:
virtual void itemSelected(int button, unsigned int index);
};
SendtoWorkspacemenu sendToMenu;
SendGroupToWorkspacemenu sendGroupToMenu;
};
#endif // WINDOWMENU_HH
<|endoftext|> |
<commit_before>/*
* Copyright 2013 The OpenMx Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <valarray>
#include "omxState.h"
#include "omxFitFunction.h"
#include "omxExportBackendState.h"
#include "Compute.h"
#include "matrix.h"
#include "Eigen/Eigenvalues"
class ComputeNR : public omxCompute {
typedef omxCompute super;
omxMatrix *fitMatrix;
int maxIter;
double tolerance;
int verbose;
double priorSpeed;
int minorIter;
double refFit;
void lineSearch(FitContext *fc, int iter, double *maxAdj, double *maxAdjSigned,
int *maxAdjParam, double *improvement);
public:
virtual void initFromFrontend(SEXP rObj);
virtual void computeImpl(FitContext *fc);
virtual void reportResults(FitContext *fc, MxRList *slots, MxRList *out);
};
class omxCompute *newComputeNewtonRaphson()
{
return new ComputeNR();
}
void ComputeNR::initFromFrontend(SEXP rObj)
{
super::initFromFrontend(rObj);
fitMatrix = omxNewMatrixFromSlot(rObj, globalState, "fitfunction");
setFreeVarGroup(fitMatrix->fitFunction, varGroup);
omxCompleteFitFunction(fitMatrix);
if (!fitMatrix->fitFunction->hessianAvailable ||
!fitMatrix->fitFunction->gradientAvailable) {
Rf_error("Newton-Raphson requires derivatives");
}
SEXP slotValue;
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("maxIter")));
maxIter = INTEGER(slotValue)[0];
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("tolerance")));
tolerance = REAL(slotValue)[0];
if (tolerance <= 0) Rf_error("tolerance must be positive");
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("verbose")));
verbose = Rf_asInteger(slotValue);
}
void omxApproxInvertPosDefTriangular(int dim, double *hess, double *ihess, double *stress)
{
int info;
int retries = 0;
const int maxRetries = 31; // assume >=32 bit integers
double adj = 0;
do {
memcpy(ihess, hess, sizeof(double) * dim * dim);
if (retries >= 1) {
int th = maxRetries - retries;
if (th > 0) {
adj = 1.0/(1 << th);
} else {
adj = (1 << -th);
}
for (int px=0; px < dim; ++px) {
ihess[px * dim + px] += adj;
}
}
Matrix ihessMat(ihess, dim, dim);
info = InvertSymmetricPosDef(ihessMat, 'L');
if (info == 0) break;
} while (++retries < maxRetries * 1.5);
if (info > 0) {
// or just set stress to something high and return? TODO
omxRaiseErrorf("Hessian is not even close to positive definite (order %d)", info);
return;
}
if (stress) *stress = adj;
}
void omxApproxInvertPackedPosDefTriangular(int dim, int *mask, double *packedHess, double *stress)
{
int mdim = 0;
for (int dx=0; dx < dim; ++dx) if (mask[dx]) mdim += 1;
if (mdim == 0) {
*stress = 0;
return;
}
std::vector<double> hess(mdim * mdim, 0.0);
for (int d1=0, px=0, m1=-1; d1 < dim; ++d1) {
if (mask[d1]) ++m1;
for (int d2=0, m2=-1; d2 <= d1; ++d2) {
if (mask[d2]) ++m2;
if (mask[d1] && mask[d2]) {
hess[m2 * mdim + m1] = packedHess[px];
}
++px;
}
}
std::vector<double> ihess(mdim * mdim);
omxApproxInvertPosDefTriangular(mdim, hess.data(), ihess.data(), stress);
for (int d1=0, px=0, m1=-1; d1 < dim; ++d1) {
if (mask[d1]) ++m1;
for (int d2=0, m2=-1; d2 <= d1; ++d2) {
if (mask[d2]) ++m2;
if (mask[d1] && mask[d2]) {
packedHess[px] = *stress? 0 : ihess[m2 * mdim + m1];
}
++px;
}
}
}
void pda(const double *ar, int rows, int cols);
void ComputeNR::lineSearch(FitContext *fc, int iter, double *maxAdj, double *maxAdjSigned,
int *maxAdjParam, double *improvement)
{
const size_t numParam = varGroup->vars.size();
const double epsilon = .3;
bool steepestDescent = false;
Eigen::Map<Eigen::VectorXd> prevEst(fc->est, numParam);
int want = FF_COMPUTE_GRADIENT | FF_COMPUTE_IHESSIAN;
if (iter == 1) {
want |= FF_COMPUTE_FIT;
}
Global->checkpointPrefit(fc, fc->est, false);
omxFitFunctionCompute(fitMatrix->fitFunction, want, fc);
Global->checkpointPostfit(fc);
double speed = std::min(priorSpeed * 1.5, 1.0);
if (iter == 1) refFit = fitMatrix->data[0];
Eigen::VectorXd searchDir(fc->ihessGradProd());
double targetImprovement = searchDir.dot(fc->grad);
if (targetImprovement < tolerance) {
if (verbose >= 4) mxLog("%s: target improvement %f too small, using steepest descent",
name, targetImprovement);
steepestDescent = true;
if (0 && fc->grad.norm() > tolerance) {
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;
es.compute(fc->getDenseIHess());
Eigen::VectorXd ev(es.eigenvalues());
mxLog("ihess EV");
pda(ev.data(), 1, numParam);
mxLog("ihess");
Eigen::MatrixXd ihess(fc->getDenseIHess());
ihess.triangularView<Eigen::StrictlyLower>() = ihess.transpose().triangularView<Eigen::StrictlyLower>();
pda(ihess.data(), numParam, numParam);
}
searchDir = fc->grad;
targetImprovement = searchDir.norm();
if (targetImprovement < tolerance) return;
//speed = std::max(speed, .1); // expect steepestDescent
}
// This is based on the Goldstein test. However, we don't enforce
// a lower bound on the improvement.
int probeCount = 0;
Eigen::VectorXd trial;
trial.resize(numParam);
double bestSpeed = 0;
double bestImproved = 0;
double goodness = 0;
double bestFit = 0;
while (++probeCount < 16) {
const double scaledTarget = speed * targetImprovement;
if (scaledTarget < tolerance) return;
trial = prevEst - speed * searchDir;
++minorIter;
fc->copyParamToModel(globalState, trial.data());
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_FIT, fc);
if (verbose >= 4) mxLog("%s: speed %f for target %.3g fit %f ref %f",
name, speed, scaledTarget, fitMatrix->data[0], refFit);
if (!std::isfinite(fitMatrix->data[0])) {
speed *= .1;
continue;
}
const double improved = refFit - fitMatrix->data[0];
if (improved <= 0) {
speed *= .1;
continue;
}
bestImproved = improved;
bestSpeed = speed;
bestFit = fitMatrix->data[0];
goodness = improved / scaledTarget;
if (verbose >= 3) mxLog("%s: viable speed %f for improvement %.3g goodness %f",
name, bestSpeed, bestImproved, goodness);
break;
}
if (bestSpeed == 0) return;
if (0 && speed < 1 && goodness < epsilon) { // seems to be not worth it
int retries = 4; // search up to 2.4*speed
speed *= 1.25;
while (--retries > 0 && goodness < epsilon) {
++probeCount;
trial = prevEst - speed * searchDir;
++minorIter;
fc->copyParamToModel(globalState, trial.data());
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_FIT, fc);
if (!std::isfinite(fitMatrix->data[0])) break;
const double improved = refFit - fitMatrix->data[0];
if (bestImproved >= improved) break;
bestFit = fitMatrix->data[0];
bestImproved = improved;
bestSpeed = speed;
goodness = improved / (speed * targetImprovement);
}
}
if (verbose >= 3) mxLog("%s: using steepestDescent %d probes %d speed %f improved %.3g",
name, steepestDescent, probeCount, bestSpeed, bestImproved);
if (!steepestDescent) priorSpeed = bestSpeed;
trial = prevEst - bestSpeed * searchDir;
*maxAdj = 0;
for (size_t px=0; px < numParam; ++px) {
double oldEst = fc->est[px];
double badj = fabs(oldEst - trial(px));
if (*maxAdj < badj) {
*maxAdj = badj;
*maxAdjSigned = oldEst - trial(px);
*maxAdjParam = px;
}
}
memcpy(fc->est, trial.data(), sizeof(double) * numParam);
*improvement = bestImproved;
refFit = bestFit;
}
void ComputeNR::computeImpl(FitContext *fc)
{
// complain if there are non-linear constraints TODO
size_t numParam = varGroup->vars.size();
if (numParam <= 0) {
Rf_error("Model has no free parameters");
return;
}
fc->flavor.assign(numParam, NULL);
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_PARAMFLAVOR, fc);
// flavor used for debug output only
for (size_t px=0; px < numParam; ++px) {
if (!fc->flavor[px]) fc->flavor[px] = "?";
}
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_PREOPTIMIZE, fc);
priorSpeed = 1;
minorIter = 0;
int startIter = fc->iterations;
bool converged = false;
double maxAdj = 0;
double maxAdjSigned = 0;
int maxAdjParam = -1;
const char *maxAdjFlavor = "?";
if (verbose >= 2) {
mxLog("Welcome to Newton-Raphson (tolerance %.3g, max iter %d)",
tolerance, maxIter);
}
while (1) {
fc->iterations += 1;
int iter = fc->iterations - startIter;
if (verbose >= 2) {
if (iter == 1) {
mxLog("%s: begin iter %d/%d", name, iter, maxIter);
} else {
const char *pname = "none";
if (maxAdjParam >= 0) pname = fc->varGroup->vars[maxAdjParam]->name;
mxLog("%s: begin iter %d/%d (prev maxAdj %.3g for %s %s)",
name, iter, maxIter, maxAdjSigned, maxAdjFlavor, pname);
}
}
fc->grad = Eigen::VectorXd::Zero(fc->numParam);
fc->clearHessian();
maxAdj = 0;
double improvement = 0;
lineSearch(fc, iter, &maxAdj, &maxAdjSigned, &maxAdjParam, &improvement);
converged = improvement < tolerance;
maxAdjFlavor = fc->flavor[maxAdjParam];
fc->copyParamToModel(globalState);
R_CheckUserInterrupt();
if (converged || iter >= maxIter || isErrorRaised(globalState)) break;
}
if (converged) {
fc->inform = INFORM_CONVERGED_OPTIMUM;
fc->wanted |= FF_COMPUTE_BESTFIT;
if (verbose >= 1) {
int iter = fc->iterations - startIter;
mxLog("%s: converged in %d cycles (%d minor iterations)", name, iter, minorIter);
}
} else {
fc->inform = INFORM_ITERATION_LIMIT;
if (verbose >= 1) {
int iter = fc->iterations - startIter;
mxLog("%s: failed to converge after %d cycles (%d minor iterations)",
name, iter, minorIter);
}
}
}
void ComputeNR::reportResults(FitContext *fc, MxRList *slots, MxRList *output)
{
omxPopulateFitFunction(fitMatrix, output);
}
<commit_msg>Checkpoint correct fit in Newton-Raphson<commit_after>/*
* Copyright 2013 The OpenMx Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <valarray>
#include "omxState.h"
#include "omxFitFunction.h"
#include "omxExportBackendState.h"
#include "Compute.h"
#include "matrix.h"
#include "Eigen/Eigenvalues"
class ComputeNR : public omxCompute {
typedef omxCompute super;
omxMatrix *fitMatrix;
int maxIter;
double tolerance;
int verbose;
double priorSpeed;
int minorIter;
double refFit;
void lineSearch(FitContext *fc, int iter, double *maxAdj, double *maxAdjSigned,
int *maxAdjParam, double *improvement);
public:
virtual void initFromFrontend(SEXP rObj);
virtual void computeImpl(FitContext *fc);
virtual void reportResults(FitContext *fc, MxRList *slots, MxRList *out);
};
class omxCompute *newComputeNewtonRaphson()
{
return new ComputeNR();
}
void ComputeNR::initFromFrontend(SEXP rObj)
{
super::initFromFrontend(rObj);
fitMatrix = omxNewMatrixFromSlot(rObj, globalState, "fitfunction");
setFreeVarGroup(fitMatrix->fitFunction, varGroup);
omxCompleteFitFunction(fitMatrix);
if (!fitMatrix->fitFunction->hessianAvailable ||
!fitMatrix->fitFunction->gradientAvailable) {
Rf_error("Newton-Raphson requires derivatives");
}
SEXP slotValue;
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("maxIter")));
maxIter = INTEGER(slotValue)[0];
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("tolerance")));
tolerance = REAL(slotValue)[0];
if (tolerance <= 0) Rf_error("tolerance must be positive");
Rf_protect(slotValue = R_do_slot(rObj, Rf_install("verbose")));
verbose = Rf_asInteger(slotValue);
}
void omxApproxInvertPosDefTriangular(int dim, double *hess, double *ihess, double *stress)
{
int info;
int retries = 0;
const int maxRetries = 31; // assume >=32 bit integers
double adj = 0;
do {
memcpy(ihess, hess, sizeof(double) * dim * dim);
if (retries >= 1) {
int th = maxRetries - retries;
if (th > 0) {
adj = 1.0/(1 << th);
} else {
adj = (1 << -th);
}
for (int px=0; px < dim; ++px) {
ihess[px * dim + px] += adj;
}
}
Matrix ihessMat(ihess, dim, dim);
info = InvertSymmetricPosDef(ihessMat, 'L');
if (info == 0) break;
} while (++retries < maxRetries * 1.5);
if (info > 0) {
// or just set stress to something high and return? TODO
omxRaiseErrorf("Hessian is not even close to positive definite (order %d)", info);
return;
}
if (stress) *stress = adj;
}
void omxApproxInvertPackedPosDefTriangular(int dim, int *mask, double *packedHess, double *stress)
{
int mdim = 0;
for (int dx=0; dx < dim; ++dx) if (mask[dx]) mdim += 1;
if (mdim == 0) {
*stress = 0;
return;
}
std::vector<double> hess(mdim * mdim, 0.0);
for (int d1=0, px=0, m1=-1; d1 < dim; ++d1) {
if (mask[d1]) ++m1;
for (int d2=0, m2=-1; d2 <= d1; ++d2) {
if (mask[d2]) ++m2;
if (mask[d1] && mask[d2]) {
hess[m2 * mdim + m1] = packedHess[px];
}
++px;
}
}
std::vector<double> ihess(mdim * mdim);
omxApproxInvertPosDefTriangular(mdim, hess.data(), ihess.data(), stress);
for (int d1=0, px=0, m1=-1; d1 < dim; ++d1) {
if (mask[d1]) ++m1;
for (int d2=0, m2=-1; d2 <= d1; ++d2) {
if (mask[d2]) ++m2;
if (mask[d1] && mask[d2]) {
packedHess[px] = *stress? 0 : ihess[m2 * mdim + m1];
}
++px;
}
}
}
void pda(const double *ar, int rows, int cols);
void ComputeNR::lineSearch(FitContext *fc, int iter, double *maxAdj, double *maxAdjSigned,
int *maxAdjParam, double *improvement)
{
const size_t numParam = varGroup->vars.size();
const double epsilon = .3;
bool steepestDescent = false;
Eigen::Map<Eigen::VectorXd> prevEst(fc->est, numParam);
int want = FF_COMPUTE_GRADIENT | FF_COMPUTE_IHESSIAN;
if (iter == 1) {
want |= FF_COMPUTE_FIT;
}
Global->checkpointPrefit(fc, fc->est, false);
omxFitFunctionCompute(fitMatrix->fitFunction, want, fc);
if (iter == 1) refFit = fitMatrix->data[0];
fc->fit = refFit;
Global->checkpointPostfit(fc);
double speed = std::min(priorSpeed * 1.5, 1.0);
Eigen::VectorXd searchDir(fc->ihessGradProd());
double targetImprovement = searchDir.dot(fc->grad);
if (targetImprovement < tolerance) {
if (verbose >= 4) mxLog("%s: target improvement %f too small, using steepest descent",
name, targetImprovement);
steepestDescent = true;
if (0 && fc->grad.norm() > tolerance) {
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es;
es.compute(fc->getDenseIHess());
Eigen::VectorXd ev(es.eigenvalues());
mxLog("ihess EV");
pda(ev.data(), 1, numParam);
mxLog("ihess");
Eigen::MatrixXd ihess(fc->getDenseIHess());
ihess.triangularView<Eigen::StrictlyLower>() = ihess.transpose().triangularView<Eigen::StrictlyLower>();
pda(ihess.data(), numParam, numParam);
}
searchDir = fc->grad;
targetImprovement = searchDir.norm();
if (targetImprovement < tolerance) return;
//speed = std::max(speed, .1); // expect steepestDescent
}
// This is based on the Goldstein test. However, we don't enforce
// a lower bound on the improvement.
int probeCount = 0;
Eigen::VectorXd trial;
trial.resize(numParam);
double bestSpeed = 0;
double bestImproved = 0;
double goodness = 0;
double bestFit = 0;
while (++probeCount < 16) {
const double scaledTarget = speed * targetImprovement;
if (scaledTarget < tolerance) return;
trial = prevEst - speed * searchDir;
++minorIter;
fc->copyParamToModel(globalState, trial.data());
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_FIT, fc);
if (verbose >= 4) mxLog("%s: speed %f for target %.3g fit %f ref %f",
name, speed, scaledTarget, fitMatrix->data[0], refFit);
if (!std::isfinite(fitMatrix->data[0])) {
speed *= .1;
continue;
}
const double improved = refFit - fitMatrix->data[0];
if (improved <= 0) {
speed *= .1;
continue;
}
bestImproved = improved;
bestSpeed = speed;
bestFit = fitMatrix->data[0];
goodness = improved / scaledTarget;
if (verbose >= 3) mxLog("%s: viable speed %f for improvement %.3g goodness %f",
name, bestSpeed, bestImproved, goodness);
break;
}
if (bestSpeed == 0) return;
if (0 && speed < 1 && goodness < epsilon) { // seems to be not worth it
int retries = 4; // search up to 2.4*speed
speed *= 1.25;
while (--retries > 0 && goodness < epsilon) {
++probeCount;
trial = prevEst - speed * searchDir;
++minorIter;
fc->copyParamToModel(globalState, trial.data());
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_FIT, fc);
if (!std::isfinite(fitMatrix->data[0])) break;
const double improved = refFit - fitMatrix->data[0];
if (bestImproved >= improved) break;
bestFit = fitMatrix->data[0];
bestImproved = improved;
bestSpeed = speed;
goodness = improved / (speed * targetImprovement);
}
}
if (verbose >= 3) mxLog("%s: using steepestDescent %d probes %d speed %f improved %.3g",
name, steepestDescent, probeCount, bestSpeed, bestImproved);
if (!steepestDescent) priorSpeed = bestSpeed;
trial = prevEst - bestSpeed * searchDir;
*maxAdj = 0;
for (size_t px=0; px < numParam; ++px) {
double oldEst = fc->est[px];
double badj = fabs(oldEst - trial(px));
if (*maxAdj < badj) {
*maxAdj = badj;
*maxAdjSigned = oldEst - trial(px);
*maxAdjParam = px;
}
}
memcpy(fc->est, trial.data(), sizeof(double) * numParam);
*improvement = bestImproved;
refFit = bestFit;
}
void ComputeNR::computeImpl(FitContext *fc)
{
// complain if there are non-linear constraints TODO
size_t numParam = varGroup->vars.size();
if (numParam <= 0) {
Rf_error("Model has no free parameters");
return;
}
fc->flavor.assign(numParam, NULL);
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_PARAMFLAVOR, fc);
// flavor used for debug output only
for (size_t px=0; px < numParam; ++px) {
if (!fc->flavor[px]) fc->flavor[px] = "?";
}
omxFitFunctionCompute(fitMatrix->fitFunction, FF_COMPUTE_PREOPTIMIZE, fc);
priorSpeed = 1;
minorIter = 0;
int startIter = fc->iterations;
bool converged = false;
double maxAdj = 0;
double maxAdjSigned = 0;
int maxAdjParam = -1;
const char *maxAdjFlavor = "?";
if (verbose >= 2) {
mxLog("Welcome to Newton-Raphson (tolerance %.3g, max iter %d)",
tolerance, maxIter);
}
while (1) {
fc->iterations += 1;
int iter = fc->iterations - startIter;
if (verbose >= 2) {
if (iter == 1) {
mxLog("%s: begin iter %d/%d", name, iter, maxIter);
} else {
const char *pname = "none";
if (maxAdjParam >= 0) pname = fc->varGroup->vars[maxAdjParam]->name;
mxLog("%s: begin iter %d/%d (prev maxAdj %.3g for %s %s)",
name, iter, maxIter, maxAdjSigned, maxAdjFlavor, pname);
}
}
fc->grad = Eigen::VectorXd::Zero(fc->numParam);
fc->clearHessian();
maxAdj = 0;
double improvement = 0;
lineSearch(fc, iter, &maxAdj, &maxAdjSigned, &maxAdjParam, &improvement);
converged = improvement < tolerance;
maxAdjFlavor = fc->flavor[maxAdjParam];
fc->copyParamToModel(globalState);
R_CheckUserInterrupt();
if (converged || iter >= maxIter || isErrorRaised(globalState)) break;
}
if (converged) {
fc->inform = INFORM_CONVERGED_OPTIMUM;
fc->wanted |= FF_COMPUTE_BESTFIT;
if (verbose >= 1) {
int iter = fc->iterations - startIter;
mxLog("%s: converged in %d cycles (%d minor iterations)", name, iter, minorIter);
}
} else {
fc->inform = INFORM_ITERATION_LIMIT;
if (verbose >= 1) {
int iter = fc->iterations - startIter;
mxLog("%s: failed to converge after %d cycles (%d minor iterations)",
name, iter, minorIter);
}
}
}
void ComputeNR::reportResults(FitContext *fc, MxRList *slots, MxRList *output)
{
omxPopulateFitFunction(fitMatrix, output);
}
<|endoftext|> |
<commit_before><commit_msg>Revert behavior for zero-sized regions.<commit_after><|endoftext|> |
<commit_before><commit_msg>Couple quick updates for handling failed update checks.<commit_after><|endoftext|> |
<commit_before>///
/// @file macros.hpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef MACROS_HPP
#define MACROS_HPP
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
/// We do the opposite of C/C++'s assert():
/// 1) By default ASSERT() is disabled (no-op).
/// 2) ASSERT() must be explicitly enabled using -DENABLE_ASSERT.
///
#if defined(ENABLE_ASSERT)
#undef NDEBUG
#include <cassert>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x) (static_cast<void>(0))
#endif
#if __has_attribute(always_inline)
#define ALWAYS_INLINE __attribute__((always_inline)) inline
#elif defined(_MSC_VER)
#define ALWAYS_INLINE __forceinline
#else
#define ALWAYS_INLINE
#endif
/// Some functions in primesieve use a large number of variables
/// at the same time. If such functions are inlined then
/// performance drops because not all variables fit into registers
/// which causes register spilling. We annotate such functions
/// with NOINLINE in order to avoid these issues.
///
#if __has_attribute(noinline)
#define NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE
#endif
#if __cplusplus >= 202002L && \
__has_cpp_attribute(unlikely)
#define if_unlikely(x) if (x) [[unlikely]]
#elif defined(__GNUC__) || \
__has_builtin(__builtin_expect)
#define if_unlikely(x) if (__builtin_expect(!!(x), 0))
#else
#define if_unlikely(x) if (x)
#endif
#if __cplusplus >= 201703L && \
__has_cpp_attribute(fallthrough)
#define FALLTHROUGH [[fallthrough]]
#elif __has_attribute(fallthrough)
#define FALLTHROUGH __attribute__((fallthrough))
#else
#define FALLTHROUGH
#endif
#if defined(__GNUC__) || \
__has_builtin(__builtin_unreachable)
#define UNREACHABLE __builtin_unreachable()
#elif defined(_MSC_VER)
#define UNREACHABLE __assume(0)
#else
#define UNREACHABLE
#endif
#endif
<commit_msg>Update comment<commit_after>///
/// @file macros.hpp
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef MACROS_HPP
#define MACROS_HPP
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
/// Enable expensive debugging assertions.
/// These assertions enable e.g. bounds checks for the
/// pod_vector and pod_array types.
///
#if defined(ENABLE_ASSERT)
#undef NDEBUG
#include <cassert>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x) (static_cast<void>(0))
#endif
#if __has_attribute(always_inline)
#define ALWAYS_INLINE __attribute__((always_inline)) inline
#elif defined(_MSC_VER)
#define ALWAYS_INLINE __forceinline
#else
#define ALWAYS_INLINE
#endif
/// Some functions in primesieve use a large number of variables
/// at the same time. If such functions are inlined then
/// performance drops because not all variables fit into registers
/// which causes register spilling. We annotate such functions
/// with NOINLINE in order to avoid these issues.
///
#if __has_attribute(noinline)
#define NOINLINE __attribute__((noinline))
#elif defined(_MSC_VER)
#define NOINLINE __declspec(noinline)
#else
#define NOINLINE
#endif
#if __cplusplus >= 202002L && \
__has_cpp_attribute(unlikely)
#define if_unlikely(x) if (x) [[unlikely]]
#elif defined(__GNUC__) || \
__has_builtin(__builtin_expect)
#define if_unlikely(x) if (__builtin_expect(!!(x), 0))
#else
#define if_unlikely(x) if (x)
#endif
#if __cplusplus >= 201703L && \
__has_cpp_attribute(fallthrough)
#define FALLTHROUGH [[fallthrough]]
#elif __has_attribute(fallthrough)
#define FALLTHROUGH __attribute__((fallthrough))
#else
#define FALLTHROUGH
#endif
#if defined(__GNUC__) || \
__has_builtin(__builtin_unreachable)
#define UNREACHABLE __builtin_unreachable()
#elif defined(_MSC_VER)
#define UNREACHABLE __assume(0)
#else
#define UNREACHABLE
#endif
#endif
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
namespace seastar {
template <typename Func>
class deferred_action {
Func _func;
bool _cancelled = false;
public:
static_assert(std::is_nothrow_move_constructible<Func>::value, "Func(Func&&) must be noexcept");
deferred_action(Func&& func) noexcept : _func(std::move(func)) {}
deferred_action(deferred_action&& o) noexcept : _func(std::move(o._func)), _cancelled(o._cancelled) {
o._cancelled = true;
}
deferred_action& operator=(deferred_action&& o) noexcept {
if (this != &o) {
this->~deferred_action();
new (this) deferred_action(std::move(o));
}
return *this;
}
deferred_action(const deferred_action&) = delete;
~deferred_action() { if (!_cancelled) { _func(); }; }
void cancel() { _cancelled = true; }
};
template <typename Func>
inline
deferred_action<Func>
defer(Func&& func) {
return deferred_action<Func>(std::forward<Func>(func));
}
}
<commit_msg>defer: include std headers<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <type_traits>
#include <utility>
namespace seastar {
template <typename Func>
class deferred_action {
Func _func;
bool _cancelled = false;
public:
static_assert(std::is_nothrow_move_constructible<Func>::value, "Func(Func&&) must be noexcept");
deferred_action(Func&& func) noexcept : _func(std::move(func)) {}
deferred_action(deferred_action&& o) noexcept : _func(std::move(o._func)), _cancelled(o._cancelled) {
o._cancelled = true;
}
deferred_action& operator=(deferred_action&& o) noexcept {
if (this != &o) {
this->~deferred_action();
new (this) deferred_action(std::move(o));
}
return *this;
}
deferred_action(const deferred_action&) = delete;
~deferred_action() { if (!_cancelled) { _func(); }; }
void cancel() { _cancelled = true; }
};
template <typename Func>
inline
deferred_action<Func>
defer(Func&& func) {
return deferred_action<Func>(std::forward<Func>(func));
}
}
<|endoftext|> |
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*
*/
#include "aalang_cpp.hh"
#include "helper.hh"
aalang_cpp::aalang_cpp(): aalang(),action_cnt(1), tag_cnt(1),
istate(NULL), name(NULL), tag(false)
{
default_guard="return true;";
default_body="";
default_adapter="";
std::vector<std::string> t;
aname.push_back(t);
tname.push_back(t);
amap.push_back(0);
tmap.push_back(0);
}
void aalang_cpp::set_starter(std::string* st)
{
s+=*st;
}
void aalang_cpp::set_name(std::string* name)
{
/*
{ printf("\n\t//action%i: ",action); }
anames.push_back(*$2.str); printf("%s",$2.str->c_str()); delete $2.str; $2.str=NULL; } ;
*/
s+="\n//action"+to_string(action_cnt)+": \""+*name+"\"\n";
aname.back().push_back(*name);
amap.push_back(action_cnt);
name_cnt++;
}
void aalang_cpp::set_namestr(std::string* _name)
{
/*
printf("class _gen_");
printf("%s: public aal {\nprivate:\n\t",
$1.str->c_str()); };
*/
name=_name;
s+="#include \"aal.hh\"\n\n";
s+="class _gen_"+*name+":public aal {\nprivate:\n\t";
}
void aalang_cpp::set_variables(std::string* var)
{
/*
printf("//variables\n%s\n",$2.str->c_str()); } ;
*/
s+="//variables\n"+*var+"\n";
delete var;
}
void aalang_cpp::set_istate(std::string* ist)
{
istate=ist;
}
void aalang_cpp::set_push(std::string* p)
{
push=*p;
delete p;
}
void aalang_cpp::set_pop(std::string* p)
{
pop=*p;
delete p;
}
void aalang_cpp::set_tagname(std::string* name)
{
s+="\n//tag"+to_string(tag_cnt)+": \""+*name+"\"\n";
tname.back().push_back(*name);
tmap.push_back(tag_cnt);
name_cnt++;
tag=true;
}
void aalang_cpp::next_tag()
{
std::vector<std::string> t;
tname.push_back(t);
tag_cnt+=name_cnt;
name_cnt=0;
tag=false;
}
void aalang_cpp::set_guard(std::string* gua)
{
if (tag) {
s+="bool tag"+to_string(tag_cnt)+"_guard() {\n"+
*gua+"}\n";
} else {
s+="bool action"+to_string(action_cnt)+"_guard() {\n"+
*gua+"}\n";
}
if (gua!=&default_guard)
delete gua;
}
void aalang_cpp::set_body(std::string* bod)
{
/*
printf("void action%i_body() {\n%s}\n",action,$3.str->c_str()); } ;
*/
s+="void action"+to_string(action_cnt)+"_body() {\n"+*bod+"}\n";
if (bod!=&default_body)
delete bod;
}
void aalang_cpp::set_adapter(std::string* ada)
{
/*
printf("int action%i_adapter() {\n%s}\n",action,$3.str->c_str()); }|;
*/
s+="int action" + to_string(action_cnt) + "_adapter() {\n" +
*ada + "\n"
"\treturn " + to_string(action_cnt) + ";\n"
"}\n";
if (ada!=&default_adapter)
delete ada;
}
void aalang_cpp::next_action()
{
std::vector<std::string> t;
aname.push_back(t);
action_cnt+=name_cnt;
name_cnt=0;
}
std::string aalang_cpp::stringify()
{
s=s+
"\npublic:\n"
"\t_gen_"+*name+"(Log& l): aal(l) {\n\taction_names.push_back(\"\");\n";
for(std::list<std::vector<std::string> >::iterator i=aname.begin();i!=aname.end();i++) {
for(std::vector<std::string>::iterator j=i->begin();j!=i->end();j++) {
s+="\taction_names.push_back(\""+*j+"\");\n";
}
}
s=s+"\ttag_names.push_back(\"\");\n";
for(std::list<std::vector<std::string> >::iterator i=tname.begin();i!=tname.end();i++) {
for(std::vector<std::string>::iterator j=i->begin();j!=i->end();j++) {
s+="\ttag_names.push_back(\""+*j+"\");\n";
}
}
s+=*istate+"}\n"
"virtual bool reset() {\n"+
*istate +
"return true;\n}\n\n"
"virtual int adapter_execute(int action) {\n"
"\tswitch(action) {\n";
if (pop!="") {
s=s+"\nvirtual void pop(){\n"+pop+"\n}\n";
s=s+"\nvirtual void push(){\n"+push+"\n}\n";
}
for(int i=1;i<action_cnt;i++) {
s+="\t\tcase "+to_string(i)+":\n"
"\t\treturn action"+to_string(amap[i])+
"_adapter();\n\t\tbreak;\n";
}
s=s+"\t\tdefault:\n"
"\t\treturn 0;\n"
"\t};\n"
"}\n"
"virtual int model_execute(int action) {\n"
"\tswitch(action) {\n";
for(int i=1;i<action_cnt;i++) {
s+="\t\tcase "+to_string(i)+":\n"
"\t\taction"+to_string(amap[i])+"_body();\n\t\treturn "+
to_string(i)+";\n\t\tbreak;\n";
}
s=s+"\t\tdefault:\n"
"\t\treturn 0;\n"
"\t};\n"
"}\n"
"virtual int getActions(int** act) {\n"
"actions.clear();\n";
for(int i=1;i<action_cnt;i++) {
s+="\tif (action"+to_string(amap[i])+"_guard()) {\n"
"\t\tactions.push_back("+to_string(i)+");\n"
"\t}\n";
}
s=s+"\t*act = &actions[0];\n"
"\treturn actions.size();\n"
"}\n";
s=s+"virtual int getprops(int** props) {\n"
"tags.clear();\n";
for(int i=1;i<tag_cnt;i++) {
s+="\tif (tag"+to_string(tmap[i])+"_guard()) {\n"
"\t\ttags.push_back("+to_string(i)+");\n"
"\t}\n";
}
s=s+"\t*props = &tags[0];\n"
"\treturn tags.size();\n"
"}\n"
"};\n";
factory_register();
return s;
}
void aalang_cpp::factory_register()
{
s=s+" /* factory register */\n\n"
"namespace {\n"
"static aal* a=NULL;\n\n"
"Model* model_creator(Log&l, std::string params) {\n"
"\tif (!a) {\n"
"\t a=new _gen_"+*name+"(l);\n"
"\t}\n"
"\treturn new Mwrapper(l,params,a);\n"
"}\n\n"
"static ModelFactory::Register me1(\""+*name+"\", model_creator);\n\n"
"Adapter* adapter_creator(Log&l, std::string params = \"\")\n"
"{\n"
"\tif (!a) {\n"
"\t a=new _gen_"+*name+"(l);\n"
"\t}\n"
"\treturn new Awrapper(l,params,a);\n"
"}\n"
"static AdapterFactory::Register me2(\""+*name+"\", adapter_creator);\n"+
"}\n";
}
<commit_msg>fix uninitialised variable remove old commented out stuff<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*
*/
#include "aalang_cpp.hh"
#include "helper.hh"
aalang_cpp::aalang_cpp(): aalang(),action_cnt(1), tag_cnt(1), name_cnt(0),
istate(NULL), name(NULL), tag(false)
{
default_guard="return true;";
default_body="";
default_adapter="";
std::vector<std::string> t;
aname.push_back(t);
tname.push_back(t);
amap.push_back(0);
tmap.push_back(0);
}
void aalang_cpp::set_starter(std::string* st)
{
s+=*st;
}
void aalang_cpp::set_name(std::string* name)
{
s+="\n//action"+to_string(action_cnt)+": \""+*name+"\"\n";
aname.back().push_back(*name);
amap.push_back(action_cnt);
name_cnt++;
}
void aalang_cpp::set_namestr(std::string* _name)
{
name=_name;
s+="#include \"aal.hh\"\n\n";
s+="class _gen_"+*name+":public aal {\nprivate:\n\t";
}
void aalang_cpp::set_variables(std::string* var)
{
s+="//variables\n"+*var+"\n";
delete var;
}
void aalang_cpp::set_istate(std::string* ist)
{
istate=ist;
}
void aalang_cpp::set_push(std::string* p)
{
push=*p;
delete p;
}
void aalang_cpp::set_pop(std::string* p)
{
pop=*p;
delete p;
}
void aalang_cpp::set_tagname(std::string* name)
{
s+="\n//tag"+to_string(tag_cnt)+": \""+*name+"\"\n";
tname.back().push_back(*name);
tmap.push_back(tag_cnt);
name_cnt++;
tag=true;
}
void aalang_cpp::next_tag()
{
std::vector<std::string> t;
tname.push_back(t);
tag_cnt+=name_cnt;
name_cnt=0;
tag=false;
}
void aalang_cpp::set_guard(std::string* gua)
{
if (tag) {
s+="bool tag"+to_string(tag_cnt)+"_guard() {\n"+
*gua+"}\n";
} else {
s+="bool action"+to_string(action_cnt)+"_guard() {\n"+
*gua+"}\n";
}
if (gua!=&default_guard)
delete gua;
}
void aalang_cpp::set_body(std::string* bod)
{
s+="void action"+to_string(action_cnt)+"_body() {\n"+*bod+"}\n";
if (bod!=&default_body)
delete bod;
}
void aalang_cpp::set_adapter(std::string* ada)
{
s+="int action" + to_string(action_cnt) + "_adapter() {\n" +
*ada + "\n"
"\treturn " + to_string(action_cnt) + ";\n"
"}\n";
if (ada!=&default_adapter)
delete ada;
}
void aalang_cpp::next_action()
{
std::vector<std::string> t;
aname.push_back(t);
action_cnt+=name_cnt;
name_cnt=0;
}
std::string aalang_cpp::stringify()
{
s=s+
"\npublic:\n"
"\t_gen_"+*name+"(Log& l): aal(l) {\n\taction_names.push_back(\"\");\n";
for(std::list<std::vector<std::string> >::iterator i=aname.begin();i!=aname.end();i++) {
for(std::vector<std::string>::iterator j=i->begin();j!=i->end();j++) {
s+="\taction_names.push_back(\""+*j+"\");\n";
}
}
s=s+"\ttag_names.push_back(\"\");\n";
for(std::list<std::vector<std::string> >::iterator i=tname.begin();i!=tname.end();i++) {
for(std::vector<std::string>::iterator j=i->begin();j!=i->end();j++) {
s+="\ttag_names.push_back(\""+*j+"\");\n";
}
}
s+=*istate+"}\n"
"virtual bool reset() {\n"+
*istate +
"return true;\n}\n\n"
"virtual int adapter_execute(int action) {\n"
"\tswitch(action) {\n";
if (pop!="") {
s=s+"\nvirtual void pop(){\n"+pop+"\n}\n";
s=s+"\nvirtual void push(){\n"+push+"\n}\n";
}
for(int i=1;i<action_cnt;i++) {
s+="\t\tcase "+to_string(i)+":\n"
"\t\treturn action"+to_string(amap[i])+
"_adapter();\n\t\tbreak;\n";
}
s=s+"\t\tdefault:\n"
"\t\treturn 0;\n"
"\t};\n"
"}\n"
"virtual int model_execute(int action) {\n"
"\tswitch(action) {\n";
for(int i=1;i<action_cnt;i++) {
s+="\t\tcase "+to_string(i)+":\n"
"\t\taction"+to_string(amap[i])+"_body();\n\t\treturn "+
to_string(i)+";\n\t\tbreak;\n";
}
s=s+"\t\tdefault:\n"
"\t\treturn 0;\n"
"\t};\n"
"}\n"
"virtual int getActions(int** act) {\n"
"actions.clear();\n";
for(int i=1;i<action_cnt;i++) {
s+="\tif (action"+to_string(amap[i])+"_guard()) {\n"
"\t\tactions.push_back("+to_string(i)+");\n"
"\t}\n";
}
s=s+"\t*act = &actions[0];\n"
"\treturn actions.size();\n"
"}\n";
s=s+"virtual int getprops(int** props) {\n"
"tags.clear();\n";
for(int i=1;i<tag_cnt;i++) {
s+="\tif (tag"+to_string(tmap[i])+"_guard()) {\n"
"\t\ttags.push_back("+to_string(i)+");\n"
"\t}\n";
}
s=s+"\t*props = &tags[0];\n"
"\treturn tags.size();\n"
"}\n"
"};\n";
factory_register();
return s;
}
void aalang_cpp::factory_register()
{
s=s+" /* factory register */\n\n"
"namespace {\n"
"static aal* a=NULL;\n\n"
"Model* model_creator(Log&l, std::string params) {\n"
"\tif (!a) {\n"
"\t a=new _gen_"+*name+"(l);\n"
"\t}\n"
"\treturn new Mwrapper(l,params,a);\n"
"}\n\n"
"static ModelFactory::Register me1(\""+*name+"\", model_creator);\n\n"
"Adapter* adapter_creator(Log&l, std::string params = \"\")\n"
"{\n"
"\tif (!a) {\n"
"\t a=new _gen_"+*name+"(l);\n"
"\t}\n"
"\treturn new Awrapper(l,params,a);\n"
"}\n"
"static AdapterFactory::Register me2(\""+*name+"\", adapter_creator);\n"+
"}\n";
}
<|endoftext|> |
<commit_before>/*
* IceWM
*
* Copyright (C) 1998-2001 Marko Macek
*
* CPU Status
*/
#include "config.h"
#ifdef CONFIG_APPLET_CPU_STATUS
#include "ylib.h"
#include "wmapp.h"
#include "acpustatus.h"
#include "sysdep.h"
#include "default.h"
#if defined(linux)
//#include <linux/kernel.h>
#include <sys/sysinfo.h>
#endif
#ifdef HAVE_KSTAT_H
#include <kstat.h>
#endif
#include "intl.h"
#if (defined(linux) || defined(HAVE_KSTAT_H))
#define UPDATE_INTERVAL 500
extern YPixmap *taskbackPixmap;
CPUStatus::CPUStatus(YWindow *aParent): YWindow(aParent) {
cpu = new int *[taskBarCPUSamples];
for (int a(0); a < taskBarCPUSamples; a++)
cpu[a] = new int[IWM_STATES];
fUpdateTimer = new YTimer(UPDATE_INTERVAL);
if (fUpdateTimer) {
fUpdateTimer->setTimerListener(this);
fUpdateTimer->startTimer();
}
color[IWM_USER] = new YColor(clrCpuUser);
color[IWM_NICE] = new YColor(clrCpuNice);
color[IWM_SYS] = new YColor(clrCpuSys);
color[IWM_IDLE] = *clrCpuIdle
? new YColor(clrCpuIdle) : NULL;
for (int i(0); i < taskBarCPUSamples; i++) {
cpu[i][IWM_USER] = cpu[i][IWM_NICE] = cpu[i][IWM_SYS] = 0;
cpu[i][IWM_IDLE] = 1;
}
setSize(taskBarCPUSamples, 20);
last_cpu[IWM_USER] = last_cpu[IWM_NICE] = last_cpu[IWM_SYS] = last_cpu[IWM_IDLE] = 0;
getStatus();
updateStatus();
updateToolTip();
}
CPUStatus::~CPUStatus() {
for (int a(0); a < taskBarCPUSamples; a++) {
delete cpu[a]; cpu[a] = 0;
}
delete cpu; cpu = 0;
delete color[IWM_USER]; color[IWM_USER] = 0;
delete color[IWM_NICE]; color[IWM_NICE] = 0;
delete color[IWM_SYS]; color[IWM_SYS] = 0;
delete color[IWM_IDLE]; color[IWM_IDLE] = 0;
}
void CPUStatus::paint(Graphics &g, int /*x*/, int /*y*/, unsigned int /*width*/, unsigned int /*height*/) {
int n, h = height();
for (int i(0); i < taskBarCPUSamples; i++) {
int user = cpu[i][IWM_USER];
int nice = cpu[i][IWM_NICE];
int sys = cpu[i][IWM_SYS];
int idle = cpu[i][IWM_IDLE];
int total = user + sys + nice + idle;
int y = height() - 1;
if (total > 0) {
if (sys) {
n = (h * (total - sys)) / total; // check rounding
if (n >= y) n = y;
g.setColor(color[IWM_SYS]);
g.drawLine(i, y, i, n);
y = n - 1;
}
if (nice) {
n = (h * (total - sys - nice))/ total;
if (n >= y) n = y;
g.setColor(color[IWM_NICE]);
g.drawLine(i, y, i, n);
y = n - 1;
}
if (user) {
n = (h * (total - sys - nice - user))/ total;
if (n >= y) n = y;
g.setColor(color[IWM_USER]);
g.drawLine(i, y, i, n);
y = n - 1;
}
}
if (idle) {
if (color[IWM_IDLE]) {
g.setColor(color[IWM_IDLE]);
g.drawLine(i, 0, i, y);
} else {
#ifdef CONFIG_GRADIENTS
class YPixbuf * gradient(parent()->getGradient());
if (gradient)
g.copyPixbuf(*gradient,
this->x() + i, this->y(), width(), y + 1, i, 0);
else
#endif
if (taskbackPixmap)
g.fillPixmap(taskbackPixmap,
i, 0, width(), y + 1, this->x() + i, this->y());
}
}
}
}
bool CPUStatus::handleTimer(YTimer *t) {
if (t != fUpdateTimer)
return false;
if (toolTipVisible())
updateToolTip();
updateStatus();
return true;
}
void CPUStatus::updateToolTip() {
#ifdef linux
char load[64];
struct sysinfo sys;
float l1, l5, l15;
sysinfo(&sys);
l1 = (float)sys.loads[0] / 65536.0;
l5 = (float)sys.loads[1] / 65536.0;
l15 = (float)sys.loads[2] / 65536.0;
sprintf(load, _("CPU Load: %3.2f %3.2f %3.2f, %d processes."),
l1, l5, l15, sys.procs);
setToolTip(load);
#endif
}
void CPUStatus::handleClick(const XButtonEvent &up, int count) {
if (up.button == 1) {
if (cpuCommand && cpuCommand[0] &&
(taskBarLaunchOnSingleClick ? count == 1 : !(count % 2)))
wmapp->runCommandOnce(cpuClassHint, cpuCommand);
}
}
void CPUStatus::updateStatus() {
for (int i(1); i < taskBarCPUSamples; i++) {
cpu[i - 1][IWM_USER] = cpu[i][IWM_USER];
cpu[i - 1][IWM_NICE] = cpu[i][IWM_NICE];
cpu[i - 1][IWM_SYS] = cpu[i][IWM_SYS];
cpu[i - 1][IWM_IDLE] = cpu[i][IWM_IDLE];
}
getStatus(),
repaint();
}
void CPUStatus::getStatus() {
#ifdef linux
char *p, buf[128];
long cur[IWM_STATES];
int len, fd = open("/proc/stat", O_RDONLY);
cpu[taskBarCPUSamples-1][IWM_USER] = 0;
cpu[taskBarCPUSamples-1][IWM_NICE] = 0;
cpu[taskBarCPUSamples-1][IWM_SYS] = 0;
cpu[taskBarCPUSamples-1][IWM_IDLE] = 0;
if (fd == -1)
return;
len = read(fd, buf, sizeof(buf) - 1);
if (len != sizeof(buf) - 1) {
close(fd);
return;
}
buf[len] = 0;
p = buf;
while (*p && (*p < '0' || *p > '9'))
p++;
for (int i = 0; i < 4; i++) {
cur[i] = strtoul(p, &p, 10);
cpu[taskBarCPUSamples-1][i] = cur[i] - last_cpu[i];
last_cpu[i] = cur[i];
}
close(fd);
#if 0
msg(_("cpu: %d %d %d %d"),
cpu[taskBarCPUSamples-1][IWM_USER], cpu[taskBarCPUSamples-1][IWM_NICE],
cpu[taskBarCPUSamples-1][IWM_SYS], cpu[taskBarCPUSamples-1][IDLE]);
#endif
#endif /* linux */
#ifdef HAVE_KSTAT_H
#ifdef HAVE_OLD_KSTAT
#define ui32 ul
#endif
static kstat_ctl_t *kc = NULL;
static kid_t kcid;
kid_t new_kcid;
kstat_t *ks = NULL;
kstat_named_t *kn = NULL;
int changed,change,total_change;
unsigned int thiscpu;
register int i,j;
static unsigned int ncpus;
static kstat_t **cpu_ks=NULL;
static cpu_stat_t *cpu_stat=NULL;
static long cp_old[CPU_STATES];
long cp_time[CPU_STATES], cp_pct[CPU_STATES];
/* Initialize the kstat */
if (!kc) {
kc = kstat_open();
if (!kc) {
perror("kstat_open ");
return;/* FIXME : need err handler? */
}
changed = 1;
kcid = kc->kc_chain_id;
} else {
changed = 0;
}
/* Fetch the kstat data. Whenever we detect that the kstat has been
changed by the kernel, we 'continue' and restart this loop.
Otherwise, we break out at the end. */
while (1) {
new_kcid = kstat_chain_update(kc);
if (new_kcid) {
changed = 1;
kcid = new_kcid;
}
if (new_kcid < 0) {
perror("kstat_chain_update ");
return;/* FIXME : need err handler? */
}
if (new_kcid != 0)
continue; /* kstat changed - start over */
ks = kstat_lookup(kc, "unix", 0, "system_misc");
if (kstat_read(kc, ks, 0) == -1) {
perror("kstat_read ");
return;/* FIXME : need err handler? */
}
if (changed) {
/* the kstat has changed - reread the data */
thiscpu = 0; ncpus = 0;
kn = (kstat_named_t *)kstat_data_lookup(ks, "ncpus");
if ((kn) && (kn->value.ui32 > ncpus)) {
/* I guess I should be using 'new' here... FIXME */
ncpus = kn->value.ui32;
if ((cpu_ks = (kstat_t **)
realloc(cpu_ks, ncpus * sizeof(kstat_t *))) == NULL)
{
perror("realloc: cpu_ks ");
return;/* FIXME : need err handler? */
}
if ((cpu_stat = (cpu_stat_t *)
realloc(cpu_stat, ncpus * sizeof(cpu_stat_t))) == NULL)
{
perror("realloc: cpu_stat ");
return;/* FIXME : need err handler? */
}
}
for (ks = kc->kc_chain; ks; ks = ks->ks_next) {
if (strncmp(ks->ks_name, "cpu_stat", 8) == 0) {
new_kcid = kstat_read(kc, ks, NULL);
if (new_kcid < 0) {
perror("kstat_read ");
return;/* FIXME : need err handler? */
}
if (new_kcid != kcid)
break;
cpu_ks[thiscpu] = ks;
thiscpu++;
if (thiscpu > ncpus) {
warn(_("kstat finds too many cpus: should be %d"),
ncpus);
return;/* FIXME : need err handler? */
}
}
}
if (new_kcid != kcid)
continue;
ncpus = thiscpu;
changed = 0;
}
for (i = 0; i<(int)ncpus; i++) {
new_kcid = kstat_read(kc, cpu_ks[i], &cpu_stat[i]);
if (new_kcid < 0) {
perror("kstat_read ");
return;/* FIXME : need err handler? */
}
}
if (new_kcid != kcid)
continue; /* kstat changed - start over */
else
break;
} /* while (1) */
/* Initialize the cp_time array */
for (i = 0; i < CPU_STATES; i++)
cp_time[i] = 0L;
for (i = 0; i < (int)ncpus; i++) {
for (j = 0; j < CPU_STATES; j++)
cp_time[j] += (long) cpu_stat[i].cpu_sysinfo.cpu[j];
}
/* calculate the percent utilization for each category */
/* cpu_state calculations */
total_change = 0;
for (i = 0; i < CPU_STATES; i++) {
change = cp_time[i] - cp_old[i];
if (change < 0) /* The counter rolled over */
change = (int) ((unsigned long)cp_time[i] - (unsigned long)cp_old[i]);
cp_pct[i] = change;
total_change += change;
cp_old[i] = cp_time[i]; /* copy the data for the next run */
}
/* this percent calculation isn't really needed, since the repaint
routine takes care of this... */
for (i = 0; i < CPU_STATES; i++)
cp_pct[i] =
((total_change > 0) ?
((int)(((1000.0 * (float)cp_pct[i]) / total_change) + 0.5)) :
((i == CPU_IDLE) ? (1000) : (0)));
/* OK, we've got the data. Now copy it to cpu[][] */
cpu[taskBarCPUSamples-1][IWM_USER] = cp_pct[CPU_USER];
cpu[taskBarCPUSamples-1][IWM_NICE] = cp_pct[CPU_WAIT];
cpu[taskBarCPUSamples-1][IWM_SYS] = cp_pct[CPU_KERNEL];
cpu[taskBarCPUSamples-1][IWM_IDLE] = cp_pct[CPU_IDLE];
#endif /* have_kstat_h */
}
#endif
#endif
<commit_msg>hopefully fix with unclosed file descriptor (bug 561846)<commit_after>/*
* IceWM
*
* Copyright (C) 1998-2001 Marko Macek
*
* CPU Status
*/
#include "config.h"
#ifdef CONFIG_APPLET_CPU_STATUS
#include "ylib.h"
#include "wmapp.h"
#include "acpustatus.h"
#include "sysdep.h"
#include "default.h"
#if defined(linux)
//#include <linux/kernel.h>
#include <sys/sysinfo.h>
#endif
#ifdef HAVE_KSTAT_H
#include <kstat.h>
#endif
#include "intl.h"
#if (defined(linux) || defined(HAVE_KSTAT_H))
#define UPDATE_INTERVAL 500
extern YPixmap *taskbackPixmap;
CPUStatus::CPUStatus(YWindow *aParent): YWindow(aParent) {
cpu = new int *[taskBarCPUSamples];
for (int a(0); a < taskBarCPUSamples; a++)
cpu[a] = new int[IWM_STATES];
fUpdateTimer = new YTimer(UPDATE_INTERVAL);
if (fUpdateTimer) {
fUpdateTimer->setTimerListener(this);
fUpdateTimer->startTimer();
}
color[IWM_USER] = new YColor(clrCpuUser);
color[IWM_NICE] = new YColor(clrCpuNice);
color[IWM_SYS] = new YColor(clrCpuSys);
color[IWM_IDLE] = *clrCpuIdle
? new YColor(clrCpuIdle) : NULL;
for (int i(0); i < taskBarCPUSamples; i++) {
cpu[i][IWM_USER] = cpu[i][IWM_NICE] = cpu[i][IWM_SYS] = 0;
cpu[i][IWM_IDLE] = 1;
}
setSize(taskBarCPUSamples, 20);
last_cpu[IWM_USER] = last_cpu[IWM_NICE] = last_cpu[IWM_SYS] = last_cpu[IWM_IDLE] = 0;
getStatus();
updateStatus();
updateToolTip();
}
CPUStatus::~CPUStatus() {
for (int a(0); a < taskBarCPUSamples; a++) {
delete cpu[a]; cpu[a] = 0;
}
delete cpu; cpu = 0;
delete color[IWM_USER]; color[IWM_USER] = 0;
delete color[IWM_NICE]; color[IWM_NICE] = 0;
delete color[IWM_SYS]; color[IWM_SYS] = 0;
delete color[IWM_IDLE]; color[IWM_IDLE] = 0;
}
void CPUStatus::paint(Graphics &g, int /*x*/, int /*y*/, unsigned int /*width*/, unsigned int /*height*/) {
int n, h = height();
for (int i(0); i < taskBarCPUSamples; i++) {
int user = cpu[i][IWM_USER];
int nice = cpu[i][IWM_NICE];
int sys = cpu[i][IWM_SYS];
int idle = cpu[i][IWM_IDLE];
int total = user + sys + nice + idle;
int y = height() - 1;
if (total > 0) {
if (sys) {
n = (h * (total - sys)) / total; // check rounding
if (n >= y) n = y;
g.setColor(color[IWM_SYS]);
g.drawLine(i, y, i, n);
y = n - 1;
}
if (nice) {
n = (h * (total - sys - nice))/ total;
if (n >= y) n = y;
g.setColor(color[IWM_NICE]);
g.drawLine(i, y, i, n);
y = n - 1;
}
if (user) {
n = (h * (total - sys - nice - user))/ total;
if (n >= y) n = y;
g.setColor(color[IWM_USER]);
g.drawLine(i, y, i, n);
y = n - 1;
}
}
if (idle) {
if (color[IWM_IDLE]) {
g.setColor(color[IWM_IDLE]);
g.drawLine(i, 0, i, y);
} else {
#ifdef CONFIG_GRADIENTS
class YPixbuf * gradient(parent()->getGradient());
if (gradient)
g.copyPixbuf(*gradient,
this->x() + i, this->y(), width(), y + 1, i, 0);
else
#endif
if (taskbackPixmap)
g.fillPixmap(taskbackPixmap,
i, 0, width(), y + 1, this->x() + i, this->y());
}
}
}
}
bool CPUStatus::handleTimer(YTimer *t) {
if (t != fUpdateTimer)
return false;
if (toolTipVisible())
updateToolTip();
updateStatus();
return true;
}
void CPUStatus::updateToolTip() {
#ifdef linux
char load[64];
struct sysinfo sys;
float l1, l5, l15;
sysinfo(&sys);
l1 = (float)sys.loads[0] / 65536.0;
l5 = (float)sys.loads[1] / 65536.0;
l15 = (float)sys.loads[2] / 65536.0;
sprintf(load, _("CPU Load: %3.2f %3.2f %3.2f, %d processes."),
l1, l5, l15, sys.procs);
setToolTip(load);
#endif
}
void CPUStatus::handleClick(const XButtonEvent &up, int count) {
if (up.button == 1) {
if (cpuCommand && cpuCommand[0] &&
(taskBarLaunchOnSingleClick ? count == 1 : !(count % 2)))
wmapp->runCommandOnce(cpuClassHint, cpuCommand);
}
}
void CPUStatus::updateStatus() {
for (int i(1); i < taskBarCPUSamples; i++) {
cpu[i - 1][IWM_USER] = cpu[i][IWM_USER];
cpu[i - 1][IWM_NICE] = cpu[i][IWM_NICE];
cpu[i - 1][IWM_SYS] = cpu[i][IWM_SYS];
cpu[i - 1][IWM_IDLE] = cpu[i][IWM_IDLE];
}
getStatus(),
repaint();
}
void CPUStatus::getStatus() {
#ifdef linux
char *p, buf[128];
long cur[IWM_STATES];
int len, fd = open("/proc/stat", O_RDONLY);
cpu[taskBarCPUSamples-1][IWM_USER] = 0;
cpu[taskBarCPUSamples-1][IWM_NICE] = 0;
cpu[taskBarCPUSamples-1][IWM_SYS] = 0;
cpu[taskBarCPUSamples-1][IWM_IDLE] = 0;
if (fd == -1)
return;
len = read(fd, buf, sizeof(buf) - 1);
if (len != sizeof(buf) - 1) {
close(fd);
return;
}
buf[len] = 0;
p = buf;
while (*p && (*p < '0' || *p > '9'))
p++;
for (int i = 0; i < 4; i++) {
cur[i] = strtoul(p, &p, 10);
cpu[taskBarCPUSamples-1][i] = cur[i] - last_cpu[i];
last_cpu[i] = cur[i];
}
close(fd);
#if 0
msg(_("cpu: %d %d %d %d"),
cpu[taskBarCPUSamples-1][IWM_USER], cpu[taskBarCPUSamples-1][IWM_NICE],
cpu[taskBarCPUSamples-1][IWM_SYS], cpu[taskBarCPUSamples-1][IDLE]);
#endif
#endif /* linux */
#ifdef HAVE_KSTAT_H
#ifdef HAVE_OLD_KSTAT
#define ui32 ul
#endif
static kstat_ctl_t *kc = NULL;
static kid_t kcid;
kid_t new_kcid;
kstat_t *ks = NULL;
kstat_named_t *kn = NULL;
int changed,change,total_change;
unsigned int thiscpu;
register int i,j;
static unsigned int ncpus;
static kstat_t **cpu_ks=NULL;
static cpu_stat_t *cpu_stat=NULL;
static long cp_old[CPU_STATES];
long cp_time[CPU_STATES], cp_pct[CPU_STATES];
/* Initialize the kstat */
if (!kc) {
kc = kstat_open();
if (!kc) {
perror("kstat_open ");
return;/* FIXME : need err handler? */
}
changed = 1;
kcid = kc->kc_chain_id;
fcntl(kc->kc_kd, F_SETFD, FD_CLOEXEC);
} else {
changed = 0;
}
/* Fetch the kstat data. Whenever we detect that the kstat has been
changed by the kernel, we 'continue' and restart this loop.
Otherwise, we break out at the end. */
while (1) {
new_kcid = kstat_chain_update(kc);
if (new_kcid) {
changed = 1;
kcid = new_kcid;
}
if (new_kcid < 0) {
perror("kstat_chain_update ");
return;/* FIXME : need err handler? */
}
if (new_kcid != 0)
continue; /* kstat changed - start over */
ks = kstat_lookup(kc, "unix", 0, "system_misc");
if (kstat_read(kc, ks, 0) == -1) {
perror("kstat_read ");
return;/* FIXME : need err handler? */
}
if (changed) {
/* the kstat has changed - reread the data */
thiscpu = 0; ncpus = 0;
kn = (kstat_named_t *)kstat_data_lookup(ks, "ncpus");
if ((kn) && (kn->value.ui32 > ncpus)) {
/* I guess I should be using 'new' here... FIXME */
ncpus = kn->value.ui32;
if ((cpu_ks = (kstat_t **)
realloc(cpu_ks, ncpus * sizeof(kstat_t *))) == NULL)
{
perror("realloc: cpu_ks ");
return;/* FIXME : need err handler? */
}
if ((cpu_stat = (cpu_stat_t *)
realloc(cpu_stat, ncpus * sizeof(cpu_stat_t))) == NULL)
{
perror("realloc: cpu_stat ");
return;/* FIXME : need err handler? */
}
}
for (ks = kc->kc_chain; ks; ks = ks->ks_next) {
if (strncmp(ks->ks_name, "cpu_stat", 8) == 0) {
new_kcid = kstat_read(kc, ks, NULL);
if (new_kcid < 0) {
perror("kstat_read ");
return;/* FIXME : need err handler? */
}
if (new_kcid != kcid)
break;
cpu_ks[thiscpu] = ks;
thiscpu++;
if (thiscpu > ncpus) {
warn(_("kstat finds too many cpus: should be %d"),
ncpus);
return;/* FIXME : need err handler? */
}
}
}
if (new_kcid != kcid)
continue;
ncpus = thiscpu;
changed = 0;
}
for (i = 0; i<(int)ncpus; i++) {
new_kcid = kstat_read(kc, cpu_ks[i], &cpu_stat[i]);
if (new_kcid < 0) {
perror("kstat_read ");
return;/* FIXME : need err handler? */
}
}
if (new_kcid != kcid)
continue; /* kstat changed - start over */
else
break;
} /* while (1) */
/* Initialize the cp_time array */
for (i = 0; i < CPU_STATES; i++)
cp_time[i] = 0L;
for (i = 0; i < (int)ncpus; i++) {
for (j = 0; j < CPU_STATES; j++)
cp_time[j] += (long) cpu_stat[i].cpu_sysinfo.cpu[j];
}
/* calculate the percent utilization for each category */
/* cpu_state calculations */
total_change = 0;
for (i = 0; i < CPU_STATES; i++) {
change = cp_time[i] - cp_old[i];
if (change < 0) /* The counter rolled over */
change = (int) ((unsigned long)cp_time[i] - (unsigned long)cp_old[i]);
cp_pct[i] = change;
total_change += change;
cp_old[i] = cp_time[i]; /* copy the data for the next run */
}
/* this percent calculation isn't really needed, since the repaint
routine takes care of this... */
for (i = 0; i < CPU_STATES; i++)
cp_pct[i] =
((total_change > 0) ?
((int)(((1000.0 * (float)cp_pct[i]) / total_change) + 0.5)) :
((i == CPU_IDLE) ? (1000) : (0)));
/* OK, we've got the data. Now copy it to cpu[][] */
cpu[taskBarCPUSamples-1][IWM_USER] = cp_pct[CPU_USER];
cpu[taskBarCPUSamples-1][IWM_NICE] = cp_pct[CPU_WAIT];
cpu[taskBarCPUSamples-1][IWM_SYS] = cp_pct[CPU_KERNEL];
cpu[taskBarCPUSamples-1][IWM_IDLE] = cp_pct[CPU_IDLE];
#endif /* have_kstat_h */
}
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <vSMC/internal/common.hpp>
#include <iostream>
#include <map>
#include <set>
#include <string>
namespace vSMC {
/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<unsigned (Particle<T> &, void *)>
initialize_type;
/// The type of move and mcmc functor
typedef internal::function<unsigned (unsigned, Particle<T> &)>
move_type;
/// The type of ESS history vector
typedef std::vector<double> ess_type;
/// The type of resampling history vector
typedef std::vector<bool> resampled_type;
/// The type of accept count history vector
typedef std::vector<unsigned> accept_type;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
typename Particle<T>::size_type N,
const initialize_type &init = NULL,
const move_type &move = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
initialized_(false), init_(init), move_(move),
scheme_(scheme), threshold_(threshold),
particle_(N, seed), iter_num_(0) {}
/// \brief Size of the particle set
///
/// \return The number of particles
typename Particle<T>::size_type size () const
{
return particle_.size();
}
/// \brief The number of iterations recorded
///
/// \return The number of iterations recorded so far (including the
/// initialization)
unsigned iter_size () const
{
return ess_.size();
}
/// \brief The number of iterations
///
/// \return The number of iterations performed by iterate() so far (not
/// including the initialization)
unsigned iter_num () const
{
return iter_num_;
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold;
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess () const
{
return ess_;
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled () const
{
return resampled_;
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param new_init New Initialization functor
void init (const initialize_type &new_init)
{
init_ = new_init;
}
/// \brief Replace iteration functor
///
/// \param new_move New Move functor
void move (const move_type &new_move)
{
move_ = new_move;
}
/// \brief Replace iteration functor
///
/// \param new_mcmc New MCMC Move functor
void mcmc (const move_type &new_mcmc)
{
mcmc_.push_back(new_mcmc);
}
/// \brief Clear all MCMC moves
void clear_mcmc ()
{
mcmc_.clear();
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
assert(bool(init_));
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap)
imap->second.clear();
iter_num_ = 0;
accept_.push_back(init_(particle_, param));
post_move();
particle_.reset_zconst();
initialized_ = true;
}
/// \brief Perform iteration
void iterate ()
{
assert(initialized_);
assert(bool(move_));
++iter_num_;
if (bool(move_))
accept_.push_back(move_(iter_num_, particle_));
for (typename std::vector<move_type>::iterator miter = mcmc_.begin();
miter != mcmc_.end(); ++miter)
accept_.back() = (*miter)(iter_num_, particle_);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (unsigned n)
{
for (unsigned i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
template<typename MonitorType>
void integrate (const MonitorType &integral, double *res)
{
Monitor<T> m(integral.dim(), integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Perform importance sampling integration
///
/// \param dim The dimension of the parameter
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
void integrate (unsigned dim,
const typename Monitor<T>::integral_type &integral, double *res)
{
assert(bool(integral));
Monitor<T> m(dim, integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
template<typename MonitorType>
void monitor (const std::string &name, const MonitorType &integral)
{
monitor_.insert(std::make_pair(
name, Monitor<T>(integral.dim(), integral)));
monitor_name_.insert(name);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::integral_type &integral)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
typename std::map<std::string, Monitor<T> >::const_iterator
monitor (const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
const std::map<std::string, Monitor<T> > &monitor () const
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
void path_sampling (const typename Path<T>::integral_type &integral)
{
path_.integral(integral);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
void print (std::ostream &os = std::cout, bool print_header = true) const
{
print(os, print_header, !path_.index().empty(), monitor_name_);
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_path Print path sampling history if \b true
/// \param print_monitor A set of monitor names to be printed
/// \param print_header Print header if \b true
void print (std::ostream &os, bool print_header, bool print_path,
const std::set<std::string> &print_monitor) const
{
if (print_header) {
os << "iter\tESS\tresample\taccept\t";
if (print_path)
os << "path.integrand\tpath.width\tpath.grid\t";
}
typename Path<T>::index_type::const_iterator iter_path_index
= path_.index().begin();
typename Path<T>::integrand_type::const_iterator iter_path_integrand
= path_.integrand().begin();
typename Path<T>::width_type::const_iterator iter_path_width
= path_.width().begin();
typename Path<T>::grid_type::const_iterator iter_path_grid
= path_.grid().begin();
std::vector<bool> monitor_index_empty;
std::vector<unsigned> monitor_dim;
std::vector<typename Monitor<T>::index_type::const_iterator>
iter_monitor_index;
std::vector<typename Monitor<T>::record_type::const_iterator>
iter_monitor_record;
for (typename std::map<std::string, Monitor<T> >::const_iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (print_monitor.count(imap->first)) {
monitor_index_empty.push_back(imap->second.index().empty());
monitor_dim.push_back(imap->second.dim());
iter_monitor_index.push_back(imap->second.index().begin());
iter_monitor_record.push_back(imap->second.record().begin());
if (print_header) {
if (monitor_dim.back() > 1) {
for (unsigned d = 0; d != monitor_dim.back(); ++d)
os << imap->first << d + 1 << '\t';
} else {
os << imap->first << '\t';
}
}
}
}
if (print_header)
os << '\n';
for (unsigned i = 0; i != iter_size(); ++i) {
os
<< i << '\t' << ess_[i] / size()
<< '\t' << resampled_[i]
<< '\t' << static_cast<double>(accept_[i]) / size();
if (print_path) {
if (!path_.index().empty() && *iter_path_index == i) {
os
<< '\t' << *iter_path_integrand++
<< '\t' << *iter_path_width++
<< '\t' << *iter_path_grid++;
++iter_path_index;
} else {
os << '\t' << '.' << '\t' << '.' << '\t' << '.';
}
}
for (unsigned m = 0; m != monitor_index_empty.size(); ++m) {
if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << (*iter_monitor_record[m])[d];
++iter_monitor_index[m];
++iter_monitor_record[m];
} else {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << '.';
}
}
if (i != iter_size() - 1)
os << '\n';
}
}
private :
/// Initialization indicator
bool initialized_;
/// Initialization and movement
initialize_type init_;
move_type move_;
std::vector<move_type> mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
unsigned iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
std::map<std::string, Monitor<T> > monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
bool do_resample = particle_.ess() < threshold_ * size();
if (do_resample)
particle_.resample(scheme_);
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num_, particle_);
}
ess_.push_back(particle_.ess());
resampled_.push_back(do_resample);
particle_.resampled(resampled_.back());
particle_.accept(accept_.back());
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<commit_msg>reserve<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <vSMC/internal/common.hpp>
#include <iostream>
#include <map>
#include <set>
#include <string>
namespace vSMC {
/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<unsigned (Particle<T> &, void *)>
initialize_type;
/// The type of move and mcmc functor
typedef internal::function<unsigned (unsigned, Particle<T> &)>
move_type;
/// The type of ESS history vector
typedef std::vector<double> ess_type;
/// The type of resampling history vector
typedef std::vector<bool> resampled_type;
/// The type of accept count history vector
typedef std::vector<unsigned> accept_type;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
typename Particle<T>::size_type N,
const initialize_type &init = NULL,
const move_type &move = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
initialized_(false), init_(init), move_(move),
scheme_(scheme), threshold_(threshold),
particle_(N, seed), iter_num_(0) {}
/// \brief Size of the particle set
///
/// \return The number of particles
typename Particle<T>::size_type size () const
{
return particle_.size();
}
/// \brief The number of iterations recorded
///
/// \return The number of iterations recorded so far (including the
/// initialization)
unsigned iter_size () const
{
return ess_.size();
}
/// \brief The number of iterations
///
/// \return The number of iterations performed by iterate() so far (not
/// including the initialization)
unsigned iter_num () const
{
return iter_num_;
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold;
}
/// \brief Reserve space for histories
///
/// \param num Expected iteration number
void reserve (unsigned num)
{
ess_.reserve(num);
resampled_.reserve(num);
accept_.reserve(num);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.reserve(num);
}
if (!path_.empty())
path_.reserve(num);
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess () const
{
return ess_;
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled () const
{
return resampled_;
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param new_init New Initialization functor
void init (const initialize_type &new_init)
{
init_ = new_init;
}
/// \brief Replace iteration functor
///
/// \param new_move New Move functor
void move (const move_type &new_move)
{
move_ = new_move;
}
/// \brief Replace iteration functor
///
/// \param new_mcmc New MCMC Move functor
void mcmc (const move_type &new_mcmc)
{
mcmc_.push_back(new_mcmc);
}
/// \brief Clear all MCMC moves
void clear_mcmc ()
{
mcmc_.clear();
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
assert(bool(init_));
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap)
imap->second.clear();
iter_num_ = 0;
accept_.push_back(init_(particle_, param));
post_move();
particle_.reset_zconst();
initialized_ = true;
}
/// \brief Perform iteration
void iterate ()
{
assert(initialized_);
assert(bool(move_));
++iter_num_;
if (bool(move_))
accept_.push_back(move_(iter_num_, particle_));
for (typename std::vector<move_type>::iterator miter = mcmc_.begin();
miter != mcmc_.end(); ++miter)
accept_.back() = (*miter)(iter_num_, particle_);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (unsigned n)
{
for (unsigned i = 0; i != n; ++i)
iterate();
}
/// \brief Perform importance sampling integration
///
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
template<typename MonitorType>
void integrate (const MonitorType &integral, double *res)
{
Monitor<T> m(integral.dim(), integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Perform importance sampling integration
///
/// \param dim The dimension of the parameter
/// \param integral The functor used to compute the integrands
/// \param res The result, an array of length dim
void integrate (unsigned dim,
const typename Monitor<T>::integral_type &integral, double *res)
{
assert(bool(integral));
Monitor<T> m(dim, integral);
m.eval(iter_num_, particle_);
Eigen::Map<Eigen::VectorXd> r(res, m.dim());
r = m.record().back();
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param integral The functor used to compute the integrands
template<typename MonitorType>
void monitor (const std::string &name, const MonitorType &integral)
{
monitor_.insert(std::make_pair(
name, Monitor<T>(integral.dim(), integral)));
monitor_name_.insert(name);
}
/// \brief Add a monitor, similar to \b monitor in \b BUGS
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor
/// \param integral The functor used to compute the integrands
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::integral_type &integral)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, integral)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
typename std::map<std::string, Monitor<T> >::const_iterator
monitor (const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
const std::map<std::string, Monitor<T> > &monitor () const
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling integral
///
/// \param integral The functor used to compute the integrands
void path_sampling (const typename Path<T>::integral_type &integral)
{
path_.integral(integral);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
void print (std::ostream &os = std::cout, bool print_header = true) const
{
print(os, print_header, !path_.index().empty(), monitor_name_);
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_path Print path sampling history if \b true
/// \param print_monitor A set of monitor names to be printed
/// \param print_header Print header if \b true
void print (std::ostream &os, bool print_header, bool print_path,
const std::set<std::string> &print_monitor) const
{
if (print_header) {
os << "iter\tESS\tresample\taccept\t";
if (print_path)
os << "path.integrand\tpath.width\tpath.grid\t";
}
typename Path<T>::index_type::const_iterator iter_path_index
= path_.index().begin();
typename Path<T>::integrand_type::const_iterator iter_path_integrand
= path_.integrand().begin();
typename Path<T>::width_type::const_iterator iter_path_width
= path_.width().begin();
typename Path<T>::grid_type::const_iterator iter_path_grid
= path_.grid().begin();
std::vector<bool> monitor_index_empty;
std::vector<unsigned> monitor_dim;
std::vector<typename Monitor<T>::index_type::const_iterator>
iter_monitor_index;
std::vector<typename Monitor<T>::record_type::const_iterator>
iter_monitor_record;
for (typename std::map<std::string, Monitor<T> >::const_iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (print_monitor.count(imap->first)) {
monitor_index_empty.push_back(imap->second.index().empty());
monitor_dim.push_back(imap->second.dim());
iter_monitor_index.push_back(imap->second.index().begin());
iter_monitor_record.push_back(imap->second.record().begin());
if (print_header) {
if (monitor_dim.back() > 1) {
for (unsigned d = 0; d != monitor_dim.back(); ++d)
os << imap->first << d + 1 << '\t';
} else {
os << imap->first << '\t';
}
}
}
}
if (print_header)
os << '\n';
for (unsigned i = 0; i != iter_num_ + 1; ++i) {
os
<< i << '\t' << ess_[i] / size()
<< '\t' << resampled_[i]
<< '\t' << static_cast<double>(accept_[i]) / size();
if (print_path) {
if (!path_.index().empty() && *iter_path_index == i) {
os
<< '\t' << *iter_path_integrand++
<< '\t' << *iter_path_width++
<< '\t' << *iter_path_grid++;
++iter_path_index;
} else {
os << '\t' << '.' << '\t' << '.' << '\t' << '.';
}
}
for (unsigned m = 0; m != monitor_index_empty.size(); ++m) {
if (!monitor_index_empty[m] && *iter_monitor_index[m] == i) {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << (*iter_monitor_record[m])[d];
++iter_monitor_index[m];
++iter_monitor_record[m];
} else {
for (unsigned d = 0; d != monitor_dim[m]; ++d)
os << '\t' << '.';
}
}
os << '\n';
}
}
private :
/// Initialization indicator
bool initialized_;
/// Initialization and movement
initialize_type init_;
move_type move_;
std::vector<move_type> mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
unsigned iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
std::map<std::string, Monitor<T> > monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
bool do_resample = particle_.ess() < threshold_ * size();
if (do_resample)
particle_.resample(scheme_);
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename std::map<std::string, Monitor<T> >::iterator
imap = monitor_.begin(); imap != monitor_.end(); ++imap) {
if (!imap->second.empty())
imap->second.eval(iter_num_, particle_);
}
ess_.push_back(particle_.ess());
resampled_.push_back(do_resample);
particle_.resampled(resampled_.back());
particle_.accept(accept_.back());
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T>
std::ostream & operator<< (std::ostream &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<|endoftext|> |
<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <vSMC/internal/common.hpp>
#include <ostream>
#include <map>
#include <set>
#include <string>
namespace vSMC {
/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<unsigned (Particle<T> &, void *)>
initialize_type;
/// The type of move and mcmc functor
typedef internal::function<unsigned (unsigned, Particle<T> &)>
move_type;
/// The type of ESS history vector
typedef std::deque<double> ess_type;
/// The type of resampling history vector
typedef std::deque<bool> resampled_type;
/// The type of accept count history vector
typedef std::deque<std::deque<unsigned> > accept_type;
/// The type of Monitor map
typedef std::map<std::string, Monitor<T> > monitor_map_type;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
typename Particle<T>::size_type N,
const initialize_type &init = NULL,
const move_type &move = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
init_(init), move_(move),
scheme_(scheme), threshold_(threshold),
particle_(N, seed), iter_num_(0) {}
/// \brief Size of the particle set
///
/// \return The number of particles
typename Particle<T>::size_type size () const
{
return particle_.size();
}
/// \brief The number of iterations recorded
///
/// \return The number of iterations recorded so far (including the
/// initialization)
unsigned iter_size () const
{
return ess_.size();
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold;
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess () const
{
return ess_;
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled () const
{
return resampled_;
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param new_init New Initialization functor
void init (const initialize_type &new_init)
{
init_ = new_init;
}
/// \brief Replace iteration functor
///
/// \param new_move New Move functor
void move (const move_type &new_move)
{
move_ = new_move;
}
/// \brief Replace iteration functor
///
/// \param new_mcmc New MCMC Move functor
void mcmc (const move_type &new_mcmc)
{
mcmc_.push_back(new_mcmc);
}
/// \brief Clear all MCMC moves
void clear_mcmc ()
{
mcmc_.clear();
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename monitor_map_type::iterator
m = monitor_.begin(); m != monitor_.end(); ++m)
m->second.clear();
iter_num_ = 0;
if (bool(init_)) {
accept_.push_back(
std::deque<unsigned>(1, init_(particle_, param)));
}
#ifndef NDEBUG
else {
std::cerr << "vSMC Warning:" << std::endl;
std::cerr << "\tSampler::initiliaize" << std::end;
std::cerr
<< "\Attempt Initialization without a callable object"
<< std::endl;
}
#endif
post_move();
particle_.reset_zconst();
}
/// \brief Perform iteration
void iterate ()
{
++iter_num_;
std::deque<unsigned> acc;
if (bool(move_)) {
acc.push_back(move_(iter_num_, particle_));
}
#ifndef NDEBUG
else {
std::cerr << "vSMC Warning:" << std::endl;
std::cerr << "\tSampler::iterate" << std::end;
std::cerr
<< "\tAttempt Move without a callable object"
<< std::endl;
}
#endif
for (typename std::deque<move_type>::iterator
m = mcmc_.begin(); m != mcmc_.end(); ++m) {
if (bool(*m)) {
acc.push_back((*m)(iter_num_, particle_));
}
#ifndef NDEBUG
else {
std::cerr << "vSMC Warning:" << std::endl;
std::cerr << "\tSampler::iterate" << std::end;
std::cerr
<< "\tAttempt MCMC without a callable object"
<< std::endl;
}
#endif
}
accept_.push_back(acc);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (unsigned n)
{
for (unsigned i = 0; i != n; ++i)
iterate();
}
/// \brief Add a monitor
///
/// \param name The name of the monitor
/// \param new_monitor The monitor
void monitor (const std::string &name, const Monitor<T> &new_monitor)
{
monitor_.insert(std::make_pair(name, new_monitor));
monitor_name_.insert(name);
}
/// \brief Add a monitor with an evaluation functor
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor, i.e., the number of variables
/// \param eval The functor used to directly evaluate the results
/// \param direct Whether or not eval return the integrands or the final
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::eval_type &eval, bool direct = false)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, eval, direct)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
typename monitor_map_type::const_iterator monitor (
const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read and write access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An iterator point to the monitor for the given name
typename monitor_map_type::iterator monitor (const std::string &name)
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
const monitor_map_type &monitor () const
{
return monitor_;
}
/// \brief Read and write access to all monitors
///
/// \return A reference to monitors
monitor_map_type &monitor ()
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling evaluation functor
///
/// \param eval The functor used to compute the integrands or results
/// \param direct Whether or not eval return the integrands or the final
/// results
void path_sampling (const typename Path<T>::eval_type &eval,
bool direct = false)
{
path_.eval(eval, direct);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
template<typename CharT, typename Traits>
void print (std::basic_ostream<CharT, Traits> &os = std::cout,
bool print_header = true) const
{
const char sep = '\t';
// Accept count
unsigned accd = 0;
for (accept_type::const_iterator
a = accept_.begin(); a != accept_.end(); ++a) {
if (a->size() > accd)
accd = a->size();
}
Eigen::MatrixXd acc(iter_size(), accd);
acc.setConstant(0);
double accdnorm = static_cast<double>(size());
for (unsigned r = 0; r != iter_size(); ++r)
for (unsigned c = 0; c != accept_[r].size(); ++c)
acc(r, c) = accept_[r][c] / accdnorm;
// Path sampling
Eigen::MatrixXd pa(iter_size(), 3);
Eigen::MatrixXi pmask(iter_size(), 1);
pmask.setConstant(false);
for (unsigned d = 0; d != path_.iter_size(); ++d) {
unsigned pr = path_.index()[d];
pa(pr, 0) = path_.integrand()[d];
pa(pr, 1) = path_.width()[d];
pa(pr, 2) = path_.grid()[d];
pmask(pr) = true;
}
// Monitors
unsigned mond = 0;
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
mond += m->second.dim();
}
Eigen::MatrixXd mon(iter_size(), mond);
Eigen::MatrixXi mmask(iter_size(), monitor_.size());
unsigned mc = 0;
unsigned mm = 0;
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
unsigned md = m->second.dim();
for (unsigned d = 0; d != m->second.iter_size(); ++d) {
unsigned mr = m->second.index()[d];
for (unsigned c = 0; c != md; ++c)
mon(mr, c + mc) = m->second.record()[c][d];
mmask(mr, mm) = true;
}
mc += md;
++mm;
}
// Print header
if (print_header) {
os << "Iter" << sep << "ESS" << sep << "ResSam" << sep;
if (accd == 1) {
os << "Accept" << sep;
} else {
for (unsigned d = 0; d != accd; ++d)
os << "Accept." << d + 1 << sep;
}
os
<< "Path.Integrand" << sep
<< "Path.Width" << sep
<< "Path.Grid" << sep << "";
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
if (m->second.dim() == 1) {
os << m->first << sep;
} else {
for (unsigned d = 0; d != m->second.dim(); ++d)
os << m->first << '.' << d + 1 << sep;
}
}
os << '\n';
}
// Print data
for (unsigned iter = 0; iter != iter_size(); ++iter) {
os << iter << sep;
os << ess_[iter] / size() << sep;
os << resampled_[iter] << sep;
os << acc.row(iter) << sep;
if (pmask(iter))
os << pa.row(iter) << sep;
else
os << '.' << sep << '.' << sep << '.' << sep;
unsigned mc = 0;
unsigned mm = 0;
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
unsigned md = m->second.dim();
if (mmask(iter, mm)) {
os << mon.block(iter, mc, 1, md) << sep;
} else {
for (unsigned m = 0; m != md; ++m)
os << '.' << sep;
}
mc += md;
++mm;
}
os << '\n';
}
}
private :
/// Initialization and movement
initialize_type init_;
move_type move_;
std::deque<move_type> mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
unsigned iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
monitor_map_type monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
bool do_resample = particle_.ess() < threshold_ * size();
if (do_resample)
particle_.resample(scheme_);
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename monitor_map_type::iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
if (!m->second.empty())
m->second.eval(iter_num_, particle_);
}
ess_.push_back(particle_.ess());
resampled_.push_back(do_resample);
particle_.resampled(resampled_.back());
particle_.accept(accept_.back().back());
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T, typename CharT, typename Traits>
std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os, true);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<commit_msg>fix typo<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP
#define V_SMC_CORE_SAMPLER_HPP
#include <vSMC/internal/common.hpp>
#include <ostream>
#include <map>
#include <set>
#include <string>
namespace vSMC {
/// \brief SMC Sampler
///
/// \tparam T State state type. Requiment:
/// \li Consturctor: T (IntType N)
/// \li Method: copy (IntType from, IntType to)
template <typename T>
class Sampler
{
public :
/// The type of initialization functor
typedef internal::function<unsigned (Particle<T> &, void *)>
initialize_type;
/// The type of move and mcmc functor
typedef internal::function<unsigned (unsigned, Particle<T> &)>
move_type;
/// The type of ESS history vector
typedef std::deque<double> ess_type;
/// The type of resampling history vector
typedef std::deque<bool> resampled_type;
/// The type of accept count history vector
typedef std::deque<std::deque<unsigned> > accept_type;
/// The type of Monitor map
typedef std::map<std::string, Monitor<T> > monitor_map_type;
/// \brief Construct a sampler with given number of particles
///
/// \param N The number of particles
/// \param init The functor used to initialize the particles
/// \param move The functor used to move the particles and weights
/// \param scheme The resampling scheme. See ResampleScheme
/// \param threshold The threshold for performing resampling
/// \param seed The seed to the parallel RNG system
explicit Sampler (
typename Particle<T>::size_type N,
const initialize_type &init = NULL,
const move_type &move = NULL,
ResampleScheme scheme = STRATIFIED,
double threshold = 0.5,
typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :
init_(init), move_(move),
scheme_(scheme), threshold_(threshold),
particle_(N, seed), iter_num_(0) {}
/// \brief Size of the particle set
///
/// \return The number of particles
typename Particle<T>::size_type size () const
{
return particle_.size();
}
/// \brief The number of iterations recorded
///
/// \return The number of iterations recorded so far (including the
/// initialization)
unsigned iter_size () const
{
return ess_.size();
}
/// \brief Get the current resampling scheme
///
/// \return The current resampling scheme
ResampleScheme resample_scheme () const
{
return scheme_;
}
/// \brief Set new resampling scheme
///
/// \param scheme The new scheme for resampling
void resample_scheme (ResampleScheme scheme)
{
scheme_ = scheme;
}
/// \brief Get the current threshold
///
/// \return The current threshold for resmapling
double resample_threshold () const
{
return threshold_;
}
/// \brief Set new resampling threshold
///
/// \param threshold The new threshold for resampling
void resample_threshold (double threshold)
{
threshold_ = threshold;
}
/// \brief ESS history
///
/// \return A const reference to the history of ESS
const ess_type &ess () const
{
return ess_;
}
/// \brief Resampling history
///
/// \return A const reference to the history of resampling
const resampled_type &resampled () const
{
return resampled_;
}
/// \brief Accept count history
///
/// \return A const reference to the history of accept count
const accept_type &accept () const
{
return accept_;
}
/// \brief Read and write access to the particle set
///
/// \return A reference to the latest particle set
Particle<T> &particle ()
{
return particle_;
}
/// \brief Read only access to the particle set
///
/// \return A const reference to the latest particle set.
const Particle<T> &particle () const
{
return particle_;
}
/// \brief Replace initialization functor
///
/// \param new_init New Initialization functor
void init (const initialize_type &new_init)
{
init_ = new_init;
}
/// \brief Replace iteration functor
///
/// \param new_move New Move functor
void move (const move_type &new_move)
{
move_ = new_move;
}
/// \brief Replace iteration functor
///
/// \param new_mcmc New MCMC Move functor
void mcmc (const move_type &new_mcmc)
{
mcmc_.push_back(new_mcmc);
}
/// \brief Clear all MCMC moves
void clear_mcmc ()
{
mcmc_.clear();
}
/// \brief Initialize the particle set
///
/// \param param Additional parameters passed to the initialization
/// functor
void initialize (void *param = NULL)
{
ess_.clear();
resampled_.clear();
accept_.clear();
path_.clear();
for (typename monitor_map_type::iterator
m = monitor_.begin(); m != monitor_.end(); ++m)
m->second.clear();
iter_num_ = 0;
if (bool(init_)) {
accept_.push_back(
std::deque<unsigned>(1, init_(particle_, param)));
}
#ifndef NDEBUG
else {
std::cerr << "vSMC Warning:" << std::endl;
std::cerr << "\tSampler::initiliaize" << std::endl;
std::cerr
<< "\Attempt Initialization without a callable object"
<< std::endl;
}
#endif
post_move();
particle_.reset_zconst();
}
/// \brief Perform iteration
void iterate ()
{
++iter_num_;
std::deque<unsigned> acc;
if (bool(move_)) {
acc.push_back(move_(iter_num_, particle_));
}
#ifndef NDEBUG
else {
std::cerr << "vSMC Warning:" << std::endl;
std::cerr << "\tSampler::iterate" << std::endl;
std::cerr
<< "\tAttempt Move without a callable object"
<< std::endl;
}
#endif
for (typename std::deque<move_type>::iterator
m = mcmc_.begin(); m != mcmc_.end(); ++m) {
if (bool(*m)) {
acc.push_back((*m)(iter_num_, particle_));
}
#ifndef NDEBUG
else {
std::cerr << "vSMC Warning:" << std::endl;
std::cerr << "\tSampler::iterate" << std::endl;
std::cerr
<< "\tAttempt MCMC without a callable object"
<< std::endl;
}
#endif
}
accept_.push_back(acc);
post_move();
}
/// \brief Perform iteration
///
/// \param n The number of iterations to be performed
void iterate (unsigned n)
{
for (unsigned i = 0; i != n; ++i)
iterate();
}
/// \brief Add a monitor
///
/// \param name The name of the monitor
/// \param new_monitor The monitor
void monitor (const std::string &name, const Monitor<T> &new_monitor)
{
monitor_.insert(std::make_pair(name, new_monitor));
monitor_name_.insert(name);
}
/// \brief Add a monitor with an evaluation functor
///
/// \param name The name of the monitor
/// \param dim The dimension of the monitor, i.e., the number of variables
/// \param eval The functor used to directly evaluate the results
/// \param direct Whether or not eval return the integrands or the final
void monitor (const std::string &name, unsigned dim,
const typename Monitor<T>::eval_type &eval, bool direct = false)
{
monitor_.insert(std::make_pair(name, Monitor<T>(dim, eval, direct)));
monitor_name_.insert(name);
}
/// \brief Read only access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An const_iterator point to the monitor for the given name
typename monitor_map_type::const_iterator monitor (
const std::string &name) const
{
return monitor_.find(name);
}
/// \brief Read and write access to a named monitor through iterator
///
/// \param name The name of the monitor
///
/// \return An iterator point to the monitor for the given name
typename monitor_map_type::iterator monitor (const std::string &name)
{
return monitor_.find(name);
}
/// \brief Read only access to all monitors
///
/// \return A const reference to monitors
const monitor_map_type &monitor () const
{
return monitor_;
}
/// \brief Read and write access to all monitors
///
/// \return A reference to monitors
monitor_map_type &monitor ()
{
return monitor_;
}
/// \brief Erase a named monitor
///
/// \param name The name of the monitor
void clear_monitor (const std::string &name)
{
monitor_.erase(name);
monitor_name_.erase(name);
}
/// \brief Erase all monitors
void clear_monitor ()
{
monitor_.clear();
monitor_name_.clear();
}
/// \brief Read only access to the Path sampling monitor
///
/// \return A const reference to the Path sampling monitor
const Path<T> &path () const
{
return path_;
}
/// \brief Set the path sampling evaluation functor
///
/// \param eval The functor used to compute the integrands or results
/// \param direct Whether or not eval return the integrands or the final
/// results
void path_sampling (const typename Path<T>::eval_type &eval,
bool direct = false)
{
path_.eval(eval, direct);
}
/// \brief Path sampling estimate of normalizing constant
///
/// \return The log ratio of normalizing constants
double path_sampling () const
{
return path_.zconst();
}
/// \brief SMC estimate of normalizing constant
///
/// \return The log of SMC normalizng constant estimate
double zconst () const
{
return particle_.zconst();
}
/// \brief Print the history of the sampler
///
/// \param os The ostream to which the contents are printed
/// \param print_header Print header if \b true
template<typename CharT, typename Traits>
void print (std::basic_ostream<CharT, Traits> &os = std::cout,
bool print_header = true) const
{
const char sep = '\t';
// Accept count
unsigned accd = 0;
for (accept_type::const_iterator
a = accept_.begin(); a != accept_.end(); ++a) {
if (a->size() > accd)
accd = a->size();
}
Eigen::MatrixXd acc(iter_size(), accd);
acc.setConstant(0);
double accdnorm = static_cast<double>(size());
for (unsigned r = 0; r != iter_size(); ++r)
for (unsigned c = 0; c != accept_[r].size(); ++c)
acc(r, c) = accept_[r][c] / accdnorm;
// Path sampling
Eigen::MatrixXd pa(iter_size(), 3);
Eigen::MatrixXi pmask(iter_size(), 1);
pmask.setConstant(false);
for (unsigned d = 0; d != path_.iter_size(); ++d) {
unsigned pr = path_.index()[d];
pa(pr, 0) = path_.integrand()[d];
pa(pr, 1) = path_.width()[d];
pa(pr, 2) = path_.grid()[d];
pmask(pr) = true;
}
// Monitors
unsigned mond = 0;
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
mond += m->second.dim();
}
Eigen::MatrixXd mon(iter_size(), mond);
Eigen::MatrixXi mmask(iter_size(), monitor_.size());
unsigned mc = 0;
unsigned mm = 0;
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
unsigned md = m->second.dim();
for (unsigned d = 0; d != m->second.iter_size(); ++d) {
unsigned mr = m->second.index()[d];
for (unsigned c = 0; c != md; ++c)
mon(mr, c + mc) = m->second.record()[c][d];
mmask(mr, mm) = true;
}
mc += md;
++mm;
}
// Print header
if (print_header) {
os << "Iter" << sep << "ESS" << sep << "ResSam" << sep;
if (accd == 1) {
os << "Accept" << sep;
} else {
for (unsigned d = 0; d != accd; ++d)
os << "Accept." << d + 1 << sep;
}
os
<< "Path.Integrand" << sep
<< "Path.Width" << sep
<< "Path.Grid" << sep << "";
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
if (m->second.dim() == 1) {
os << m->first << sep;
} else {
for (unsigned d = 0; d != m->second.dim(); ++d)
os << m->first << '.' << d + 1 << sep;
}
}
os << '\n';
}
// Print data
for (unsigned iter = 0; iter != iter_size(); ++iter) {
os << iter << sep;
os << ess_[iter] / size() << sep;
os << resampled_[iter] << sep;
os << acc.row(iter) << sep;
if (pmask(iter))
os << pa.row(iter) << sep;
else
os << '.' << sep << '.' << sep << '.' << sep;
unsigned mc = 0;
unsigned mm = 0;
for (typename monitor_map_type::const_iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
unsigned md = m->second.dim();
if (mmask(iter, mm)) {
os << mon.block(iter, mc, 1, md) << sep;
} else {
for (unsigned m = 0; m != md; ++m)
os << '.' << sep;
}
mc += md;
++mm;
}
os << '\n';
}
}
private :
/// Initialization and movement
initialize_type init_;
move_type move_;
std::deque<move_type> mcmc_;
/// Resampling
ResampleScheme scheme_;
double threshold_;
/// Particle sets
Particle<T> particle_;
unsigned iter_num_;
ess_type ess_;
resampled_type resampled_;
accept_type accept_;
/// Monte Carlo estimation by integration
monitor_map_type monitor_;
std::set<std::string> monitor_name_;
/// Path sampling
Path<T> path_;
void post_move ()
{
bool do_resample = particle_.ess() < threshold_ * size();
if (do_resample)
particle_.resample(scheme_);
if (!path_.empty())
path_.eval(iter_num_, particle_);
for (typename monitor_map_type::iterator
m = monitor_.begin(); m != monitor_.end(); ++m) {
if (!m->second.empty())
m->second.eval(iter_num_, particle_);
}
ess_.push_back(particle_.ess());
resampled_.push_back(do_resample);
particle_.resampled(resampled_.back());
particle_.accept(accept_.back().back());
}
}; // class Sampler
} // namespace vSMC
namespace std {
/// \brief Print the sampler
///
/// \param os The ostream to which the contents are printed
/// \param sampler The sampler to be printed
///
/// \note This is the same as <tt>sampler.print(os)</tt>
template<typename T, typename CharT, typename Traits>
std::basic_ostream<CharT, Traits> &operator<< (
std::basic_ostream<CharT, Traits> &os, const vSMC::Sampler<T> &sampler)
{
sampler.print(os, true);
return os;
}
} // namespace std
#endif // V_SMC_CORE_SAMPLER_HPP
<|endoftext|> |
<commit_before>#ifndef NANO_SIGNAL_SLOT_HPP
#define NANO_SIGNAL_SLOT_HPP
#include "nano_function.hpp"
#include "nano_observer.hpp"
namespace Nano
{
template <typename RT> class Signal;
template <typename RT, typename... Args>
class Signal<RT(Args...)> : private Observer
{
template <typename T>
void insert_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::insert(key, instance);
instance->insert(key, this);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::remove(key);
instance->remove(key);
}
template <typename T>
void insert_sfinae(DelegateKey const& key, ...)
{
Observer::insert(key);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, ...)
{
Observer::remove(key);
}
public:
using Delegate = Function<RT(Args...)>;
//-------------------------------------------------------------------CONNECT
template <typename L>
void connect(L* instance)
{
Observer::insert(Delegate::template bind (instance));
}
template <typename L>
void connect(L& instance)
{
connect(std::addressof(instance));
}
template <RT (* fun_ptr)(Args...)>
void connect()
{
Observer::insert(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------------------DISCONNECT
template <typename L>
void disconnect(L* instance)
{
Observer::remove(Delegate::template bind (instance));
}
template <typename L>
void disconnect(L& instance)
{
disconnect(std::addressof(instance));
}
template <RT (* fun_ptr)(Args...)>
void disconnect()
{
Observer::remove(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------EMIT / EMIT ACCUMULATE
#ifdef NANO_USE_DEPRECATED
/// Will not benefit from perfect forwarding
/// TODO [[deprecated]] when c++14 is comfortably supported
void operator() (Args... args)
{
emit(std::forward<Args>(args)...);
}
template <typename Accumulate>
void operator() (Args... args, Accumulate&& accumulate)
{
emit_accumulate<Accumulate>
(std::forward<Accumulate>(accumulate), std::forward<Args>(args)...);
}
#endif
template <typename... Uref>
void emit(Uref&&... args)
{
Observer::onEach<Delegate>(std::forward<Uref>(args)...);
}
template <typename Accumulate, typename... Uref>
void emit_accumulate(Accumulate&& accumulate, Uref&&... args)
{
Observer::onEach_Accumulate<Delegate, Accumulate>
(std::forward<Accumulate>(accumulate), std::forward<Uref>(args)...);
}
//---------------------------------------------------------------------EMPTY
bool empty() {
return Observer::empty();
}
};
} // namespace Nano ------------------------------------------------------------
#endif // NANO_SIGNAL_SLOT_HPP
<commit_msg>Normalize newline.<commit_after>#ifndef NANO_SIGNAL_SLOT_HPP
#define NANO_SIGNAL_SLOT_HPP
#include "nano_function.hpp"
#include "nano_observer.hpp"
namespace Nano
{
template <typename RT> class Signal;
template <typename RT, typename... Args>
class Signal<RT(Args...)> : private Observer
{
template <typename T>
void insert_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::insert(key, instance);
instance->insert(key, this);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, typename T::Observer* instance)
{
Observer::remove(key);
instance->remove(key);
}
template <typename T>
void insert_sfinae(DelegateKey const& key, ...)
{
Observer::insert(key);
}
template <typename T>
void remove_sfinae(DelegateKey const& key, ...)
{
Observer::remove(key);
}
public:
using Delegate = Function<RT(Args...)>;
//-------------------------------------------------------------------CONNECT
template <typename L>
void connect(L* instance)
{
Observer::insert(Delegate::template bind (instance));
}
template <typename L>
void connect(L& instance)
{
connect(std::addressof(instance));
}
template <RT (* fun_ptr)(Args...)>
void connect()
{
Observer::insert(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void connect(T* instance)
{
insert_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void connect(T& instance)
{
connect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------------------DISCONNECT
template <typename L>
void disconnect(L* instance)
{
Observer::remove(Delegate::template bind (instance));
}
template <typename L>
void disconnect(L& instance)
{
disconnect(std::addressof(instance));
}
template <RT (* fun_ptr)(Args...)>
void disconnect()
{
Observer::remove(Delegate::template bind<fun_ptr>());
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void disconnect(T* instance)
{
remove_sfinae<T>(Delegate::template bind<T, mem_ptr>(instance), instance);
}
template <typename T, RT (T::* mem_ptr)(Args...)>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
template <typename T, RT (T::* mem_ptr)(Args...) const>
void disconnect(T& instance)
{
disconnect<T, mem_ptr>(std::addressof(instance));
}
//----------------------------------------------------EMIT / EMIT ACCUMULATE
#ifdef NANO_USE_DEPRECATED
/// Will not benefit from perfect forwarding
/// TODO [[deprecated]] when c++14 is comfortably supported
void operator() (Args... args)
{
emit(std::forward<Args>(args)...);
}
template <typename Accumulate>
void operator() (Args... args, Accumulate&& accumulate)
{
emit_accumulate<Accumulate>
(std::forward<Accumulate>(accumulate), std::forward<Args>(args)...);
}
#endif
template <typename... Uref>
void emit(Uref&&... args)
{
Observer::onEach<Delegate>(std::forward<Uref>(args)...);
}
template <typename Accumulate, typename... Uref>
void emit_accumulate(Accumulate&& accumulate, Uref&&... args)
{
Observer::onEach_Accumulate<Delegate, Accumulate>
(std::forward<Accumulate>(accumulate), std::forward<Uref>(args)...);
}
//---------------------------------------------------------------------EMPTY
bool empty()
{
return Observer::empty();
}
};
} // namespace Nano ------------------------------------------------------------
#endif // NANO_SIGNAL_SLOT_HPP
<|endoftext|> |
<commit_before><commit_msg>Getting confused about the derivative...<commit_after><|endoftext|> |
<commit_before><commit_msg>Allocate deep copied varis on no-chain stack<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_FILE_HDF5_H
#define NIX_FILE_HDF5_H
#include <nix/base/IFile.hpp>
#include <nix/Version.hpp>
#include "h5x/H5Group.hpp"
#include <string>
#include <memory>
#define HDF5_FF_VERSION nix::FormatVersion({1, 0, 0})
namespace nix {
namespace hdf5 {
/**
* Class that represents a NIX file.
*/
class FileHDF5 : public H5Object, public base::IFile, public std::enable_shared_from_this<FileHDF5> {
private:
/* groups representing different sections of the file */
H5Group root, metadata, data;
FileMode mode;
public:
/**
* Constructor that is used to open the file.
*
* @param name The name of the file to open.
* @param prefix The prefix used for IDs.
* @param mode File open mode ReadOnly, ReadWrite or Overwrite.
*/
FileHDF5(const std::string &name, const FileMode mode = FileMode::ReadWrite);
//--------------------------------------------------
// Methods concerning blocks
//--------------------------------------------------
ndsize_t blockCount() const;
bool hasBlock(const std::string &name_or_id) const;
std::shared_ptr<base::IBlock> getBlock(const std::string &name_or_id) const;
std::shared_ptr<base::IBlock> getBlock(ndsize_t index) const;
std::shared_ptr<base::IBlock> createBlock(const std::string &name, const std::string &type);
bool deleteBlock(const std::string &name_or_id);
//--------------------------------------------------
// Methods concerning sections
//--------------------------------------------------
bool hasSection(const std::string &name_or_id) const;
std::shared_ptr<base::ISection> getSection(const std::string &name_or_id) const;
std::shared_ptr<base::ISection> getSection(ndsize_t index) const;
ndsize_t sectionCount() const;
std::shared_ptr<base::ISection> createSection(const std::string &name, const std::string &type);
bool deleteSection(const std::string &name_or_id);
//--------------------------------------------------
// Methods for file attribute access.
//--------------------------------------------------
std::vector<int> version() const;
std::string format() const;
std::string location() const;
time_t createdAt() const;
time_t updatedAt() const;
void setUpdatedAt();
void forceUpdatedAt();
void setCreatedAt();
void forceCreatedAt(time_t t);
void close();
bool isOpen() const;
FileMode fileMode() const;
bool operator==(const FileHDF5 &other) const;
bool operator!=(const FileHDF5 &other) const;
virtual ~FileHDF5();
private:
std::shared_ptr<base::IFile> file() const;
// check for existence
bool fileExists(const std::string &name) const;
void openRoot();
bool checkHeader(FileMode mode) const;
void createHeader() const;
};
} // namespace hdf5
} // namespace nix
#endif // NIX_FILE_HDF5_H
<commit_msg>[Version] File format version: 1.1.0<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_FILE_HDF5_H
#define NIX_FILE_HDF5_H
#include <nix/base/IFile.hpp>
#include <nix/Version.hpp>
#include "h5x/H5Group.hpp"
#include <string>
#include <memory>
#define HDF5_FF_VERSION nix::FormatVersion({1, 1, 0})
namespace nix {
namespace hdf5 {
/**
* Class that represents a NIX file.
*/
class FileHDF5 : public H5Object, public base::IFile, public std::enable_shared_from_this<FileHDF5> {
private:
/* groups representing different sections of the file */
H5Group root, metadata, data;
FileMode mode;
public:
/**
* Constructor that is used to open the file.
*
* @param name The name of the file to open.
* @param prefix The prefix used for IDs.
* @param mode File open mode ReadOnly, ReadWrite or Overwrite.
*/
FileHDF5(const std::string &name, const FileMode mode = FileMode::ReadWrite);
//--------------------------------------------------
// Methods concerning blocks
//--------------------------------------------------
ndsize_t blockCount() const;
bool hasBlock(const std::string &name_or_id) const;
std::shared_ptr<base::IBlock> getBlock(const std::string &name_or_id) const;
std::shared_ptr<base::IBlock> getBlock(ndsize_t index) const;
std::shared_ptr<base::IBlock> createBlock(const std::string &name, const std::string &type);
bool deleteBlock(const std::string &name_or_id);
//--------------------------------------------------
// Methods concerning sections
//--------------------------------------------------
bool hasSection(const std::string &name_or_id) const;
std::shared_ptr<base::ISection> getSection(const std::string &name_or_id) const;
std::shared_ptr<base::ISection> getSection(ndsize_t index) const;
ndsize_t sectionCount() const;
std::shared_ptr<base::ISection> createSection(const std::string &name, const std::string &type);
bool deleteSection(const std::string &name_or_id);
//--------------------------------------------------
// Methods for file attribute access.
//--------------------------------------------------
std::vector<int> version() const;
std::string format() const;
std::string location() const;
time_t createdAt() const;
time_t updatedAt() const;
void setUpdatedAt();
void forceUpdatedAt();
void setCreatedAt();
void forceCreatedAt(time_t t);
void close();
bool isOpen() const;
FileMode fileMode() const;
bool operator==(const FileHDF5 &other) const;
bool operator!=(const FileHDF5 &other) const;
virtual ~FileHDF5();
private:
std::shared_ptr<base::IFile> file() const;
// check for existence
bool fileExists(const std::string &name) const;
void openRoot();
bool checkHeader(FileMode mode) const;
void createHeader() const;
};
} // namespace hdf5
} // namespace nix
#endif // NIX_FILE_HDF5_H
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <deque>
#include <boost/cstdint.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set.hpp>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
namespace pt = boost::posix_time;
namespace libtorrent { namespace dht
{
using asio::ip::udp;
//TORRENT_DECLARE_LOG(table);
typedef std::deque<node_entry> bucket_t;
// differences in the implementation from the description in
// the paper:
//
// * The routing table tree is not allocated dynamically, there
// are always 160 buckets.
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class routing_table;
namespace aux
{
// Iterates over a flattened routing_table structure.
class routing_table_iterator
: public boost::iterator_facade<
routing_table_iterator
, node_entry const
, boost::forward_traversal_tag
>
{
public:
routing_table_iterator()
{
}
private:
friend class libtorrent::dht::routing_table;
friend class boost::iterator_core_access;
typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator
bucket_iterator_t;
routing_table_iterator(
bucket_iterator_t begin
, bucket_iterator_t end)
: m_bucket_iterator(begin)
, m_bucket_end(end)
, m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator())
{
if (m_bucket_iterator == m_bucket_end) return;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
bool equal(routing_table_iterator const& other) const
{
return m_bucket_iterator == other.m_bucket_iterator
&& (m_bucket_iterator == m_bucket_end
|| m_iterator == other.m_iterator);
}
void increment()
{
assert(m_bucket_iterator != m_bucket_end);
++m_iterator;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
node_entry const& dereference() const
{
assert(m_bucket_iterator != m_bucket_end);
return *m_iterator;
}
bucket_iterator_t m_bucket_iterator;
bucket_iterator_t m_bucket_end;
bucket_t::const_iterator m_iterator;
};
} // namespace aux
class routing_table
{
public:
typedef aux::routing_table_iterator iterator;
typedef iterator const_iterator;
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void node_failed(node_id const& id);
// adds an endpoint that will never be added to
// the routing table
void add_router_node(udp::endpoint router);
// iterates over the router nodes added
typedef std::set<udp::endpoint>::const_iterator router_iterator;
router_iterator router_begin() const { return m_router_nodes.begin(); }
router_iterator router_end() const { return m_router_nodes.end(); }
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint addr);
// returns time when the given bucket needs another refresh.
// if the given bucket is empty but there are nodes
// in a bucket closer to us, or if the bucket is non-empty and
// the time from the last activity is more than 15 minutes
boost::posix_time::ptime next_refresh(int bucket);
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, bool include_self, int count = 0);
// returns true if the given node would be placed in a bucket
// that is not full. If the node already exists in the table
// this function returns false
bool need_node(node_id const& id);
// this will set the given bucket's latest activity
// to the current time
void touch_bucket(int bucket);
int bucket_size(int bucket)
{
assert(bucket >= 0 && bucket < 160);
return (int)m_buckets[bucket].first.size();
}
int bucket_size() const { return m_bucket_size; }
iterator begin() const;
iterator end() const;
boost::tuple<int, int> size() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
void replacement_cache(bucket_t& nodes) const;
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
private:
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// 160 (k-bucket, replacement cache) pairs
typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t;
table_t m_buckets;
// timestamps of the last activity in each bucket
typedef boost::array<boost::posix_time::ptime, 160> table_activity_t;
table_activity_t m_bucket_activity;
node_id m_id; // our own node id
// this is a set of all the endpoints that have
// been identified as router nodes. They will
// be used in searches, but they will never
// be added to the routing table.
std::set<udp::endpoint> m_router_nodes;
// this is the lowest bucket index with nodes in it
int m_lowest_active_bucket;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<commit_msg>fixed incorrect include of standard header with .hpp-sufix<commit_after>/*
Copyright (c) 2006, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ROUTING_TABLE_HPP
#define ROUTING_TABLE_HPP
#include <vector>
#include <deque>
#include <boost/cstdint.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/utility.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/array.hpp>
#include <set>
#include <libtorrent/kademlia/logging.hpp>
#include <libtorrent/kademlia/node_id.hpp>
#include <libtorrent/kademlia/node_entry.hpp>
#include <libtorrent/session_settings.hpp>
namespace pt = boost::posix_time;
namespace libtorrent { namespace dht
{
using asio::ip::udp;
//TORRENT_DECLARE_LOG(table);
typedef std::deque<node_entry> bucket_t;
// differences in the implementation from the description in
// the paper:
//
// * The routing table tree is not allocated dynamically, there
// are always 160 buckets.
// * Nodes are not marked as being stale, they keep a counter
// that tells how many times in a row they have failed. When
// a new node is to be inserted, the node that has failed
// the most times is replaced. If none of the nodes in the
// bucket has failed, then it is put in the replacement
// cache (just like in the paper).
class routing_table;
namespace aux
{
// Iterates over a flattened routing_table structure.
class routing_table_iterator
: public boost::iterator_facade<
routing_table_iterator
, node_entry const
, boost::forward_traversal_tag
>
{
public:
routing_table_iterator()
{
}
private:
friend class libtorrent::dht::routing_table;
friend class boost::iterator_core_access;
typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator
bucket_iterator_t;
routing_table_iterator(
bucket_iterator_t begin
, bucket_iterator_t end)
: m_bucket_iterator(begin)
, m_bucket_end(end)
, m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator())
{
if (m_bucket_iterator == m_bucket_end) return;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
bool equal(routing_table_iterator const& other) const
{
return m_bucket_iterator == other.m_bucket_iterator
&& (m_bucket_iterator == m_bucket_end
|| m_iterator == other.m_iterator);
}
void increment()
{
assert(m_bucket_iterator != m_bucket_end);
++m_iterator;
while (m_iterator == m_bucket_iterator->first.end())
{
if (++m_bucket_iterator == m_bucket_end)
break;
m_iterator = m_bucket_iterator->first.begin();
}
}
node_entry const& dereference() const
{
assert(m_bucket_iterator != m_bucket_end);
return *m_iterator;
}
bucket_iterator_t m_bucket_iterator;
bucket_iterator_t m_bucket_end;
bucket_t::const_iterator m_iterator;
};
} // namespace aux
class routing_table
{
public:
typedef aux::routing_table_iterator iterator;
typedef iterator const_iterator;
routing_table(node_id const& id, int bucket_size
, dht_settings const& settings);
void node_failed(node_id const& id);
// adds an endpoint that will never be added to
// the routing table
void add_router_node(udp::endpoint router);
// iterates over the router nodes added
typedef std::set<udp::endpoint>::const_iterator router_iterator;
router_iterator router_begin() const { return m_router_nodes.begin(); }
router_iterator router_end() const { return m_router_nodes.end(); }
// this function is called every time the node sees
// a sign of a node being alive. This node will either
// be inserted in the k-buckets or be moved to the top
// of its bucket.
bool node_seen(node_id const& id, udp::endpoint addr);
// returns time when the given bucket needs another refresh.
// if the given bucket is empty but there are nodes
// in a bucket closer to us, or if the bucket is non-empty and
// the time from the last activity is more than 15 minutes
boost::posix_time::ptime next_refresh(int bucket);
// fills the vector with the count nodes from our buckets that
// are nearest to the given id.
void find_node(node_id const& id, std::vector<node_entry>& l
, bool include_self, int count = 0);
// returns true if the given node would be placed in a bucket
// that is not full. If the node already exists in the table
// this function returns false
bool need_node(node_id const& id);
// this will set the given bucket's latest activity
// to the current time
void touch_bucket(int bucket);
int bucket_size(int bucket)
{
assert(bucket >= 0 && bucket < 160);
return (int)m_buckets[bucket].first.size();
}
int bucket_size() const { return m_bucket_size; }
iterator begin() const;
iterator end() const;
boost::tuple<int, int> size() const;
// returns true if there are no working nodes
// in the routing table
bool need_bootstrap() const;
void replacement_cache(bucket_t& nodes) const;
// used for debug and monitoring purposes. This will print out
// the state of the routing table to the given stream
void print_state(std::ostream& os) const;
private:
// constant called k in paper
int m_bucket_size;
dht_settings const& m_settings;
// 160 (k-bucket, replacement cache) pairs
typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t;
table_t m_buckets;
// timestamps of the last activity in each bucket
typedef boost::array<boost::posix_time::ptime, 160> table_activity_t;
table_activity_t m_bucket_activity;
node_id m_id; // our own node id
// this is a set of all the endpoints that have
// been identified as router nodes. They will
// be used in searches, but they will never
// be added to the routing table.
std::set<udp::endpoint> m_router_nodes;
// this is the lowest bucket index with nodes in it
int m_lowest_active_bucket;
};
} } // namespace libtorrent::dht
#endif // ROUTING_TABLE_HPP
<|endoftext|> |
<commit_before>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_EDITOR_SETTINGSBAR_HPP
#define RJ_GAME_EDITOR_SETTINGSBAR_HPP
#include "button_item.hpp"
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>
#include <rectojump/ui/connected_buttons.hpp>
namespace rj
{
template<typename Editor>
class settingsbar
{
Editor& m_editor;
typename Editor::gh_type& m_gamehandler;
rndr& m_render;
// interface
sf::RectangleShape m_shape;
ui::connected_buttons m_buttons;
ui::button m_toggle_bar_button{{16.f, 16.f}, {16.f, 16.f}};
sf::Texture m_toggle_bar_button_tx;
sf::Font m_font;
// moving
bool m_is_expanded{true}, m_moving{false}, m_need_move_right{false}, m_need_move_left{false};
float m_moved{0.f};
float m_max_move{m_shape.getSize().x - 32.f};
static constexpr float m_move_step{1.f};
public:
settingsbar(Editor& e, const vec2f& size) :
m_editor{e},
m_gamehandler{e.get_gamehandler()},
m_render{m_gamehandler.get_render()},
m_shape{size},
m_toggle_bar_button_tx{m_gamehandler.get_datamgr().template get_as<sf::Texture>("arrow.png")},
m_font{m_gamehandler.get_datamgr().template get_as<sf::Font>("Fipps-Regular.otf")}
{this->init();}
~settingsbar()
{settings::set_editor_settings_expanded(m_is_expanded);}
void update(dur duration)
{
m_buttons.update(duration);
m_toggle_bar_button.update(duration);
if(m_toggle_bar_button.is_pressed() && !m_moving)
{
m_moved = 0.f;
flip_h(m_toggle_bar_button);
if(m_is_expanded) m_need_move_right = true;
else m_need_move_left = true;
}
if(m_need_move_right)
{
if(m_moved > m_max_move)
{
m_moving = false;
m_need_move_right = false;
m_is_expanded = false;
return;
}
m_moving = true;
auto move_offset(vec2f{m_move_step, 0.f} * duration);
this->move(move_offset);
m_moved += move_offset.x;
}
if(m_need_move_left)
{
if(m_moved > m_max_move)
{
m_moving = false;
m_need_move_left = false;
m_is_expanded = true;
return;
}
m_moving = true;
auto move_offset(vec2f{-m_move_step, 0.f} * duration);
this->move(move_offset);
m_moved += -move_offset.x;
}
}
void render()
{
m_render(m_shape, m_toggle_bar_button, m_buttons);
}
const vec2f& get_size() const noexcept
{return m_shape.getSize();}
private:
void init()
{
// shape
auto& shape_size(m_shape.getSize());
m_shape.setOrigin(shape_size / 2.f);
m_shape.setPosition(shape_size / 2.f);
m_shape.setFillColor(settings::get_color_default_light());
// toggle (expand) settings bar
m_toggle_bar_button.set_origin(m_toggle_bar_button.get_size() / 2.f);
m_toggle_bar_button.set_texture(&m_toggle_bar_button_tx);
if(settings::get_editor_settings_expanded())
flip_h(m_toggle_bar_button);
else m_need_move_right = true;
// buttons
vec2f btn_size{80.f, 40.f};
auto save_btn(m_buttons.add_button_event<button_item>(
[this]{m_editor.handle_save();}, btn_size, vec2f{shape_size.x / 2.f - 60.f, shape_size.y - btn_size.y}));
save_btn->set_origin(btn_size / 2.f);
save_btn->set_font(m_font);
save_btn->set_fontsize(16);
save_btn->set_text("Save");
save_btn->set_fontcolor(settings::get_color_light());
auto load_btn(m_buttons.add_button_event<button_item>(
[this]{m_editor.handle_load();}, btn_size, vec2f{shape_size.x / 2.f + 60.f, shape_size.y - btn_size.y}));
load_btn->set_origin(btn_size / 2.f);
load_btn->set_font(m_font);
load_btn->set_fontsize(16);
load_btn->set_text("Load");
load_btn->set_fontcolor(settings::get_color_light());
}
void move(const vec2f& offset) noexcept
{
m_shape.move(offset);
m_toggle_bar_button.move(offset);
for(auto& a : m_buttons.get_buttons())
a.second.button->move(offset);
}
};
}
#endif // RJ_GAME_EDITOR_SETTINGSBAR_HPP
<commit_msg>settingsbar: added get_bounds()<commit_after>//
// Copyright (c) 2013-2014 Christoph Malek
// See LICENSE for more information.
//
#ifndef RJ_GAME_EDITOR_SETTINGSBAR_HPP
#define RJ_GAME_EDITOR_SETTINGSBAR_HPP
#include "button_item.hpp"
#include <rectojump/global/common.hpp>
#include <rectojump/global/config_settings.hpp>
#include <rectojump/shared/level_manager/level_manager.hpp>
#include <rectojump/ui/connected_buttons.hpp>
namespace rj
{
template<typename Editor>
class settingsbar
{
Editor& m_editor;
typename Editor::gh_type& m_gamehandler;
rndr& m_render;
// interface
sf::RectangleShape m_shape;
ui::connected_buttons m_buttons;
ui::button m_toggle_bar_button{{16.f, 16.f}, {16.f, 16.f}};
sf::Texture m_toggle_bar_button_tx;
sf::Font m_font;
// moving
bool m_is_expanded{true}, m_moving{false}, m_need_move_right{false}, m_need_move_left{false};
float m_moved{0.f};
float m_max_move{m_shape.getSize().x - 32.f};
static constexpr float m_move_step{1.f};
public:
settingsbar(Editor& e, const vec2f& size) :
m_editor{e},
m_gamehandler{e.get_gamehandler()},
m_render{m_gamehandler.get_render()},
m_shape{size},
m_toggle_bar_button_tx{m_gamehandler.get_datamgr().template get_as<sf::Texture>("arrow.png")},
m_font{m_gamehandler.get_datamgr().template get_as<sf::Font>("Fipps-Regular.otf")}
{this->init();}
~settingsbar()
{settings::set_editor_settings_expanded(m_is_expanded);}
void update(dur duration)
{
m_buttons.update(duration);
m_toggle_bar_button.update(duration);
if(m_toggle_bar_button.is_pressed() && !m_moving)
{
m_moved = 0.f;
flip_h(m_toggle_bar_button);
if(m_is_expanded) m_need_move_right = true;
else m_need_move_left = true;
}
if(m_need_move_right)
{
if(m_moved > m_max_move)
{
m_moving = false;
m_need_move_right = false;
m_is_expanded = false;
return;
}
m_moving = true;
auto move_offset(vec2f{m_move_step, 0.f} * duration);
this->move(move_offset);
m_moved += move_offset.x;
}
if(m_need_move_left)
{
if(m_moved > m_max_move)
{
m_moving = false;
m_need_move_left = false;
m_is_expanded = true;
return;
}
m_moving = true;
auto move_offset(vec2f{-m_move_step, 0.f} * duration);
this->move(move_offset);
m_moved += -move_offset.x;
}
}
void render()
{
m_render(m_shape, m_toggle_bar_button, m_buttons);
}
auto get_bounds() const noexcept
-> decltype(m_shape.getGlobalBounds())
{return m_shape.getGlobalBounds();}
const vec2f& get_size() const noexcept
{return m_shape.getSize();}
private:
void init()
{
// shape
auto& shape_size(m_shape.getSize());
m_shape.setOrigin(shape_size / 2.f);
m_shape.setPosition(shape_size / 2.f);
m_shape.setFillColor(settings::get_color_default_light());
// toggle (expand) settings bar
m_toggle_bar_button.set_origin(m_toggle_bar_button.get_size() / 2.f);
m_toggle_bar_button.set_texture(&m_toggle_bar_button_tx);
if(settings::get_editor_settings_expanded())
flip_h(m_toggle_bar_button);
else m_need_move_right = true;
// buttons
vec2f btn_size{80.f, 40.f};
auto save_btn(m_buttons.add_button_event<button_item>(
[this]{m_editor.handle_save();}, btn_size, vec2f{shape_size.x / 2.f - 60.f, shape_size.y - btn_size.y}));
save_btn->set_origin(btn_size / 2.f);
save_btn->set_font(m_font);
save_btn->set_fontsize(16);
save_btn->set_text("Save");
save_btn->set_fontcolor(settings::get_color_light());
auto load_btn(m_buttons.add_button_event<button_item>(
[this]{m_editor.handle_load();}, btn_size, vec2f{shape_size.x / 2.f + 60.f, shape_size.y - btn_size.y}));
load_btn->set_origin(btn_size / 2.f);
load_btn->set_font(m_font);
load_btn->set_fontsize(16);
load_btn->set_text("Load");
load_btn->set_fontcolor(settings::get_color_light());
}
void move(const vec2f& offset) noexcept
{
m_shape.move(offset);
m_toggle_bar_button.move(offset);
for(auto& a : m_buttons.get_buttons())
a.second.button->move(offset);
}
};
}
#endif // RJ_GAME_EDITOR_SETTINGSBAR_HPP
<|endoftext|> |
<commit_before><commit_msg>newly set nStart and nEnd are not used<commit_after><|endoftext|> |
<commit_before>/* -*- c++ -*-
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
c2ffi 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <clang/Lex/Token.h>
#include <clang/Lex/MacroInfo.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/LiteralSupport.h>
#include <set>
#include <string>
#include <sstream>
#include <map>
#include "c2ffi.h"
#include "c2ffi/macros.h"
typedef std::set<std::string> StringSet;
typedef std::map<std::string, std::string> RedefMap;
enum best_guess {
tok_invalid = 0,
tok_ok = 1,
tok_int,
tok_float,
tok_string
};
static best_guess macro_type(clang::Preprocessor &pp,
const char *macro_name,
const clang::MacroInfo *mi,
StringSet *seen = NULL);
static best_guess num_type(clang::Preprocessor &pp,
const clang::Token &t) {
llvm::StringRef sr(t.getLiteralData(), t.getLength());
clang::NumericLiteralParser parser(sr, t.getLocation(), pp);
if(parser.isIntegerLiteral())
return tok_int;
if(parser.isFloatingLiteral())
return tok_float;
return tok_invalid;
}
static best_guess tok_type(clang::Preprocessor &pp, const char *macro_name,
const clang::Token &t, StringSet *seen) {
using namespace clang;
tok::TokenKind k = t.getKind();
if(k == tok::identifier) {
return tok_ok;
IdentifierInfo *ii = t.getIdentifierInfo();
if(ii && !seen->count(ii->getNameStart()))
return macro_type(pp, ii->getNameStart(),
pp.getMacroInfo(ii), seen);
return tok_invalid;
}
if (k == tok::l_paren || k == tok::r_paren || k == tok::amp || k == tok::plus ||
k == tok::star || k == tok::minus || k == tok::tilde || k == tok::slash ||
k == tok::percent || k == tok::lessless || k == tok::greatergreater ||
k == tok::caret || k == tok::pipe)
return tok_ok;
return tok_invalid;
}
static best_guess macro_type(clang::Preprocessor &pp, const char *macro_name,
const clang::MacroInfo *mi, StringSet *seen) {
if(!mi) return tok_invalid;
best_guess result = tok_invalid, guess = tok_invalid;
bool owns_seen = (seen == NULL);
if(owns_seen) seen = new StringSet;
seen->insert(macro_name);
for(clang::MacroInfo::tokens_iterator j = mi->tokens_begin();
j != mi->tokens_end(); j++) {
const clang::Token &t = (*j);
if(t.isLiteral()) {
if(t.getKind() == clang::tok::numeric_constant)
guess = num_type(pp, t);
else if(t.getKind() == clang::tok::string_literal)
guess = tok_string;
else {
result = tok_invalid;
goto end;
}
if(guess > result) result = guess;
} else {
guess = tok_type(pp, macro_name, t, seen);
if(guess == tok_invalid) goto end;
if(guess > result) result = guess;
}
}
end:
if(owns_seen) delete seen;
// Not much good if we don't know a type
if(result <= tok_ok)
return tok_invalid;
return result;
}
static std::string macro_to_string(const clang::Preprocessor &pp,
const clang::MacroInfo *mi) {
std::stringstream ss;
for(clang::MacroInfo::tokens_iterator j = mi->tokens_begin();
j != mi->tokens_end(); j++) {
const clang::Token &t = (*j);
ss << pp.getSpelling(t);
}
return ss.str();
}
static void
output_redef(clang::Preprocessor &pp, const char *name, const clang::MacroInfo *mi,
const best_guess type, std::ostream &os) {
using namespace c2ffi;
os << "const ";
switch(type) {
case tok_int: os << "__int128_t"; break;
case tok_float: os << "double"; break;
case tok_string:
default:
os << "char*"; break;
}
os << " __c2ffi_" << name << " = " << name << ";" << std::endl;
}
void c2ffi::process_macros(clang::CompilerInstance &ci, std::ostream &os) {
using namespace c2ffi;
clang::SourceManager &sm = ci.getSourceManager();
clang::Preprocessor &pp = ci.getPreprocessor();
for(clang::Preprocessor::macro_iterator i = pp.macro_begin();
i != pp.macro_end(); i++) {
const clang::MacroInfo *mi = (*i).second->getInfo();
const clang::SourceLocation sl = mi->getDefinitionLoc();
std::string loc = sl.printToString(sm);
const char *name = (*i).first->getNameStart();
if(mi->isBuiltinMacro() || loc.substr(0,10) == "<built-in>") {
} else if(mi->isFunctionLike()) {
} else if(best_guess type = macro_type(pp, name, mi)) {
os << "/* " << loc << " */" << std::endl;
os << "#define " << name << " "
<< macro_to_string(pp, mi)
<< std::endl << std::endl;
}
}
for(clang::Preprocessor::macro_iterator i = pp.macro_begin();
i != pp.macro_end(); i++) {
clang::MacroInfo *mi = (*i).second->getInfo();
clang::SourceLocation sl = mi->getDefinitionLoc();
std::string loc = sl.printToString(sm);
const char *name = (*i).first->getNameStart();
if(mi->isBuiltinMacro() || loc.substr(0,10) == "<built-in>") {
} else if(mi->isFunctionLike()) {
} else if(best_guess type = macro_type(pp, name, mi)) {
output_redef(pp, name, mi, type, os);
}
}
}
<commit_msg>Update for llvm@178146<commit_after>/* -*- c++ -*-
c2ffi
Copyright (C) 2013 Ryan Pavlik
This file is part of c2ffi.
c2ffi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
c2ffi 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with c2ffi. If not, see <http://www.gnu.org/licenses/>.
*/
#include <clang/Lex/Token.h>
#include <clang/Lex/MacroInfo.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/LiteralSupport.h>
#include <set>
#include <string>
#include <sstream>
#include <map>
#include "c2ffi.h"
#include "c2ffi/macros.h"
typedef std::set<std::string> StringSet;
typedef std::map<std::string, std::string> RedefMap;
enum best_guess {
tok_invalid = 0,
tok_ok = 1,
tok_int,
tok_float,
tok_string
};
static best_guess macro_type(clang::Preprocessor &pp,
const char *macro_name,
const clang::MacroInfo *mi,
StringSet *seen = NULL);
static best_guess num_type(clang::Preprocessor &pp,
const clang::Token &t) {
llvm::StringRef sr(t.getLiteralData(), t.getLength());
clang::NumericLiteralParser parser(sr, t.getLocation(), pp);
if(parser.isIntegerLiteral())
return tok_int;
if(parser.isFloatingLiteral())
return tok_float;
return tok_invalid;
}
static best_guess tok_type(clang::Preprocessor &pp, const char *macro_name,
const clang::Token &t, StringSet *seen) {
using namespace clang;
tok::TokenKind k = t.getKind();
if(k == tok::identifier) {
return tok_ok;
IdentifierInfo *ii = t.getIdentifierInfo();
if(ii && !seen->count(ii->getNameStart()))
return macro_type(pp, ii->getNameStart(),
pp.getMacroInfo(ii), seen);
return tok_invalid;
}
if (k == tok::l_paren || k == tok::r_paren || k == tok::amp || k == tok::plus ||
k == tok::star || k == tok::minus || k == tok::tilde || k == tok::slash ||
k == tok::percent || k == tok::lessless || k == tok::greatergreater ||
k == tok::caret || k == tok::pipe)
return tok_ok;
return tok_invalid;
}
static best_guess macro_type(clang::Preprocessor &pp, const char *macro_name,
const clang::MacroInfo *mi, StringSet *seen) {
if(!mi) return tok_invalid;
best_guess result = tok_invalid, guess = tok_invalid;
bool owns_seen = (seen == NULL);
if(owns_seen) seen = new StringSet;
seen->insert(macro_name);
for(clang::MacroInfo::tokens_iterator j = mi->tokens_begin();
j != mi->tokens_end(); j++) {
const clang::Token &t = (*j);
if(t.isLiteral()) {
if(t.getKind() == clang::tok::numeric_constant)
guess = num_type(pp, t);
else if(t.getKind() == clang::tok::string_literal)
guess = tok_string;
else {
result = tok_invalid;
goto end;
}
if(guess > result) result = guess;
} else {
guess = tok_type(pp, macro_name, t, seen);
if(guess == tok_invalid) goto end;
if(guess > result) result = guess;
}
}
end:
if(owns_seen) delete seen;
// Not much good if we don't know a type
if(result <= tok_ok)
return tok_invalid;
return result;
}
static std::string macro_to_string(const clang::Preprocessor &pp,
const clang::MacroInfo *mi) {
std::stringstream ss;
for(clang::MacroInfo::tokens_iterator j = mi->tokens_begin();
j != mi->tokens_end(); j++) {
const clang::Token &t = (*j);
ss << pp.getSpelling(t);
}
return ss.str();
}
static void
output_redef(clang::Preprocessor &pp, const char *name, const clang::MacroInfo *mi,
const best_guess type, std::ostream &os) {
using namespace c2ffi;
os << "const ";
switch(type) {
case tok_int: os << "__int128_t"; break;
case tok_float: os << "double"; break;
case tok_string:
default:
os << "char*"; break;
}
os << " __c2ffi_" << name << " = " << name << ";" << std::endl;
}
void c2ffi::process_macros(clang::CompilerInstance &ci, std::ostream &os) {
using namespace c2ffi;
clang::SourceManager &sm = ci.getSourceManager();
clang::Preprocessor &pp = ci.getPreprocessor();
for(clang::Preprocessor::macro_iterator i = pp.macro_begin();
i != pp.macro_end(); i++) {
const clang::MacroInfo *mi = (*i).second->getMacroInfo();
const clang::SourceLocation sl = mi->getDefinitionLoc();
std::string loc = sl.printToString(sm);
const char *name = (*i).first->getNameStart();
if(mi->isBuiltinMacro() || loc.substr(0,10) == "<built-in>") {
} else if(mi->isFunctionLike()) {
} else if(best_guess type = macro_type(pp, name, mi)) {
os << "/* " << loc << " */" << std::endl;
os << "#define " << name << " "
<< macro_to_string(pp, mi)
<< std::endl << std::endl;
}
}
for(clang::Preprocessor::macro_iterator i = pp.macro_begin();
i != pp.macro_end(); i++) {
clang::MacroInfo *mi = (*i).second->getMacroInfo();
clang::SourceLocation sl = mi->getDefinitionLoc();
std::string loc = sl.printToString(sm);
const char *name = (*i).first->getNameStart();
if(mi->isBuiltinMacro() || loc.substr(0,10) == "<built-in>") {
} else if(mi->isFunctionLike()) {
} else if(best_guess type = macro_type(pp, name, mi)) {
output_redef(pp, name, mi, type, os);
}
}
}
<|endoftext|> |
<commit_before>
#ifdef _WIN32
#include <windows.h>
#else
#include <cstdio>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <nstd/File.h>
#include <nstd/Debug.h>
File::File()
{
#ifdef _WIN32
ASSERT(sizeof(void*) >= sizeof(HANDLE));
fp = INVALID_HANDLE_VALUE;
#else
fp = 0;
#endif
}
File::~File()
{
close();
}
void_t File::close()
{
#ifdef _WIN32
if(fp != INVALID_HANDLE_VALUE)
{
CloseHandle((HANDLE)fp);
fp = INVALID_HANDLE_VALUE;
}
#else
if(fp)
{
fclose((FILE*)fp);
fp = 0;
}
#endif
}
bool_t File::unlink(const String& file)
{
#ifdef _WIN32
if(!DeleteFile(file))
return false;
#else
if(::unlink(file) != 0)
return false;
#endif
return true;
}
bool_t File::open(const String& file, uint_t flags)
{
#ifdef _WIN32
if(fp != INVALID_HANDLE_VALUE)
{
SetLastError(ERROR_INVALID_HANDLE);
return false;
}
DWORD desiredAccess = 0, creationDisposition = 0;
if(flags & writeFlag)
{
desiredAccess |= GENERIC_WRITE;
creationDisposition |= CREATE_ALWAYS;
}
if(flags & readFlag)
{
desiredAccess |= GENERIC_READ;
if(!(flags & writeFlag))
creationDisposition |= OPEN_EXISTING;
}
fp = CreateFile(file, desiredAccess, FILE_SHARE_READ, NULL, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
if(fp == INVALID_HANDLE_VALUE)
return false;
#else
if(fp)
return false;
const char_t* mode = (flags & (writeFlag | readFlag)) == (writeFlag | readFlag) ? "w+" : (flags & writeFlag ? "w" : "r");
fp = fopen(file, mode); // TODO: do not use fopen api
if(!fp)
return false;
#endif
return true;
}
uint_t File::read(void_t* buffer, uint_t len)
{
#ifdef _WIN32
DWORD i;
if(!ReadFile((HANDLE)fp, buffer, len, &i, NULL))
return 0;
return i;
#else
size_t i = fread(buffer, 1, len, (FILE*)fp);
if(i == 0)
return 0;
return (int_t)i;
#endif
}
uint_t File::write(const void_t* buffer, uint_t len)
{
#ifdef _WIN32
DWORD i;
if(!WriteFile((HANDLE)fp, buffer, len, &i, NULL))
return 0;
return i;
#else
size_t i = fwrite(buffer, 1, len, (FILE*)fp);
return (int_t)i;
#endif
}
bool_t File::write(const String& data)
{
size_t size = data.length() * sizeof(tchar_t);
return write(data, (uint_t)size) == (uint_t)size;
}
String File::dirname(const String& file)
{
const tchar_t* start = file;
const tchar_t* pos = &start[file.length() - 1];
for(; pos >= start; --pos)
if(*pos == _T('\\') || *pos == _T('/'))
return file.substr(0, (int_t)(pos - start));
return String(_T("."));
}
String File::basename(const String& file, const String& extension)
{
const tchar_t* start = file;
size_t fileLen = file.length();
const tchar_t* pos = &start[fileLen - 1];
const tchar_t* result;
for(; pos >= start; --pos)
if(*pos == _T('\\') || *pos == _T('/'))
{
result = pos + 1;
goto removeExtension;
}
result = start;
removeExtension:
size_t resultLen = fileLen - (size_t)(result - start);
size_t extensionLen = extension.length();
if(extensionLen)
{
const tchar_t* extensionPtr = extension;
if(*extensionPtr == _T('.'))
{
if(resultLen >= extensionLen)
if(String::compare((const tchar_t*)result + resultLen - extensionLen, extensionPtr) == 0)
return String(result, resultLen - extensionLen);
}
else
{
size_t extensionLenPlus1 = extensionLen + 1;
if(resultLen >= extensionLenPlus1 && result[resultLen - extensionLenPlus1] == _T('.'))
if(String::compare((const tchar_t*)result + resultLen - extensionLen, extensionPtr) == 0)
return String(result, resultLen - extensionLenPlus1);
}
}
return String(result, resultLen);
}
String File::extension(const String& file)
{
const tchar_t* start = file;
size_t fileLen = file.length();
const tchar_t* pos = &start[fileLen - 1];
for(; pos >= start; --pos)
if(*pos == _T('.'))
return String(pos + 1, fileLen - ((size_t)(pos - start) + 1));
else if(*pos == _T('\\') || *pos == _T('/'))
return String();
return String();
}
String File::simplifyPath(const String& path)
{
String result(path.length());
const tchar_t* data = path;
const tchar_t* start = data;
const tchar_t* end;
const tchar_t* chunck;
size_t chunckLen;
bool_t startsWithSlash = *data == _T('/') || *data == _T('\\');
for(;;)
{
while(*start && (*start == _T('/') || *start == _T('\\')))
++start;
end = start;
while(*end && *end != _T('/') && *end != _T('\\'))
++end;
if(end == start)
break;
chunck = start;
chunckLen = (size_t)(end - start);
if(chunckLen == 2 && *chunck == _T('.') && chunck[1] == _T('.') && !result.isEmpty())
{
const tchar_t* data = result;
const tchar_t* pos = data + result.length() - 1;
for(;; --pos)
if(pos < data || *pos == _T('/') || *pos == _T('\\'))
{
if(String::compare(pos + 1, _T("..")) != 0)
{
if(pos < data)
result.resize(0);
else
result.resize((size_t)(pos - data));
goto cont;
}
break;
}
}
else if(chunckLen == 1 && *chunck == _T('.'))
goto cont;
if(!result.isEmpty() || startsWithSlash)
result.append(_T('/'));
result.append(chunck, chunckLen);
cont:
if(!*end)
break;
start = end + 1;
}
return result;
}
bool_t File::isAbsolutePath(const String& path)
{
const tchar_t* data = path;
return *data == _T('/') || *data == _T('\\') || (path.length() > 2 && data[1] == _T(':') && (data[2] == _T('/') || data[2] == _T('\\')));
}
bool_t times(const String& file, File::Times& times)
{
#ifdef _WIN32
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(file, &wfd); // TODO: use another function for this ?
if(hFind == INVALID_HANDLE_VALUE)
return false;
ASSERT(sizeof(DWORD) == 4);
// TODO: add
times.writeTime = ((timestamp_t)wfd.ftLastWriteTime.dwHighDateTime << 32LL | (timestamp_t)wfd.ftLastWriteTime.dwLowDateTime) / 10000LL - 11644473600LL;
times.accessTime = ((timestamp_t)wfd.ftLastAccessTime.dwHighDateTime << 32LL | (timestamp_t)wfd.ftLastAccessTime.dwLowDateTime) / 10000LL - 11644473600LL;
times.creationTime = ((timestamp_t)wfd.ftCreationTime.dwHighDateTime << 32LL | (timestamp_t)wfd.ftCreationTime.dwLowDateTime) / 10000LL - 11644473600LL;
FindClose(hFind);
return true;
#else
struct stat buf;
if(stat(file, &buf) != 0)
return false;
times.writeTime = ((long long)buf.st_mtim.tv_sec) * 1000LL + ((long long)buf.st_mtim.tv_nsec) / 1000000LL;
times.accessTime = ((long long)buf.st_atim.tv_sec) * 1000LL + ((long long)buf.st_atim.tv_nsec) / 1000000LL;
times.creationTime = ((long long)buf.st_ctim.tv_sec) * 1000LL + ((long long)buf.st_ctim.tv_nsec) / 1000000LL;
return true;
#endif
}
bool_t File::exists(const String& file)
{
#ifdef _WIN32
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(file, &wfd); // TODO: use GetFileAttribute ?
if(hFind == INVALID_HANDLE_VALUE) // I guess GetFileAttribute does not work on network drives. But it will produce
return false; // an error code that can be used to fall back to another implementation.
FindClose(hFind);
return true;
#else
struct stat buf;
if(lstat(file, &buf) != 0)
return false;
return true;
#endif
}
<commit_msg>File: Replace fopen/fclose with open/close<commit_after>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <nstd/File.h>
#include <nstd/Debug.h>
File::File()
{
#ifdef _WIN32
ASSERT(sizeof(void*) >= sizeof(HANDLE));
fp = INVALID_HANDLE_VALUE;
#else
fp = 0;
#endif
}
File::~File()
{
close();
}
void_t File::close()
{
#ifdef _WIN32
if(fp != INVALID_HANDLE_VALUE)
{
CloseHandle((HANDLE)fp);
fp = INVALID_HANDLE_VALUE;
}
#else
if(fp)
{
::close((int_t)fp);
fp = 0;
}
#endif
}
bool_t File::unlink(const String& file)
{
#ifdef _WIN32
if(!DeleteFile(file))
return false;
#else
if(::unlink(file) != 0)
return false;
#endif
return true;
}
bool_t File::open(const String& file, uint_t flags)
{
#ifdef _WIN32
if(fp != INVALID_HANDLE_VALUE)
{
SetLastError(ERROR_INVALID_HANDLE);
return false;
}
DWORD desiredAccess = 0, creationDisposition = 0;
if(flags & writeFlag)
{
desiredAccess |= GENERIC_WRITE;
creationDisposition |= CREATE_ALWAYS;
}
if(flags & readFlag)
{
desiredAccess |= GENERIC_READ;
if(!(flags & writeFlag))
creationDisposition |= OPEN_EXISTING;
}
fp = CreateFile(file, desiredAccess, FILE_SHARE_READ, NULL, creationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
if(fp == INVALID_HANDLE_VALUE)
return false;
#else
if(fp)
return false;
int_t oflags;
if((flags & (readFlag | writeFlag)) == (readFlag | writeFlag))
oflags = O_CREAT | O_RDWR; // create if not exists, rw mode
else if(flags & writeFlag)
oflags = O_CREAT | O_TRUNC | O_WRONLY; // create if not exists, truncate if exist, write mode
else
oflags = O_RDONLY; // do not create if not exists, read mode
fp = (void_t*)::open(file, oflags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if((int_t)fp == -1)
{
fp = 0;
return false;
}
#endif
return true;
}
uint_t File::read(void_t* buffer, uint_t len)
{
#ifdef _WIN32
DWORD i;
if(!ReadFile((HANDLE)fp, buffer, len, &i, NULL))
return 0;
return i;
#else
ssize_t i = ::read((int_t)fp, buffer, len);
if(i == -1)
return 0;
return (int_t)i;
#endif
}
uint_t File::write(const void_t* buffer, uint_t len)
{
#ifdef _WIN32
DWORD i;
if(!WriteFile((HANDLE)fp, buffer, len, &i, NULL))
return 0;
return i;
#else
ssize_t i = ::write((int_t)fp, buffer, len);
if(i == -1)
return 0;
return (int_t)i;
#endif
}
bool_t File::write(const String& data)
{
size_t size = data.length() * sizeof(tchar_t);
return write(data, (uint_t)size) == (uint_t)size;
}
String File::dirname(const String& file)
{
const tchar_t* start = file;
const tchar_t* pos = &start[file.length() - 1];
for(; pos >= start; --pos)
if(*pos == _T('\\') || *pos == _T('/'))
return file.substr(0, (int_t)(pos - start));
return String(_T("."));
}
String File::basename(const String& file, const String& extension)
{
const tchar_t* start = file;
size_t fileLen = file.length();
const tchar_t* pos = &start[fileLen - 1];
const tchar_t* result;
for(; pos >= start; --pos)
if(*pos == _T('\\') || *pos == _T('/'))
{
result = pos + 1;
goto removeExtension;
}
result = start;
removeExtension:
size_t resultLen = fileLen - (size_t)(result - start);
size_t extensionLen = extension.length();
if(extensionLen)
{
const tchar_t* extensionPtr = extension;
if(*extensionPtr == _T('.'))
{
if(resultLen >= extensionLen)
if(String::compare((const tchar_t*)result + resultLen - extensionLen, extensionPtr) == 0)
return String(result, resultLen - extensionLen);
}
else
{
size_t extensionLenPlus1 = extensionLen + 1;
if(resultLen >= extensionLenPlus1 && result[resultLen - extensionLenPlus1] == _T('.'))
if(String::compare((const tchar_t*)result + resultLen - extensionLen, extensionPtr) == 0)
return String(result, resultLen - extensionLenPlus1);
}
}
return String(result, resultLen);
}
String File::extension(const String& file)
{
const tchar_t* start = file;
size_t fileLen = file.length();
const tchar_t* pos = &start[fileLen - 1];
for(; pos >= start; --pos)
if(*pos == _T('.'))
return String(pos + 1, fileLen - ((size_t)(pos - start) + 1));
else if(*pos == _T('\\') || *pos == _T('/'))
return String();
return String();
}
String File::simplifyPath(const String& path)
{
String result(path.length());
const tchar_t* data = path;
const tchar_t* start = data;
const tchar_t* end;
const tchar_t* chunck;
size_t chunckLen;
bool_t startsWithSlash = *data == _T('/') || *data == _T('\\');
for(;;)
{
while(*start && (*start == _T('/') || *start == _T('\\')))
++start;
end = start;
while(*end && *end != _T('/') && *end != _T('\\'))
++end;
if(end == start)
break;
chunck = start;
chunckLen = (size_t)(end - start);
if(chunckLen == 2 && *chunck == _T('.') && chunck[1] == _T('.') && !result.isEmpty())
{
const tchar_t* data = result;
const tchar_t* pos = data + result.length() - 1;
for(;; --pos)
if(pos < data || *pos == _T('/') || *pos == _T('\\'))
{
if(String::compare(pos + 1, _T("..")) != 0)
{
if(pos < data)
result.resize(0);
else
result.resize((size_t)(pos - data));
goto cont;
}
break;
}
}
else if(chunckLen == 1 && *chunck == _T('.'))
goto cont;
if(!result.isEmpty() || startsWithSlash)
result.append(_T('/'));
result.append(chunck, chunckLen);
cont:
if(!*end)
break;
start = end + 1;
}
return result;
}
bool_t File::isAbsolutePath(const String& path)
{
const tchar_t* data = path;
return *data == _T('/') || *data == _T('\\') || (path.length() > 2 && data[1] == _T(':') && (data[2] == _T('/') || data[2] == _T('\\')));
}
bool_t times(const String& file, File::Times& times)
{
#ifdef _WIN32
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(file, &wfd); // TODO: use another function for this ?
if(hFind == INVALID_HANDLE_VALUE)
return false;
ASSERT(sizeof(DWORD) == 4);
// TODO: add
times.writeTime = ((timestamp_t)wfd.ftLastWriteTime.dwHighDateTime << 32LL | (timestamp_t)wfd.ftLastWriteTime.dwLowDateTime) / 10000LL - 11644473600LL;
times.accessTime = ((timestamp_t)wfd.ftLastAccessTime.dwHighDateTime << 32LL | (timestamp_t)wfd.ftLastAccessTime.dwLowDateTime) / 10000LL - 11644473600LL;
times.creationTime = ((timestamp_t)wfd.ftCreationTime.dwHighDateTime << 32LL | (timestamp_t)wfd.ftCreationTime.dwLowDateTime) / 10000LL - 11644473600LL;
FindClose(hFind);
return true;
#else
struct stat buf;
if(stat(file, &buf) != 0)
return false;
times.writeTime = ((long long)buf.st_mtim.tv_sec) * 1000LL + ((long long)buf.st_mtim.tv_nsec) / 1000000LL;
times.accessTime = ((long long)buf.st_atim.tv_sec) * 1000LL + ((long long)buf.st_atim.tv_nsec) / 1000000LL;
times.creationTime = ((long long)buf.st_ctim.tv_sec) * 1000LL + ((long long)buf.st_ctim.tv_nsec) / 1000000LL;
return true;
#endif
}
bool_t File::exists(const String& file)
{
#ifdef _WIN32
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(file, &wfd); // TODO: use GetFileAttribute ?
if(hFind == INVALID_HANDLE_VALUE) // I guess GetFileAttribute does not work on network drives. But it will produce
return false; // an error code that can be used to fall back to another implementation.
FindClose(hFind);
return true;
#else
struct stat buf;
if(lstat(file, &buf) != 0)
return false;
return true;
#endif
}
<|endoftext|> |
<commit_before>// @(#)root/base:$Name: $:$Id: TQConnection.cxx,v 1.9 2002/12/02 18:50:01 rdm Exp $
// Author: Valeriy Onuchin & Fons Rademakers 15/10/2000
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TQConnection class is an internal class, used in the object //
// communication mechanism. //
// //
// TQConnection: //
// - is a list of signal_lists containing pointers //
// to this connection //
// - receiver is the object to which slot-method is applied //
// //
// This implementation is provided by //
// Valeriy Onuchin (onuchin@sirius.ihep.su). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TQConnection.h"
#include "TRefCnt.h"
#include "TClass.h"
#include "Api.h"
#include "G__ci.h"
#include "Riostream.h"
ClassImpQ(TQConnection)
char *gTQSlotParams; // used to pass string parameter
//////////////////////////////////////////////////////////////////////////
// //
// TQSlot = slightly modified TMethodCall class //
// used in the object communication mechanism //
// //
//////////////////////////////////////////////////////////////////////////
class TQSlot : public TObject, public TRefCnt {
protected:
G__CallFunc *fFunc; // CINT method invocation environment
Long_t fOffset; // offset added to object pointer
TString fName; // full name of method
Int_t fExecuting; // true if one of this slot's ExecuteMethod methods is being called
public:
TQSlot(TClass *cl, const char *method, const char *funcname);
TQSlot(const char *class_name, const char *funcname);
virtual ~TQSlot();
const char *GetName() const { return fName.Data(); }
void ExecuteMethod(void *object);
void ExecuteMethod(void *object, Long_t param);
void ExecuteMethod(void *object, Double_t param);
void ExecuteMethod(void *object, const char *params);
void ExecuteMethod(void *object, Long_t *paramArr);
void Print(Option_t *opt= "") const;
void ls(Option_t *opt= "") const { Print(opt); }
};
//______________________________________________________________________________
TQSlot::TQSlot(TClass *cl, const char *method_name,
const char *funcname) : TObject(), TRefCnt()
{
// Create the method invocation environment. Necessary input
// information: the class, full method name with prototype
// string of the form: method(char*,int,float).
// To initialize class method with default arguments, method
// string with default parameters should be of the form:
// method(=\"ABC\",1234,3.14) (!! parameter string should
// consists of '=').
// To execute the method call TQSlot::ExecuteMethod(object,...).
fFunc = 0;
fOffset = 0;
fName = "";
fExecuting = 0;
// cl==0, is the case of interpreted function.
fName = method_name;
char *method = new char[strlen(method_name)+1];
if (method) strcpy(method, method_name);
char *proto;
char *tmp;
char *params = 0;
// separate method and protoype strings
if ((proto = strchr(method,'('))) {
// substitute first '(' symbol with '\0'
*proto++ = '\0';
// last ')' symbol with '\0'
if ((tmp = strrchr(proto,')'))) *tmp = '\0';
if ((params = strchr(proto,'='))) *params = ' ';
}
fFunc = new G__CallFunc;
// initiate class method (function) with proto
// or with default params
if (cl) {
params ?
fFunc->SetFunc(cl->GetClassInfo(), method, params, &fOffset) :
fFunc->SetFuncProto(cl->GetClassInfo(), method, proto, &fOffset);
} else {
G__ClassInfo gcl;
params ?
fFunc->SetFunc(&gcl, (char*)funcname, params, &fOffset) :
fFunc->SetFuncProto(&gcl, (char*)funcname, proto, &fOffset);
}
// cleaning
delete [] method;
}
//______________________________________________________________________________
TQSlot::TQSlot(const char *class_name, const char *funcname) :
TObject(), TRefCnt()
{
// Create the method invocation environment. Necessary input
// information: the name of class (could be interpreted class),
// full method name with prototype or parameter string
// of the form: method(char*,int,float).
// To initialize class method with default arguments, method
// string with default parameters should be of the form:
// method(=\"ABC\",1234,3.14) (!! parameter string should
// consists of '=').
// To execute the method call TQSlot::ExecuteMethod(object,...).
fFunc = 0;
fOffset = 0;
fName = funcname;
fExecuting = 0;
char *method = new char[strlen(funcname)+1];
if (method) strcpy(method, funcname);
char *proto;
char *tmp;
char *params = 0;
// separate method and protoype strings
if ((proto = strchr(method,'('))) {
*proto++ = '\0';
if ((tmp = strrchr(proto,')'))) *tmp = '\0';
if ((params = strchr(proto,'='))) *params = ' ';
}
fFunc = new G__CallFunc;
G__ClassInfo gcl;
if (!class_name)
; // function
else
gcl.Init(class_name); // class
if (params)
fFunc->SetFunc(&gcl, method, params, &fOffset);
else
fFunc->SetFuncProto(&gcl, method, proto , &fOffset);
delete [] method;
return;
}
//______________________________________________________________________________
TQSlot::~TQSlot()
{
// TQSlot dtor.
// don't delete executing environment of a slot that is being executed
if (!fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object)
{
// ExecuteMethod the method (with preset arguments) for
// the specified object.
void *address = 0;
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, Long_t param)
{
// ExecuteMethod the method for the specified object and
// with single argument value.
void *address = 0;
fFunc->ResetArg();
fFunc->SetArg(param);
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, Double_t param)
{
// ExecuteMethod the method for the specified object and
// with single argument value.
void *address = 0;
fFunc->ResetArg();
fFunc->SetArg(param);
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, const char *param)
{
// ExecuteMethod the method for the specified object and text param.
void *address = 0;
gTQSlotParams = (char*)param;
fFunc->SetArgs("gTQSlotParams");
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, Long_t *paramArr)
{
// ExecuteMethod the method for the specified object and with
// several argument values.
// paramArr is an array containing the addresses
// where to take the function parameters.
// At least as many pointers should be present in the array as
// there are required arguments (all arguments - default args).
void *address = 0;
fFunc->SetArgArray(paramArr);
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
void TQSlot::Print(Option_t *) const
{
// Print info about slot.
cout <<IsA()->GetName() << "\t" << GetName() << "\t"
<< "Number of Connections = " << References() << endl;
}
//______________________________________________________________________________
TQConnection::TQConnection() : TList(), TQObject()
{
// Default constructor.
fReceiver = 0;
fSlot = 0;
}
//______________________________________________________________________________
TQConnection::TQConnection(TClass *cl, void *receiver, const char *method_name)
: TList(), TQObject()
{
// TQConnection ctor.
// cl != 0 - connection to object == receiver of class == cl
// and method == method_name
// cl == 0 - connection to function with name == method_name
char *funcname = 0;
fReceiver = receiver; // fReceiver is pointer to receiver
if (!cl) {
funcname = G__p2f2funcname(fReceiver);
if (!funcname)
Warning("TQConnection", "%s cannot be compiled", method_name);
}
fSlot = new TQSlot(cl, method_name, funcname);
fSlot->AddReference(); //update counter of references to slot
}
//______________________________________________________________________________
TQConnection::TQConnection(const char *class_name, void *receiver,
const char *funcname) : TList(), TQObject()
{
// TQConnection ctor.
// Creates connection to method of class specified by name,
// it could be interpreted class and with method == funcname.
fSlot = new TQSlot(class_name, funcname); // new slot-method
fSlot->AddReference(); // update counter of references to slot
fReceiver = receiver; // fReceiver is pointer to receiver
}
//______________________________________________________________________________
TQConnection::~TQConnection()
{
// TQConnection dtor.
// - remove this connection from all signal lists
// - we do not delete fSlot if it has other connections,
// TQSlot::fCounter > 0 .
TIter next(this);
register TList *list;
while ((list = (TList*)next())) {
list->Remove(this);
if (list->IsEmpty()) SafeDelete(list); // delete empty list
}
if (!fSlot) return;
fSlot->RemoveReference(); // decrease references to slot
if (fSlot->References() <=0) {
SafeDelete(fSlot);
}
}
//______________________________________________________________________________
const char *TQConnection::GetName() const
{
// Returns name of connection
return fSlot->GetName();
}
//______________________________________________________________________________
void TQConnection::Destroyed()
{
// Signal Destroyed tells that connection is destroyed.
MakeZombie();
Emit("Destroyed()");
}
//______________________________________________________________________________
void TQConnection::ls(Option_t *option) const
{
// List TQConnection full method name and list all signals
// connected to this connection.
cout << "\t" << IsA()->GetName() << "\t" << GetName() << endl;
((TQConnection*)this)->ForEach(TList,ls)(option);
}
//______________________________________________________________________________
void TQConnection::Print(Option_t *) const
{
// Print TQConnection full method name and print all
// signals connected to this connection.
cout << "\t\t\t" << IsA()->GetName() << "\t" << fReceiver <<
"\t" << GetName() << endl;
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod()
{
// Apply slot-method to the fReceiver object without arguments.
fSlot->ExecuteMethod(fReceiver);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(Long_t param)
{
// Apply slot-method to the fReceiver object with
// single argument value.
fSlot->ExecuteMethod(fReceiver, param);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(Double_t param)
{
// Apply slot-method to the fReceiver object with
// single argument value.
fSlot->ExecuteMethod(fReceiver, param);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(Long_t *params)
{
// Apply slot-method to the fReceiver object with variable
// number of argument values.
fSlot->ExecuteMethod(fReceiver, params);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(const char *param)
{
// Apply slot-method to the fReceiver object and
// with string parameter.
fSlot->ExecuteMethod(fReceiver, param);
}
<commit_msg>The class TQConnection uses CINT and is not protected for multi-threading. This patch from Mathieu de Naurois adds R__LOCKGUARD(gCINTMutex) at several places in the code.<commit_after>// @(#)root/base:$Name: $:$Id: TQConnection.cxx,v 1.10 2003/01/20 08:44:46 brun Exp $
// Author: Valeriy Onuchin & Fons Rademakers 15/10/2000
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TQConnection class is an internal class, used in the object //
// communication mechanism. //
// //
// TQConnection: //
// - is a list of signal_lists containing pointers //
// to this connection //
// - receiver is the object to which slot-method is applied //
// //
// This implementation is provided by //
// Valeriy Onuchin (onuchin@sirius.ihep.su). //
// //
//////////////////////////////////////////////////////////////////////////
#include "TQConnection.h"
#include "TRefCnt.h"
#include "TClass.h"
#include "Api.h"
#include "G__ci.h"
#include "Riostream.h"
#include "TVirtualMutex.h"
ClassImpQ(TQConnection)
char *gTQSlotParams; // used to pass string parameter
//////////////////////////////////////////////////////////////////////////
// //
// TQSlot = slightly modified TMethodCall class //
// used in the object communication mechanism //
// //
//////////////////////////////////////////////////////////////////////////
class TQSlot : public TObject, public TRefCnt {
protected:
G__CallFunc *fFunc; // CINT method invocation environment
Long_t fOffset; // offset added to object pointer
TString fName; // full name of method
Int_t fExecuting; // true if one of this slot's ExecuteMethod methods is being called
public:
TQSlot(TClass *cl, const char *method, const char *funcname);
TQSlot(const char *class_name, const char *funcname);
virtual ~TQSlot();
const char *GetName() const { return fName.Data(); }
void ExecuteMethod(void *object);
void ExecuteMethod(void *object, Long_t param);
void ExecuteMethod(void *object, Double_t param);
void ExecuteMethod(void *object, const char *params);
void ExecuteMethod(void *object, Long_t *paramArr);
void Print(Option_t *opt= "") const;
void ls(Option_t *opt= "") const { Print(opt); }
};
//______________________________________________________________________________
TQSlot::TQSlot(TClass *cl, const char *method_name,
const char *funcname) : TObject(), TRefCnt()
{
// Create the method invocation environment. Necessary input
// information: the class, full method name with prototype
// string of the form: method(char*,int,float).
// To initialize class method with default arguments, method
// string with default parameters should be of the form:
// method(=\"ABC\",1234,3.14) (!! parameter string should
// consists of '=').
// To execute the method call TQSlot::ExecuteMethod(object,...).
fFunc = 0;
fOffset = 0;
fName = "";
fExecuting = 0;
// cl==0, is the case of interpreted function.
fName = method_name;
char *method = new char[strlen(method_name)+1];
if (method) strcpy(method, method_name);
char *proto;
char *tmp;
char *params = 0;
// separate method and protoype strings
if ((proto = strchr(method,'('))) {
// substitute first '(' symbol with '\0'
*proto++ = '\0';
// last ')' symbol with '\0'
if ((tmp = strrchr(proto,')'))) *tmp = '\0';
if ((params = strchr(proto,'='))) *params = ' ';
}
R__LOCKGUARD(gCINTMutex);
fFunc = new G__CallFunc;
// initiate class method (function) with proto
// or with default params
if (cl) {
params ?
fFunc->SetFunc(cl->GetClassInfo(), method, params, &fOffset) :
fFunc->SetFuncProto(cl->GetClassInfo(), method, proto, &fOffset);
} else {
G__ClassInfo gcl;
params ?
fFunc->SetFunc(&gcl, (char*)funcname, params, &fOffset) :
fFunc->SetFuncProto(&gcl, (char*)funcname, proto, &fOffset);
}
// cleaning
delete [] method;
}
//______________________________________________________________________________
TQSlot::TQSlot(const char *class_name, const char *funcname) :
TObject(), TRefCnt()
{
// Create the method invocation environment. Necessary input
// information: the name of class (could be interpreted class),
// full method name with prototype or parameter string
// of the form: method(char*,int,float).
// To initialize class method with default arguments, method
// string with default parameters should be of the form:
// method(=\"ABC\",1234,3.14) (!! parameter string should
// consists of '=').
// To execute the method call TQSlot::ExecuteMethod(object,...).
fFunc = 0;
fOffset = 0;
fName = funcname;
fExecuting = 0;
char *method = new char[strlen(funcname)+1];
if (method) strcpy(method, funcname);
char *proto;
char *tmp;
char *params = 0;
// separate method and protoype strings
if ((proto = strchr(method,'('))) {
*proto++ = '\0';
if ((tmp = strrchr(proto,')'))) *tmp = '\0';
if ((params = strchr(proto,'='))) *params = ' ';
}
R__LOCKGUARD(gCINTMutex);
fFunc = new G__CallFunc;
G__ClassInfo gcl;
if (!class_name)
; // function
else
gcl.Init(class_name); // class
if (params)
fFunc->SetFunc(&gcl, method, params, &fOffset);
else
fFunc->SetFuncProto(&gcl, method, proto , &fOffset);
delete [] method;
return;
}
//______________________________________________________________________________
TQSlot::~TQSlot()
{
// TQSlot dtor.
// don't delete executing environment of a slot that is being executed
if (!fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object)
{
// ExecuteMethod the method (with preset arguments) for
// the specified object.
void *address = 0;
if (object) address = (void*)((Long_t)object + fOffset);
R__LOCKGUARD(gCINTMutex);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, Long_t param)
{
// ExecuteMethod the method for the specified object and
// with single argument value.
void *address = 0;
R__LOCKGUARD(gCINTMutex);
fFunc->ResetArg();
fFunc->SetArg(param);
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, Double_t param)
{
// ExecuteMethod the method for the specified object and
// with single argument value.
void *address = 0;
R__LOCKGUARD(gCINTMutex);
fFunc->ResetArg();
fFunc->SetArg(param);
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, const char *param)
{
// ExecuteMethod the method for the specified object and text param.
void *address = 0;
gTQSlotParams = (char*)param;
R__LOCKGUARD(gCINTMutex);
fFunc->SetArgs("gTQSlotParams");
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
inline void TQSlot::ExecuteMethod(void *object, Long_t *paramArr)
{
// ExecuteMethod the method for the specified object and with
// several argument values.
// paramArr is an array containing the addresses
// where to take the function parameters.
// At least as many pointers should be present in the array as
// there are required arguments (all arguments - default args).
void *address = 0;
R__LOCKGUARD(gCINTMutex);
fFunc->SetArgArray(paramArr);
if (object) address = (void*)((Long_t)object + fOffset);
fExecuting++;
fFunc->Exec(address);
fExecuting--;
if (!TestBit(kNotDeleted) && !fExecuting)
delete fFunc;
}
//______________________________________________________________________________
void TQSlot::Print(Option_t *) const
{
// Print info about slot.
cout <<IsA()->GetName() << "\t" << GetName() << "\t"
<< "Number of Connections = " << References() << endl;
}
//______________________________________________________________________________
TQConnection::TQConnection() : TList(), TQObject()
{
// Default constructor.
fReceiver = 0;
fSlot = 0;
}
//______________________________________________________________________________
TQConnection::TQConnection(TClass *cl, void *receiver, const char *method_name)
: TList(), TQObject()
{
// TQConnection ctor.
// cl != 0 - connection to object == receiver of class == cl
// and method == method_name
// cl == 0 - connection to function with name == method_name
char *funcname = 0;
fReceiver = receiver; // fReceiver is pointer to receiver
if (!cl) {
funcname = G__p2f2funcname(fReceiver);
if (!funcname)
Warning("TQConnection", "%s cannot be compiled", method_name);
}
fSlot = new TQSlot(cl, method_name, funcname);
fSlot->AddReference(); //update counter of references to slot
}
//______________________________________________________________________________
TQConnection::TQConnection(const char *class_name, void *receiver,
const char *funcname) : TList(), TQObject()
{
// TQConnection ctor.
// Creates connection to method of class specified by name,
// it could be interpreted class and with method == funcname.
fSlot = new TQSlot(class_name, funcname); // new slot-method
fSlot->AddReference(); // update counter of references to slot
fReceiver = receiver; // fReceiver is pointer to receiver
}
//______________________________________________________________________________
TQConnection::~TQConnection()
{
// TQConnection dtor.
// - remove this connection from all signal lists
// - we do not delete fSlot if it has other connections,
// TQSlot::fCounter > 0 .
TIter next(this);
register TList *list;
while ((list = (TList*)next())) {
list->Remove(this);
if (list->IsEmpty()) SafeDelete(list); // delete empty list
}
if (!fSlot) return;
fSlot->RemoveReference(); // decrease references to slot
if (fSlot->References() <=0) {
SafeDelete(fSlot);
}
}
//______________________________________________________________________________
const char *TQConnection::GetName() const
{
// Returns name of connection
return fSlot->GetName();
}
//______________________________________________________________________________
void TQConnection::Destroyed()
{
// Signal Destroyed tells that connection is destroyed.
MakeZombie();
Emit("Destroyed()");
}
//______________________________________________________________________________
void TQConnection::ls(Option_t *option) const
{
// List TQConnection full method name and list all signals
// connected to this connection.
cout << "\t" << IsA()->GetName() << "\t" << GetName() << endl;
((TQConnection*)this)->ForEach(TList,ls)(option);
}
//______________________________________________________________________________
void TQConnection::Print(Option_t *) const
{
// Print TQConnection full method name and print all
// signals connected to this connection.
cout << "\t\t\t" << IsA()->GetName() << "\t" << fReceiver <<
"\t" << GetName() << endl;
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod()
{
// Apply slot-method to the fReceiver object without arguments.
fSlot->ExecuteMethod(fReceiver);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(Long_t param)
{
// Apply slot-method to the fReceiver object with
// single argument value.
fSlot->ExecuteMethod(fReceiver, param);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(Double_t param)
{
// Apply slot-method to the fReceiver object with
// single argument value.
fSlot->ExecuteMethod(fReceiver, param);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(Long_t *params)
{
// Apply slot-method to the fReceiver object with variable
// number of argument values.
fSlot->ExecuteMethod(fReceiver, params);
}
//______________________________________________________________________________
void TQConnection::ExecuteMethod(const char *param)
{
// Apply slot-method to the fReceiver object and
// with string parameter.
fSlot->ExecuteMethod(fReceiver, param);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Pavlo Lavrenenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Game.h"
#include "Logger.h"
#include "Vec3.h"
#include "ResourceManager.h"
#include <sstream>
#include <iomanip>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <fontconfig/fontconfig.h>
namespace PolandBall {
int Game::exec() {
if (!this->setUp()) {
this->tearDown();
return ERROR_SETUP;
}
SDL_Event event;
while (this->running) {
unsigned int beginFrame = SDL_GetTicks();
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
this->running = false;
break;
}
}
this->updatePlayer();
this->updateWorld();
this->updateFPS();
this->renderWorld();
this->frameTime = (SDL_GetTicks() - beginFrame) / 1000.0f;
}
this->tearDown();
return ERROR_OK;
}
bool Game::setUp() {
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Setting up...");
if (!this->initSDL() || !this->initOpenGL() || !this->initFontConfig()) {
return false;
}
this->initTestScene();
return true;
}
void Game::tearDown() {
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Tearing down...");
if (this->defaultFont) {
TTF_CloseFont(this->defaultFont);
}
if (this->context) {
SDL_GL_DeleteContext(this->context);
}
if (this->window) {
SDL_DestroyWindow(this->window);
}
FcFini();
IMG_Quit();
TTF_Quit();
SDL_Quit();
}
bool Game::initSDL() {
if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE)) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "SDL_Init() failed: %s", SDL_GetError());
return false;
}
if (TTF_Init()) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "TTF_Init() failed: %s", TTF_GetError());
return false;
}
if (!IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG)) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "IMG_Init() failed: %s", IMG_GetError());
return false;
}
SDL_version sdlVersion;
SDL_GetVersion(&sdlVersion);
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "SDL version: %d.%d.%d",
sdlVersion.major, sdlVersion.minor, sdlVersion.patch);
const SDL_version *sdlTtfVersion = TTF_Linked_Version();
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "SDL_ttf version: %d.%d.%d",
sdlTtfVersion->major, sdlTtfVersion->minor, sdlTtfVersion->patch);
const SDL_version *sdlImageVersion = IMG_Linked_Version();
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "SDL_image version: %d.%d.%d",
sdlImageVersion->major, sdlImageVersion->minor, sdlImageVersion->patch);
return true;
}
bool Game::initOpenGL() {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Initializing %d x %d viewport", this->width, this->height);
this->window = SDL_CreateWindow("Polandball The Gaem", 0, 0, this->width, this->height,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if (!this->window) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "SDL_CreateWindow() failed: %s", SDL_GetError());
return false;
}
this->context = SDL_GL_CreateContext(this->window);
if (!this->context) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "SDL_GL_CreateContext() failed: %s", SDL_GetError());
return false;
}
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "OpenGL vendor: %s", glGetString(GL_VENDOR));
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "OpenGL version: %s", glGetString(GL_VERSION));
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return true;
}
bool Game::initFontConfig() {
if (!FcInit()) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "FcInit() failed");
return false;
}
int fcVersion = FcGetVersion();
int fcMajor = fcVersion / 10000;
int fcMinor = (fcVersion - fcMajor * 10000) / 100;
int fcRevision = fcVersion - fcMajor * 10000 - fcMinor * 100;
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Fontconfig version: %d.%d.%d",
fcMajor, fcMinor, fcRevision);
FcPattern* pattern = FcNameParse((const FcChar8*)"monospace");
FcConfigSubstitute(nullptr, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
FcResult result;
FcPattern* match = FcFontMatch(nullptr, pattern, &result);
FcPatternDestroy(pattern);
if (!match) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "FcFontMatch() failed: no `sans-serif' font found");
return false;
}
FcChar8* fontPath = FcPatternFormat(match, (const FcChar8*)"%{file}");
FcChar8* fontName = FcPatternFormat(match, (const FcChar8*)"%{family}");
this->defaultFont = TTF_OpenFont((const char*)fontPath, 12);
if (!this->defaultFont) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "TTF_OpenFont failed: %s", TTF_GetError());
return false;
}
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Using `%s' family font", fontName);
FcStrFree(fontName);
FcStrFree(fontPath);
FcPatternDestroy(match);
return true;
}
void Game::initTestScene() {
// GL_DEPTH_TEST is OFF! Manually arrange sprites, farthest renders first!
auto backgroundSprite = std::shared_ptr<Sprite>(new Sprite());
backgroundSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/day_sky_3x4.png"));
auto backgroundEntity = std::shared_ptr<Entity>(new Entity());
backgroundEntity->setSprite(backgroundSprite);
backgroundEntity->setCollidable(false);
backgroundEntity->scale(10.0f); // Fit the screen
backgroundEntity->scaleX(this->width / (this->height / 1.0f)); // Scale for aspect ratio
this->entites.push_back(backgroundEntity);
//-----------------
auto bricksSprite = std::shared_ptr<Sprite>(new Sprite());
bricksSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/kazakhstan_brick.png"));
auto bricksEntity = std::shared_ptr<Entity>(new Entity());
bricksEntity->setSprite(bricksSprite);
bricksEntity->setPosition(0.0f, -4.0f, 0.0f);
bricksEntity->scaleX(1.5f); // Scale for aspect ratio
bricksEntity->replicateX(20.0f);
this->entites.push_back(bricksEntity);
//-----------------
bricksSprite = std::shared_ptr<Sprite>(new Sprite());
bricksSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/kazakhstan_brick.png"));
bricksEntity = std::shared_ptr<Entity>(new Entity());
bricksEntity->setSprite(bricksSprite);
bricksEntity->setPosition(1.0f, 1.0f, 0.0f);
bricksEntity->scaleX(1.5f); // Scale for aspect ratio
this->entites.push_back(bricksEntity);
//-----------------
auto playerSprite = std::shared_ptr<Sprite>(new Sprite());
playerSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/turkey_ball.png"));
this->player = std::shared_ptr<Player>(new Player());
this->player->setSprite(playerSprite);
this->player->setPosition(0.0f, 5.0f, 0.0f);
this->entites.push_back(this->player);
//-----------------
this->fpsCounter = std::shared_ptr<Entity>(new Entity());
this->fpsCounter->setCollidable(false);
this->fpsCounter->scale(0.25f);
this->fpsCounter->setPosition(-12.0f, 9.5f, 0.0f);
this->entites.push_back(this->fpsCounter);
//-----------------
this->player->updatePosition.connect(std::bind(&Entity::onPositionUpdate, backgroundEntity, std::placeholders::_1));
this->player->updatePosition.connect(std::bind(&Camera::onPositionUpdate, &this->camera, std::placeholders::_1));
this->player->updatePosition.connect(std::bind(&Entity::onPositionUpdate, this->fpsCounter, std::placeholders::_1));
}
void Game::updateWorld() {
for (auto& entity: this->entites) {
if (entity->getType() != Entity::TYPE_DYNAMIC || !entity->isCollidable()) {
continue;
}
float scaleFactor = (this->frameTime > this->frameTime) ? this->frameTime : this->frameStep;
float totalTime = scaleFactor;
while (totalTime <= this->frameTime && scaleFactor > 0.0f) {
entity->setSpeed(entity->getSpeed() + this->gravityAcceleration * scaleFactor);
for (auto& another: this->entites) {
if (!another->isCollidable()) {
continue;
}
Collider::CollideSide collide = entity->getCollider()->collides(another->getCollider());
Math::Vec3 speed = entity->getSpeed();
switch (collide) {
case Collider::SIDE_BOTTOM:
if (speed.get(Math::Vec3::Y) < 0.0f) {
speed.set(Math::Vec3::Y, 0.0f);
}
break;
case Collider::SIDE_TOP:
if (speed.get(Math::Vec3::Y) > 0.0f) {
speed.set(Math::Vec3::Y, 0.0f);
}
break;
case Collider::SIDE_LEFT:
if (speed.get(Math::Vec3::X) < 0.0f) {
speed.set(Math::Vec3::X, 0.0f);
}
break;
case Collider::SIDE_RIGHT:
if (speed.get(Math::Vec3::X) > 0.0f) {
speed.set(Math::Vec3::X, 0.0f);
}
break;
default:
break;
}
entity->setSpeed(speed);
entity->collideWith(another, collide);
}
entity->setPosition(entity->getPosition() + entity->getSpeed() * scaleFactor);
scaleFactor = (this->frameTime - totalTime > this->frameStep) ? this->frameStep : this->frameTime - totalTime;
totalTime += scaleFactor;
}
}
}
void Game::updatePlayer() {
Uint8 *keyStates = SDL_GetKeyboardState(nullptr);
if (keyStates[SDL_SCANCODE_ESCAPE]) {
this->running = false;
}
// Both pressed or released
if (keyStates[SDL_SCANCODE_LEFT] == keyStates[SDL_SCANCODE_RIGHT]) {
this->player->slowDown(this->frameTime);
} else if (keyStates[SDL_SCANCODE_RIGHT]) {
this->player->moveRight(this->frameTime);
} else if (keyStates[SDL_SCANCODE_LEFT]) {
this->player->moveLeft(this->frameTime);
}
if (keyStates[SDL_SCANCODE_UP]) {
this->player->jump(this->frameTime);
} else {
this->player->breakJump();
}
}
void Game::renderWorld() {
glClear(GL_COLOR_BUFFER_BIT);
Math::Mat4 mvp(this->camera.getProjectionMatrix() *
this->camera.getRotationMatrix() *
this->camera.getTranslationMatrix());
for (auto& entity: this->entites) {
if (entity->isRenderable()) {
entity->getSprite()->getEffect()->setMVP(mvp);
entity->getSprite()->render();
}
}
SDL_GL_SwapWindow(this->window);
}
void Game::updateFPS() {
static float updateTime = 1.0f;
static float frames = 0.0f;
static float textAspectRatio = 1.0f;
if (updateTime >= 0.25f) {
std::stringstream fps;
fps << "fps: " << std::setw(5) << std::left << std::setprecision(0) << std::fixed << frames / updateTime;
int textWidth, textHeight;
TTF_SizeUTF8(this->defaultFont, fps.str().c_str(), &textWidth, &textHeight);
this->fpsCounter->scaleX(1.0f / textAspectRatio);
textAspectRatio = textWidth / (textHeight / 1.0f);
this->fpsCounter->scaleX(textAspectRatio);
SDL_Color color = {0, 0, 0, 0};
SDL_Surface *textOverlay = TTF_RenderUTF8_Blended(this->defaultFont, fps.str().c_str(), color);
this->fpsCounter->getSprite()->getTexture()->load(textOverlay);
SDL_FreeSurface(textOverlay);
updateTime = 0.0f;
frames = 0.0f;
}
updateTime += this->frameTime;
frames++;
}
} // namespace PolandBall
<commit_msg>Re-center player<commit_after>/*
* Copyright (c) 2013 Pavlo Lavrenenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Game.h"
#include "Logger.h"
#include "Vec3.h"
#include "ResourceManager.h"
#include <sstream>
#include <iomanip>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <fontconfig/fontconfig.h>
namespace PolandBall {
int Game::exec() {
if (!this->setUp()) {
this->tearDown();
return ERROR_SETUP;
}
SDL_Event event;
while (this->running) {
unsigned int beginFrame = SDL_GetTicks();
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
this->running = false;
break;
}
}
this->updatePlayer();
this->updateWorld();
this->updateFPS();
this->renderWorld();
this->frameTime = (SDL_GetTicks() - beginFrame) / 1000.0f;
}
this->tearDown();
return ERROR_OK;
}
bool Game::setUp() {
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Setting up...");
if (!this->initSDL() || !this->initOpenGL() || !this->initFontConfig()) {
return false;
}
this->initTestScene();
return true;
}
void Game::tearDown() {
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Tearing down...");
if (this->defaultFont) {
TTF_CloseFont(this->defaultFont);
}
if (this->context) {
SDL_GL_DeleteContext(this->context);
}
if (this->window) {
SDL_DestroyWindow(this->window);
}
FcFini();
IMG_Quit();
TTF_Quit();
SDL_Quit();
}
bool Game::initSDL() {
if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE)) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "SDL_Init() failed: %s", SDL_GetError());
return false;
}
if (TTF_Init()) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "TTF_Init() failed: %s", TTF_GetError());
return false;
}
if (!IMG_Init(IMG_INIT_PNG | IMG_INIT_JPG)) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "IMG_Init() failed: %s", IMG_GetError());
return false;
}
SDL_version sdlVersion;
SDL_GetVersion(&sdlVersion);
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "SDL version: %d.%d.%d",
sdlVersion.major, sdlVersion.minor, sdlVersion.patch);
const SDL_version *sdlTtfVersion = TTF_Linked_Version();
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "SDL_ttf version: %d.%d.%d",
sdlTtfVersion->major, sdlTtfVersion->minor, sdlTtfVersion->patch);
const SDL_version *sdlImageVersion = IMG_Linked_Version();
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "SDL_image version: %d.%d.%d",
sdlImageVersion->major, sdlImageVersion->minor, sdlImageVersion->patch);
return true;
}
bool Game::initOpenGL() {
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Initializing %d x %d viewport", this->width, this->height);
this->window = SDL_CreateWindow("Polandball The Gaem", 0, 0, this->width, this->height,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
if (!this->window) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "SDL_CreateWindow() failed: %s", SDL_GetError());
return false;
}
this->context = SDL_GL_CreateContext(this->window);
if (!this->context) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "SDL_GL_CreateContext() failed: %s", SDL_GetError());
return false;
}
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "OpenGL vendor: %s", glGetString(GL_VENDOR));
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "OpenGL version: %s", glGetString(GL_VERSION));
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return true;
}
bool Game::initFontConfig() {
if (!FcInit()) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "FcInit() failed");
return false;
}
int fcVersion = FcGetVersion();
int fcMajor = fcVersion / 10000;
int fcMinor = (fcVersion - fcMajor * 10000) / 100;
int fcRevision = fcVersion - fcMajor * 10000 - fcMinor * 100;
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Fontconfig version: %d.%d.%d",
fcMajor, fcMinor, fcRevision);
FcPattern* pattern = FcNameParse((const FcChar8*)"monospace");
FcConfigSubstitute(nullptr, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
FcResult result;
FcPattern* match = FcFontMatch(nullptr, pattern, &result);
FcPatternDestroy(pattern);
if (!match) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "FcFontMatch() failed: no `sans-serif' font found");
return false;
}
FcChar8* fontPath = FcPatternFormat(match, (const FcChar8*)"%{file}");
FcChar8* fontName = FcPatternFormat(match, (const FcChar8*)"%{family}");
this->defaultFont = TTF_OpenFont((const char*)fontPath, 12);
if (!this->defaultFont) {
Utils::Logger::getInstance().log(Utils::Logger::LOG_ERROR, "TTF_OpenFont failed: %s", TTF_GetError());
return false;
}
Utils::Logger::getInstance().log(Utils::Logger::LOG_INFO, "Using `%s' family font", fontName);
FcStrFree(fontName);
FcStrFree(fontPath);
FcPatternDestroy(match);
return true;
}
void Game::initTestScene() {
// GL_DEPTH_TEST is OFF! Manually arrange sprites, farthest renders first!
auto backgroundSprite = std::shared_ptr<Sprite>(new Sprite());
backgroundSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/day_sky_3x4.png"));
auto backgroundEntity = std::shared_ptr<Entity>(new Entity());
backgroundEntity->setSprite(backgroundSprite);
backgroundEntity->setCollidable(false);
backgroundEntity->scale(10.0f); // Fit the screen
backgroundEntity->scaleX(this->width / (this->height / 1.0f)); // Scale for aspect ratio
this->entites.push_back(backgroundEntity);
//-----------------
auto bricksSprite = std::shared_ptr<Sprite>(new Sprite());
bricksSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/kazakhstan_brick.png"));
auto bricksEntity = std::shared_ptr<Entity>(new Entity());
bricksEntity->setSprite(bricksSprite);
bricksEntity->setPosition(0.0f, -4.0f, 0.0f);
bricksEntity->scaleX(1.5f); // Scale for aspect ratio
bricksEntity->replicateX(20.0f);
this->entites.push_back(bricksEntity);
//-----------------
bricksSprite = std::shared_ptr<Sprite>(new Sprite());
bricksSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/kazakhstan_brick.png"));
bricksEntity = std::shared_ptr<Entity>(new Entity());
bricksEntity->setSprite(bricksSprite);
bricksEntity->setPosition(4.0f, 1.0f, 0.0f);
bricksEntity->scaleX(1.5f); // Scale for aspect ratio
this->entites.push_back(bricksEntity);
//-----------------
auto playerSprite = std::shared_ptr<Sprite>(new Sprite());
playerSprite->setTexture(Utils::ResourceManager::getInstance().makeTexture("textures/turkey_ball.png"));
this->player = std::shared_ptr<Player>(new Player());
this->player->setSprite(playerSprite);
this->player->setPosition(0.0f, 0.0f, 0.0f);
this->entites.push_back(this->player);
//-----------------
this->fpsCounter = std::shared_ptr<Entity>(new Entity());
this->fpsCounter->setCollidable(false);
this->fpsCounter->scale(0.25f);
this->fpsCounter->setPosition(-12.0f, 9.5f, 0.0f);
this->entites.push_back(this->fpsCounter);
//-----------------
this->player->updatePosition.connect(std::bind(&Entity::onPositionUpdate, backgroundEntity, std::placeholders::_1));
this->player->updatePosition.connect(std::bind(&Camera::onPositionUpdate, &this->camera, std::placeholders::_1));
this->player->updatePosition.connect(std::bind(&Entity::onPositionUpdate, this->fpsCounter, std::placeholders::_1));
}
void Game::updateWorld() {
for (auto& entity: this->entites) {
if (entity->getType() != Entity::TYPE_DYNAMIC || !entity->isCollidable()) {
continue;
}
float scaleFactor = (this->frameTime > this->frameTime) ? this->frameTime : this->frameStep;
float totalTime = scaleFactor;
while (totalTime <= this->frameTime && scaleFactor > 0.0f) {
entity->setSpeed(entity->getSpeed() + this->gravityAcceleration * scaleFactor);
for (auto& another: this->entites) {
if (!another->isCollidable()) {
continue;
}
Collider::CollideSide collide = entity->getCollider()->collides(another->getCollider());
Math::Vec3 speed = entity->getSpeed();
switch (collide) {
case Collider::SIDE_BOTTOM:
if (speed.get(Math::Vec3::Y) < 0.0f) {
speed.set(Math::Vec3::Y, 0.0f);
}
break;
case Collider::SIDE_TOP:
if (speed.get(Math::Vec3::Y) > 0.0f) {
speed.set(Math::Vec3::Y, 0.0f);
}
break;
case Collider::SIDE_LEFT:
if (speed.get(Math::Vec3::X) < 0.0f) {
speed.set(Math::Vec3::X, 0.0f);
}
break;
case Collider::SIDE_RIGHT:
if (speed.get(Math::Vec3::X) > 0.0f) {
speed.set(Math::Vec3::X, 0.0f);
}
break;
default:
break;
}
entity->setSpeed(speed);
entity->collideWith(another, collide);
}
entity->setPosition(entity->getPosition() + entity->getSpeed() * scaleFactor);
scaleFactor = (this->frameTime - totalTime > this->frameStep) ? this->frameStep : this->frameTime - totalTime;
totalTime += scaleFactor;
}
}
}
void Game::updatePlayer() {
Uint8 *keyStates = SDL_GetKeyboardState(nullptr);
if (keyStates[SDL_SCANCODE_ESCAPE]) {
this->running = false;
}
// Both pressed or released
if (keyStates[SDL_SCANCODE_LEFT] == keyStates[SDL_SCANCODE_RIGHT]) {
this->player->slowDown(this->frameTime);
} else if (keyStates[SDL_SCANCODE_RIGHT]) {
this->player->moveRight(this->frameTime);
} else if (keyStates[SDL_SCANCODE_LEFT]) {
this->player->moveLeft(this->frameTime);
}
if (keyStates[SDL_SCANCODE_UP]) {
this->player->jump(this->frameTime);
} else {
this->player->breakJump();
}
}
void Game::renderWorld() {
glClear(GL_COLOR_BUFFER_BIT);
Math::Mat4 mvp(this->camera.getProjectionMatrix() *
this->camera.getRotationMatrix() *
this->camera.getTranslationMatrix());
for (auto& entity: this->entites) {
if (entity->isRenderable()) {
entity->getSprite()->getEffect()->setMVP(mvp);
entity->getSprite()->render();
}
}
SDL_GL_SwapWindow(this->window);
}
void Game::updateFPS() {
static float updateTime = 1.0f;
static float frames = 0.0f;
static float textAspectRatio = 1.0f;
if (updateTime >= 0.25f) {
std::stringstream fps;
fps << "fps: " << std::setw(5) << std::left << std::setprecision(0) << std::fixed << frames / updateTime;
int textWidth, textHeight;
TTF_SizeUTF8(this->defaultFont, fps.str().c_str(), &textWidth, &textHeight);
this->fpsCounter->scaleX(1.0f / textAspectRatio);
textAspectRatio = textWidth / (textHeight / 1.0f);
this->fpsCounter->scaleX(textAspectRatio);
SDL_Color color = {0, 0, 0, 0};
SDL_Surface *textOverlay = TTF_RenderUTF8_Blended(this->defaultFont, fps.str().c_str(), color);
this->fpsCounter->getSprite()->getTexture()->load(textOverlay);
SDL_FreeSurface(textOverlay);
updateTime = 0.0f;
frames = 0.0f;
}
updateTime += this->frameTime;
frames++;
}
} // namespace PolandBall
<|endoftext|> |
<commit_before>
#include "base/thread_pool.hpp"
#include <vector>
#include "glog/logging.h"
#include "gmock/gmock.h"
namespace principia {
namespace base {
class ThreadPoolTest : public ::testing::Test {
protected:
ThreadPoolTest() : pool_(std::thread::hardware_concurrency()) {
LOG(ERROR) << "Concurrency is " << std::thread::hardware_concurrency();
}
ThreadPool<void> pool_;
};
// Check that execution occurs in parallel. If things were sequential, the
// integers in |numbers| would be non-decreasing.
TEST_F(ThreadPoolTest, ParallelExecution) {
static constexpr int number_of_calls = 1'000'000;
std::mutex lock;
std::vector<std::int64_t> numbers;
std::vector<std::future<void>> futures;
for (std::int64_t i = 0; i < number_of_calls; ++i) {
futures.push_back(pool_.Add([i, &lock, &numbers]() {
std::lock_guard<std::mutex> l(lock);
numbers.push_back(i);
}));
}
for (auto const& future : futures) {
future.wait();
}
bool decreasing = false;
for (std::int64_t i = 1; i < numbers.size(); ++i) {
if (numbers[i] < numbers[i - 1]) {
decreasing = true;
}
}
EXPECT_TRUE(decreasing);
}
} // namespace base
} // namespace principia
<commit_msg>After egg's 2nd review.<commit_after>
#include "base/thread_pool.hpp"
#include <vector>
#include "glog/logging.h"
#include "gmock/gmock.h"
namespace principia {
namespace base {
class ThreadPoolTest : public ::testing::Test {
protected:
ThreadPoolTest() : pool_(std::thread::hardware_concurrency()) {
LOG(ERROR) << "Concurrency is " << std::thread::hardware_concurrency();
}
ThreadPool<void> pool_;
};
// Check that execution occurs in parallel. If things were sequential, the
// integers in |numbers| would be monotonically increasing.
TEST_F(ThreadPoolTest, ParallelExecution) {
static constexpr int number_of_calls = 1'000'000;
std::mutex lock;
std::vector<std::int64_t> numbers;
std::vector<std::future<void>> futures;
for (std::int64_t i = 0; i < number_of_calls; ++i) {
futures.push_back(pool_.Add([i, &lock, &numbers]() {
std::lock_guard<std::mutex> l(lock);
numbers.push_back(i);
}));
}
for (auto const& future : futures) {
future.wait();
}
bool monotonically_increasing = true;
for (std::int64_t i = 1; i < numbers.size(); ++i) {
if (numbers[i] < numbers[i - 1]) {
monotonically_increasing = false;
}
}
EXPECT_FALSE(monotonically_increasing);
}
} // namespace base
} // namespace principia
<|endoftext|> |
<commit_before>
#include "Gfdi.h"
#include <array>
#include <cassert>
#include <cmath>
// helper functions and data
namespace {
// numerous constants used in the analytic approximations
//const std::array<double, 5> x = {{
const auto x = std::array<double, 5> {{
7.265351e-2, 0.2694608, 0.533122, 0.7868801, 0.9569313}};
const auto xi = std::array<double, 5> {{
0.26356032, 1.4134031, 3.5964258, 7.0858100, 12.640801}};
const auto h = std::array<double, 5> {{
3.818735e-2, 0.1256732, 0.1986308, 0.1976334, 0.1065420}};
const auto v = std::array<double, 5> {{
0.29505869, 0.32064856, 7.3915570e-2, 3.6087389e-3, 2.3369894e-5}};
const auto c = std::array<std::array<double, 5>, 3> {{
{{0.37045057, 0.41258437, 9.777982e-2, 5.3734153e-3, 3.8746281e-5}},
{{0.39603109, 0.69468795, 0.22322760, 1.5262934e-2, 1.3081939e-4}},
{{0.76934619, 1.7891437, 0.70754974, 5.6755672e-2, 5.5571480e-4}}}};
const auto khi = std::array<std::array<double, 5>, 3> {{
{{0.43139881, 1.7597537, 4.1044654, 7.7467038, 13.457678}},
{{0.81763176, 2.4723339, 5.1160061, 9.0441465, 15.049882}},
{{1.2558461, 3.2070406, 6.1239082, 10.316126, 16.597079}}}};
inline double cube(const double a) {
return a*a*a;
}
// helper function for GFDI work
double gfdi_helper(const int k, const double chi, const double tau,
const double r) {
if (chi*tau < 1.e-4 and chi > 0.0) {
return pow(chi, k+3./2)/(k+3./2);
}
else if (k==0) {
return (chi + 1/tau)*r/2
- pow(2*tau, -3./2) * log(1 + tau*chi + sqrt(2*tau)*r);
}
else if (k==1) {
return (2./3*cube(r) - gfdi_helper(0, chi, tau, r)) / tau;
}
else if (k==2) {
return (2*chi*cube(r) - 5*gfdi_helper(1, chi, tau, r)) / (4*tau);
}
else {
return 0.0;
}
}
} // end anonymous namespace
double gfdi(const GFDI order, const double chi, const double tau) {
assert(tau <= 100. and "Outside of known convergence region for analytic approx.");
const int k = static_cast<int>(order);
if (chi <= 0.6) {
double value = 0;
for (size_t i=1; i<=5; ++i) {
value += c[k][i-1] * sqrt(1 + khi[k][i-1]*tau/2) /
(exp(-khi[k][i-1]) + exp(-chi));
}
return value;
}
else if (chi < 14.0) {
double value = 0;
for (size_t i=1; i<=5; ++i) {
value += h[i-1] * pow(x[i-1], k) * pow(chi, k+3./2)
* sqrt(1 + chi*x[i-1]*tau/2) / (1 + exp(chi*(x[i-1] - 1)))
+ v[i-1] * pow(xi[i-1] + chi, k+1./2) * sqrt(1 + (xi[i-1] + chi)*tau/2);
}
return value;
}
else {
const double r = sqrt(chi*(1 + chi*tau/2));
return gfdi_helper(k, chi, tau, r)
+ M_PI*M_PI/6. * pow(chi, k) * (k + 1./2 + (k+1)*chi*tau/2) / r;
}
}
<commit_msg>Gfdi: Add smooth transition function<commit_after>
#include "Gfdi.h"
#include <array>
#include <cassert>
#include <cmath>
// helper functions and data
namespace {
// numerous constants used in the analytic approximations
//const std::array<double, 5> x = {{
const auto x = std::array<double, 5> {{
7.265351e-2, 0.2694608, 0.533122, 0.7868801, 0.9569313}};
const auto xi = std::array<double, 5> {{
0.26356032, 1.4134031, 3.5964258, 7.0858100, 12.640801}};
const auto h = std::array<double, 5> {{
3.818735e-2, 0.1256732, 0.1986308, 0.1976334, 0.1065420}};
const auto v = std::array<double, 5> {{
0.29505869, 0.32064856, 7.3915570e-2, 3.6087389e-3, 2.3369894e-5}};
const auto c = std::array<std::array<double, 5>, 3> {{
{{0.37045057, 0.41258437, 9.777982e-2, 5.3734153e-3, 3.8746281e-5}},
{{0.39603109, 0.69468795, 0.22322760, 1.5262934e-2, 1.3081939e-4}},
{{0.76934619, 1.7891437, 0.70754974, 5.6755672e-2, 5.5571480e-4}}}};
const auto khi = std::array<std::array<double, 5>, 3> {{
{{0.43139881, 1.7597537, 4.1044654, 7.7467038, 13.457678}},
{{0.81763176, 2.4723339, 5.1160061, 9.0441465, 15.049882}},
{{1.2558461, 3.2070406, 6.1239082, 10.316126, 16.597079}}}};
inline double cube(const double a) {
return a*a*a;
}
// helper function for GFDI work
double gfdi_helper(const int k, const double chi, const double tau,
const double r) {
if (chi*tau < 1.e-4 and chi > 0.0) {
return pow(chi, k+3./2)/(k+3./2);
}
else if (k==0) {
return (chi + 1/tau)*r/2
- pow(2*tau, -3./2) * log(1 + tau*chi + sqrt(2*tau)*r);
}
else if (k==1) {
return (2./3*cube(r) - gfdi_helper(0, chi, tau, r)) / tau;
}
else if (k==2) {
return (2*chi*cube(r) - 5*gfdi_helper(1, chi, tau, r)) / (4*tau);
}
else {
return 0.0;
}
}
inline double gfdi_small(const int k, const double chi, const double tau) {
double value = 0;
for (size_t i=1; i<=5; ++i) {
value += c[k][i-1] * sqrt(1 + khi[k][i-1]*tau/2) /
(exp(-khi[k][i-1]) + exp(-chi));
}
return value;
}
inline double gfdi_mid(const int k, const double chi, const double tau) {
double value = 0;
for (size_t i=1; i<=5; ++i) {
value += h[i-1] * pow(x[i-1], k) * pow(chi, k+3./2)
* sqrt(1 + chi*x[i-1]*tau/2) / (1 + exp(chi*(x[i-1] - 1)))
+ v[i-1] * pow(xi[i-1] + chi, k+1./2) * sqrt(1 + (xi[i-1] + chi)*tau/2);
}
return value;
}
inline double gfdi_large(const int k, const double chi, const double tau) {
const double r = sqrt(chi*(1 + chi*tau/2));
return gfdi_helper(k, chi, tau, r)
+ M_PI*M_PI/6. * pow(chi, k) * (k + 1./2 + (k+1)*chi*tau/2) / r;
}
// a cubic transition function which satisfies:
// f(0) = 0, f'(0) = 0
// f(1) = 1, f'(1) = 0
inline double transition(const double fl, const double fr,
const double x, const double xl, const double xr) {
const double z = (x-xl)/(xr-xl);
const double fz = 3.*z*z - 2.*cube(z);
return fl + fz*(fr-fl);
}
} // end anonymous namespace
double gfdi(const GFDI order, const double chi, const double tau) {
assert(tau <= 100. and "Outside of known convergence region for analytic approx.");
const int k = static_cast<int>(order);
if (chi <= 0.59) {
return gfdi_small(k, chi, tau);
}
// smooth the transition from chi being "small" to "mid" over 0.59 -> 0.61
else if (chi < 0.61) {
const double gs = gfdi_small(k, chi, tau);
const double gm = gfdi_mid(k, chi, tau);
return transition(gs, gm, chi, 0.59, 0.61);
}
else if (chi <= 13.9) {
return gfdi_mid(k, chi, tau);
}
// smooth the "mid" to "large" transition over 13.9 -> 14.1
else if (chi < 14.1) {
const double gm = gfdi_mid(k, chi, tau);
const double gl = gfdi_large(k, chi, tau);
return transition(gm, gl, chi, 13.9, 14.1);
}
else {
return gfdi_large(k, chi, tau);
}
}
<|endoftext|> |
<commit_before>#ifndef __ENVIRE_MAPS_GRID_HPP__
#define __ENVIRE_MAPS_GRID_HPP__
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <boost/function.hpp>
#include "LocalMap.hpp"
namespace envire { namespace maps
{
/**@brief type for the number of cells
*/
typedef Eigen::Matrix<unsigned int, 2, 1> Vector2ui;
/**@brief type for grid resolution
*/
typedef Eigen::Vector2d Vector2d;
/**@brief type for grid position
*/
typedef Eigen::Vector3d Vector3d;
/**@brief Internal structure used to represent a position on the grid
* itself, as a cell index
*/
class Index : public Vector2ui
{
public:
typedef Vector2ui Base;
Index()
: Vector2ui(0, 0)
{}
Index(unsigned int x, unsigned int y)
: Vector2ui(x, y)
{}
// This constructor allows you to construct Index from Eigen expressions
template<typename OtherDerived>
Index(const Eigen::MatrixBase<OtherDerived>& other)
: Vector2ui(other)
{}
bool operator<(const Index& other) const
{
return (x() < other.x()
|| (x() == other.x() && y() < other.y()));
}
bool operator>(const Index& other) const
{
return (x() > other.x()
|| (x() == other.x() && y() > other.y()));
}
// TODO: add exception if the other is bigger
// than this. due to uint
//Index operator-(const Index& other) const
//{
//}
};
/** Base class for all 2D gridbased maps.
* - describes the grid structure: resolution and number of cells in x- and y- axes.
* - converts position -> index and index -> position
* - checks if the position or index is inside the grid
*/
class Grid : public LocalMap
{
public:
typedef boost::shared_ptr<Grid> Ptr;
protected:
/** Number of cells in X-axis and Y-axis **/
Vector2ui num_cells;
/**
* Resolution in local X-axis and Y-axis
* (Size of the cell in local X-axis and Y-axis in world unit)
*/
Vector2d resolution;
public:
Grid();
Grid(const Vector2ui &num_cells, const Vector2d &resolution);
/**
* @brief [brief description]
* @details share the LocalMapData
*
* @param num_cells [description]
* @param resolution [description]
* @param data [description]
*/
Grid(const Vector2ui &num_cells,
const Vector2d &resolution,
const boost::shared_ptr<LocalMapData> &data);
virtual ~Grid();
/** @brief get the number of cells
*/
const Vector2ui& getNumCells() const;
/**
* @brief get the resolution of the grid
* @return cell size in local X-axis and Y-axis in world unit
*/
const Vector2d& getResolution() const;
/**
* @brief get the size of the grid in world unit
* @return size of the grid in local X-axis and Y-axis in wold unit
*/
Vector2d getSize() const;
/**
* @brief check whether the index argument is inside the grid
* @return true or false
*/
bool inGrid(const Index& idx) const;
/**
* @brief convert the index (the grid position) into position in local frame
* by taking the offset (base::Transform3d) into account as description
* from the local map
*
*/
bool fromGrid(const Index& idx, Vector3d& pos) const;
/**
* @brief Converts coordinates from the map-local grid coordinates to
* the coordinates in the specified \c frame
*/
bool fromGrid(const Index& idx, Vector3d& pos_in_frame, const base::Transform3d &frame_in_grid) const;
/**
* @brief [brief description]
* @details for the corner and border cases no definite solution
*
* @param pos [description]
* @param idx [description]
*
* @return [description]
*/
bool toGrid(const Vector3d& pos, Index& idx) const;
bool toGrid(const Vector3d& pos, Index& idx, Vector3d &pos_diff) const;
bool toGrid(const Vector3d& pos_in_frame, Index& idx, const base::Transform3d &frame_in_grid) const;
};
}}
#endif // __ENVIRE_MAPS_GRIDBASE_HPP__
<commit_msg>src: fixed error in the Index class for the Grid<commit_after>#ifndef __ENVIRE_MAPS_GRID_HPP__
#define __ENVIRE_MAPS_GRID_HPP__
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <boost/function.hpp>
#include "LocalMap.hpp"
namespace envire { namespace maps
{
/**@brief type for the number of cells
*/
typedef Eigen::Matrix<unsigned int, 2, 1> Vector2ui;
/**@brief type for grid resolution
*/
typedef Eigen::Vector2d Vector2d;
/**@brief type for grid position
*/
typedef Eigen::Vector3d Vector3d;
/**@brief Internal structure used to represent a position on the grid
* itself, as a cell index
*/
class Index : public Vector2ui
{
public:
typedef Vector2ui Base;
Index()
: Vector2ui(0, 0)
{}
Index(unsigned int x, unsigned int y)
: Vector2ui(x, y)
{}
/* @brief this constructor allows you to construct Index from Eigen expressions
*/
template<typename OtherDerived>
Index(const Eigen::MatrixBase<OtherDerived>& other)
: Vector2ui(other)
{}
/* @brief smaller than operator (element by element)
*/
bool operator<(const Index& other) const
{
return (x() < other.x() && y() < other.y());
}
/* @brief bigger than operator (element by element)
*/
bool operator>(const Index& other) const
{
return (x() > other.x() && y() > other.y());
}
};
/** Base class for all 2D gridbased maps.
* - describes the grid structure: resolution and number of cells in x- and y- axes.
* - converts position -> index and index -> position
* - checks if the position or index is inside the grid
*/
class Grid : public LocalMap
{
public:
typedef boost::shared_ptr<Grid> Ptr;
protected:
/** Number of cells in X-axis and Y-axis **/
Vector2ui num_cells;
/**
* Resolution in local X-axis and Y-axis
* (Size of the cell in local X-axis and Y-axis in world unit)
*/
Vector2d resolution;
public:
Grid();
Grid(const Vector2ui &num_cells, const Vector2d &resolution);
/**
* @brief [brief description]
* @details share the LocalMapData
*
* @param num_cells [description]
* @param resolution [description]
* @param data [description]
*/
Grid(const Vector2ui &num_cells,
const Vector2d &resolution,
const boost::shared_ptr<LocalMapData> &data);
virtual ~Grid();
/** @brief get the number of cells
*/
const Vector2ui& getNumCells() const;
/**
* @brief get the resolution of the grid
* @return cell size in local X-axis and Y-axis in world unit
*/
const Vector2d& getResolution() const;
/**
* @brief get the size of the grid in world unit
* @return size of the grid in local X-axis and Y-axis in wold unit
*/
Vector2d getSize() const;
/**
* @brief check whether the index argument is inside the grid
* @return true or false
*/
bool inGrid(const Index& idx) const;
/**
* @brief convert the index (the grid position) into position in local frame
* by taking the offset (base::Transform3d) into account as description
* from the local map
*
*/
bool fromGrid(const Index& idx, Vector3d& pos) const;
/**
* @brief Converts coordinates from the map-local grid coordinates to
* the coordinates in the specified \c frame
*/
bool fromGrid(const Index& idx, Vector3d& pos_in_frame, const base::Transform3d &frame_in_grid) const;
/**
* @brief [brief description]
* @details for the corner and border cases no definite solution
*
* @param pos [description]
* @param idx [description]
*
* @return [description]
*/
bool toGrid(const Vector3d& pos, Index& idx) const;
bool toGrid(const Vector3d& pos, Index& idx, Vector3d &pos_diff) const;
bool toGrid(const Vector3d& pos_in_frame, Index& idx, const base::Transform3d &frame_in_grid) const;
};
}}
#endif // __ENVIRE_MAPS_GRIDBASE_HPP__
<|endoftext|> |
<commit_before>// ChiCheFrame.cpp
#include "ChiChe.h"
using namespace ChiChe;
//=====================================================================================
Frame::Frame( void ) : wxFrame( 0, wxID_ANY, "Chinese Checkers", wxDefaultPosition, wxSize( 900, 600 ) ), timer( this, ID_Timer )
{
wxMenu* gameMenu = new wxMenu();
wxMenuItem* joinGameMenuItem = new wxMenuItem( gameMenu, ID_JoinGame, wxT( "Join Game" ), wxT( "Join a hosted game on the network." ) );
wxMenuItem* hostGameMenuItem = new wxMenuItem( gameMenu, ID_HostGame, wxT( "Host Game" ), wxT( "Host a game on the network." ) );
wxMenuItem* leaveGameMenuItem = new wxMenuItem( gameMenu, ID_LeaveGame, wxT( "Leave Game" ), wxT( "Disconnect from a joined game." ) );
wxMenuItem* killGameMenuItem = new wxMenuItem( gameMenu, ID_KillGame, wxT( "Kill Game" ), wxT( "Discontinue a hosted game." ) );
wxMenuItem* toggleSoundMenuItem = new wxMenuItem( gameMenu, ID_ToggleSound, wxT( "Sound" ), wxT( "Toggle the playing of sound FX." ), wxITEM_CHECK );
wxMenuItem* effectMenuItem = new wxMenuItem( gameMenu, ID_Effect, wxT( "Effect" ), wxT( "Choose your sound effect." ) );
wxMenuItem* exitMenuItem = new wxMenuItem( gameMenu, ID_Exit, wxT( "Exit" ), wxT( "Exit the program." ) );
wxMenu* effectMenu = new wxMenu();
wxMenuItem* doinkMenuItem = new wxMenuItem( effectMenu, ID_DoinkEffect, wxT( "Doinks" ), wxT( "Your marble pieces \"doink\" about the board. It's awesome." ), wxITEM_CHECK );
wxMenuItem* fartMenuItem = new wxMenuItem( effectMenu, ID_FartEffect, wxT( "Farts" ), wxT( "Your marble pieces expell gas as they hop about the board." ), wxITEM_CHECK );
wxMenuItem* hiyawMenuItem = new wxMenuItem( effectMenu, ID_HiyawEffect, wxT( "Hiyaw!" ), wxT( "Each of your marble pieces is a black-belt in karete." ), wxITEM_CHECK );
effectMenu->Append( doinkMenuItem );
effectMenu->Append( fartMenuItem );
effectMenu->Append( hiyawMenuItem );
effectMenuItem->SetSubMenu( effectMenu );
gameMenu->Append( joinGameMenuItem );
gameMenu->Append( hostGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( leaveGameMenuItem );
gameMenu->Append( killGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( toggleSoundMenuItem );
gameMenu->Append( effectMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( exitMenuItem );
wxMenu* helpMenu = new wxMenu();
wxMenuItem* aboutMenuItem = new wxMenuItem( helpMenu, ID_About, wxT( "About" ), wxT( "Popup a dialog giving information about this program." ) );
helpMenu->Append( aboutMenuItem );
menuBar = new wxMenuBar();
menuBar->Append( gameMenu, wxT( "Game" ) );
menuBar->Append( helpMenu, wxT( "Help" ) );
SetMenuBar( menuBar );
statusBar = new wxStatusBar( this );
statusBar->PushStatusText( wxT( "Welcome! Remember to use the right mouse button to select marbles and board locations." ) );
SetStatusBar( statusBar );
Bind( wxEVT_MENU, &Frame::OnJoinGame, this, ID_JoinGame );
Bind( wxEVT_MENU, &Frame::OnHostGame, this, ID_HostGame );
Bind( wxEVT_MENU, &Frame::OnLeaveGame, this, ID_LeaveGame );
Bind( wxEVT_MENU, &Frame::OnKillGame, this, ID_KillGame );
Bind( wxEVT_MENU, &Frame::OnToggleSound, this, ID_ToggleSound );
Bind( wxEVT_MENU, &Frame::OnToggleEffect, this, ID_DoinkEffect );
Bind( wxEVT_MENU, &Frame::OnToggleEffect, this, ID_FartEffect );
Bind( wxEVT_MENU, &Frame::OnToggleEffect, this, ID_HiyawEffect );
Bind( wxEVT_MENU, &Frame::OnExit, this, ID_Exit );
Bind( wxEVT_MENU, &Frame::OnAbout, this, ID_About );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_JoinGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_HostGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_LeaveGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_KillGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_ToggleSound );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_Effect );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_DoinkEffect );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_FartEffect );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_HiyawEffect );
Bind( wxEVT_TIMER, &Frame::OnTimer, this, ID_Timer );
Bind( wxEVT_CLOSE_WINDOW, &Frame::OnClose, this );
Bind( wxEVT_ACTIVATE, &Frame::OnActivate, this );
canvas = new Canvas( this );
wxBoxSizer* boxSizer = new wxBoxSizer( wxHORIZONTAL );
boxSizer->Add( canvas, 1, wxALL | wxGROW, 0 );
SetSizer( boxSizer );
timer.Start( 50 );
continuousRefresh = true;
}
//=====================================================================================
/*virtual*/ Frame::~Frame( void )
{
}
//=====================================================================================
void Frame::OnHostGame( wxCommandEvent& event )
{
Server* server = wxGetApp().GetServer();
if( server )
return;
// The order of this array matches the enum in the Board class.
wxArrayString colorChoices;
colorChoices.Add( "Red" );
colorChoices.Add( "Green" );
colorChoices.Add( "Blue" );
colorChoices.Add( "Yellow" );
colorChoices.Add( "Magenta" );
colorChoices.Add( "Cyan" );
wxMultiChoiceDialog multiChoiceDialog( this, wxT( "Who will particpate in this game?" ), wxT( "Choose Participants" ), colorChoices );
if( wxID_OK != multiChoiceDialog.ShowModal() )
return;
wxArrayInt selections = multiChoiceDialog.GetSelections();
if( selections.Count() < 2 )
return;
int participants = 0;
for( wxArrayInt::iterator iter = selections.begin(); iter != selections.end(); iter++ )
{
int color = *iter + 1;
participants |= 1 << color;
}
wxScopedPtr< Server > serverPtr;
serverPtr.reset( new Server( participants ) );
unsigned short port = ( unsigned short )wxGetNumberFromUser( wxT( "On what port should the server listen?" ), wxT( "Port:" ), wxT( "Choose Port" ), 3000, 3000, 5000, this );
if( !serverPtr->Initialize( port ) )
return;
server = serverPtr.release();
wxGetApp().SetServer( server );
wxMessageBox( wxT( "Your game server is online and running!" ), wxT( "Server Initialization Success" ), wxOK | wxCENTRE, this );
}
//=====================================================================================
void Frame::OnJoinGame( wxCommandEvent& event )
{
Client* client = wxGetApp().GetClient();
if( client )
return;
wxString addressString = wxT( "127.0.0.1:3000" );
wxTextEntryDialog textEntryDialog( this, wxT( "Please enter the address of the host with port number." ), wxT( "Enter Address Of Host" ), addressString );
if( wxID_OK != textEntryDialog.ShowModal() )
return;
wxStringTokenizer stringTokenizer( addressString, ":" );
wxString ipAddressString, portString;
if( !stringTokenizer.HasMoreTokens() )
return;
ipAddressString = stringTokenizer.GetNextToken();
if( !stringTokenizer.HasMoreTokens() )
return;
portString = stringTokenizer.GetNextToken();
unsigned long port;
if( !portString.ToULong( &port ) )
return;
wxIPV4address address;
if( !address.Hostname( ipAddressString ) )
return;
address.Service( ( unsigned short )port );
wxArrayString typeChoices;
typeChoices.Add( "Human" );
typeChoices.Add( "Computer" );
wxSingleChoiceDialog singleChoiceDialog( this, wxT( "Will this be a human or computer client?" ), wxT( "Choose Client Type" ), typeChoices );
if( wxID_OK != singleChoiceDialog.ShowModal() )
return;
Client::Type clientType = Client::HUMAN;
wxString selection = singleChoiceDialog.GetStringSelection();
if( selection == wxT( "Computer" ) )
clientType = Client::COMPUTER;
wxScopedPtr< Client > clientPtr;
clientPtr.reset( new Client( clientType ) );
if( !clientPtr->Connect( address ) )
return;
client = clientPtr.release();
wxGetApp().SetClient( client );
}
//=====================================================================================
void Frame::OnLeaveGame( wxCommandEvent& event )
{
KillClient();
}
//=====================================================================================
void Frame::OnKillGame( wxCommandEvent& event )
{
KillServer();
}
//=====================================================================================
void Frame::OnExit( wxCommandEvent& event )
{
Close( true );
}
//=====================================================================================
void Frame::KillServer( void )
{
Server* server = wxGetApp().GetServer();
if( server )
{
server->Finalize();
delete server;
wxGetApp().SetServer(0);
}
}
//=====================================================================================
void Frame::KillClient( void )
{
Client* client = wxGetApp().GetClient();
if( client )
{
delete client;
wxGetApp().SetClient(0);
}
}
//=====================================================================================
void Frame::OnClose( wxCloseEvent& event )
{
KillServer();
KillClient();
event.Skip();
}
//=====================================================================================
void Frame::OnToggleSound( wxCommandEvent& event )
{
wxGetApp().GetSound()->Enable( !wxGetApp().GetSound()->IsEnabled() );
}
//=====================================================================================
void Frame::OnToggleEffect( wxCommandEvent& event )
{
switch( event.GetId() )
{
case ID_DoinkEffect:
{
wxGetApp().soundEffect = "Doink";
break;
}
case ID_FartEffect:
{
wxGetApp().soundEffect = "Fart";
break;
}
case ID_HiyawEffect:
{
wxGetApp().soundEffect = "Hiyaw";
break;
}
}
}
//=====================================================================================
void Frame::OnAbout( wxCommandEvent& event )
{
wxAboutDialogInfo aboutDialogInfo;
aboutDialogInfo.SetName( wxT( "Chinese Checkers" ) );
aboutDialogInfo.SetVersion( wxT( "1.0" ) );
aboutDialogInfo.SetDescription( wxT( "This program is free software and distributed under the MIT license. The AI in this program is terrible; I'm working to improve it." ) );
aboutDialogInfo.SetCopyright( wxT( "Copyright (C) 2013 Spencer T. Parkin <spencer.parkin@disney.com>" ) );
wxAboutBox( aboutDialogInfo );
}
//=====================================================================================
void Frame::OnUpdateMenuItemUI( wxUpdateUIEvent& event )
{
switch( event.GetId() )
{
case ID_JoinGame:
{
event.Enable( wxGetApp().GetClient() ? false : true );
break;
}
case ID_HostGame:
{
event.Enable( wxGetApp().GetServer() ? false : true );
break;
}
case ID_LeaveGame:
{
event.Enable( wxGetApp().GetClient() ? true : false );
break;
}
case ID_KillGame:
{
event.Enable( wxGetApp().GetServer() ? true : false );
break;
}
case ID_ToggleSound:
{
if( !wxGetApp().GetSound()->IsSetup() )
event.Enable( false );
else
{
event.Enable( true );
event.Check( wxGetApp().GetSound()->IsEnabled() );
}
break;
}
case ID_Effect:
{
event.Enable( wxGetApp().GetSound()->IsSetup() && wxGetApp().GetSound()->IsEnabled() );
break;
}
case ID_DoinkEffect:
{
event.Check( wxGetApp().soundEffect == "Doink" ? true : false );
break;
}
case ID_FartEffect:
{
event.Check( wxGetApp().soundEffect == "Fart" ? true : false );
break;
}
case ID_HiyawEffect:
{
event.Check( wxGetApp().soundEffect == "Hiyaw" ? true : false );
break;
}
}
}
//=====================================================================================
void Frame::OnTimer( wxTimerEvent& event )
{
// This routine was never meant to be re-entrant.
// Re-entrancy could cause a crash due to client or server death.
// If a dialog is put up in this routine, wxWidgets still calls the timer,
// which can cause re-entrancy.
static bool inOnTimer = false;
if( inOnTimer )
return;
inOnTimer = true;
Server* server = wxGetApp().GetServer();
if( server && !server->Run() )
KillServer();
Client* client = wxGetApp().GetClient();
if( client )
{
if( !client->Run() )
{
KillClient();
wxMessageBox( wxT( "We have lost our connection with the server, possibly because the game server has gone down." ), wxT( "Connection Lost" ), wxOK | wxCENTRE, wxGetApp().GetFrame() );
}
else
{
client->Animate( canvas->FrameRate() );
if( continuousRefresh )
canvas->Refresh();
}
}
inOnTimer = false;
}
//=====================================================================================
void Frame::OnActivate( wxActivateEvent& event )
{
continuousRefresh = event.GetActive();
}
//=====================================================================================
wxStatusBar* Frame::GetStatusBar( void )
{
return statusBar;
}
// ChiCheFrame.cpp
<commit_msg>i think it's better now...still needs improvement, but it's better<commit_after>// ChiCheFrame.cpp
#include "ChiChe.h"
using namespace ChiChe;
//=====================================================================================
Frame::Frame( void ) : wxFrame( 0, wxID_ANY, "Chinese Checkers", wxDefaultPosition, wxSize( 900, 600 ) ), timer( this, ID_Timer )
{
wxMenu* gameMenu = new wxMenu();
wxMenuItem* joinGameMenuItem = new wxMenuItem( gameMenu, ID_JoinGame, wxT( "Join Game" ), wxT( "Join a hosted game on the network." ) );
wxMenuItem* hostGameMenuItem = new wxMenuItem( gameMenu, ID_HostGame, wxT( "Host Game" ), wxT( "Host a game on the network." ) );
wxMenuItem* leaveGameMenuItem = new wxMenuItem( gameMenu, ID_LeaveGame, wxT( "Leave Game" ), wxT( "Disconnect from a joined game." ) );
wxMenuItem* killGameMenuItem = new wxMenuItem( gameMenu, ID_KillGame, wxT( "Kill Game" ), wxT( "Discontinue a hosted game." ) );
wxMenuItem* toggleSoundMenuItem = new wxMenuItem( gameMenu, ID_ToggleSound, wxT( "Sound" ), wxT( "Toggle the playing of sound FX." ), wxITEM_CHECK );
wxMenuItem* effectMenuItem = new wxMenuItem( gameMenu, ID_Effect, wxT( "Effect" ), wxT( "Choose your sound effect." ) );
wxMenuItem* exitMenuItem = new wxMenuItem( gameMenu, ID_Exit, wxT( "Exit" ), wxT( "Exit the program." ) );
wxMenu* effectMenu = new wxMenu();
wxMenuItem* doinkMenuItem = new wxMenuItem( effectMenu, ID_DoinkEffect, wxT( "Doinks" ), wxT( "Your marble pieces \"doink\" about the board. It's awesome." ), wxITEM_CHECK );
wxMenuItem* fartMenuItem = new wxMenuItem( effectMenu, ID_FartEffect, wxT( "Farts" ), wxT( "Your marble pieces expell gas as they hop about the board." ), wxITEM_CHECK );
wxMenuItem* hiyawMenuItem = new wxMenuItem( effectMenu, ID_HiyawEffect, wxT( "Hiyaw!" ), wxT( "Each of your marble pieces is a black-belt in karete." ), wxITEM_CHECK );
effectMenu->Append( doinkMenuItem );
effectMenu->Append( fartMenuItem );
effectMenu->Append( hiyawMenuItem );
effectMenuItem->SetSubMenu( effectMenu );
gameMenu->Append( joinGameMenuItem );
gameMenu->Append( hostGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( leaveGameMenuItem );
gameMenu->Append( killGameMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( toggleSoundMenuItem );
gameMenu->Append( effectMenuItem );
gameMenu->AppendSeparator();
gameMenu->Append( exitMenuItem );
wxMenu* helpMenu = new wxMenu();
wxMenuItem* aboutMenuItem = new wxMenuItem( helpMenu, ID_About, wxT( "About" ), wxT( "Popup a dialog giving information about this program." ) );
helpMenu->Append( aboutMenuItem );
menuBar = new wxMenuBar();
menuBar->Append( gameMenu, wxT( "Game" ) );
menuBar->Append( helpMenu, wxT( "Help" ) );
SetMenuBar( menuBar );
statusBar = new wxStatusBar( this );
statusBar->PushStatusText( wxT( "Welcome! Remember to use the right mouse button to select marbles and board locations." ) );
SetStatusBar( statusBar );
Bind( wxEVT_MENU, &Frame::OnJoinGame, this, ID_JoinGame );
Bind( wxEVT_MENU, &Frame::OnHostGame, this, ID_HostGame );
Bind( wxEVT_MENU, &Frame::OnLeaveGame, this, ID_LeaveGame );
Bind( wxEVT_MENU, &Frame::OnKillGame, this, ID_KillGame );
Bind( wxEVT_MENU, &Frame::OnToggleSound, this, ID_ToggleSound );
Bind( wxEVT_MENU, &Frame::OnToggleEffect, this, ID_DoinkEffect );
Bind( wxEVT_MENU, &Frame::OnToggleEffect, this, ID_FartEffect );
Bind( wxEVT_MENU, &Frame::OnToggleEffect, this, ID_HiyawEffect );
Bind( wxEVT_MENU, &Frame::OnExit, this, ID_Exit );
Bind( wxEVT_MENU, &Frame::OnAbout, this, ID_About );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_JoinGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_HostGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_LeaveGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_KillGame );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_ToggleSound );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_Effect );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_DoinkEffect );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_FartEffect );
Bind( wxEVT_UPDATE_UI, &Frame::OnUpdateMenuItemUI, this, ID_HiyawEffect );
Bind( wxEVT_TIMER, &Frame::OnTimer, this, ID_Timer );
Bind( wxEVT_CLOSE_WINDOW, &Frame::OnClose, this );
Bind( wxEVT_ACTIVATE, &Frame::OnActivate, this );
canvas = new Canvas( this );
wxBoxSizer* boxSizer = new wxBoxSizer( wxHORIZONTAL );
boxSizer->Add( canvas, 1, wxALL | wxGROW, 0 );
SetSizer( boxSizer );
timer.Start( 50 );
continuousRefresh = true;
}
//=====================================================================================
/*virtual*/ Frame::~Frame( void )
{
}
//=====================================================================================
void Frame::OnHostGame( wxCommandEvent& event )
{
Server* server = wxGetApp().GetServer();
if( server )
return;
// The order of this array matches the enum in the Board class.
wxArrayString colorChoices;
colorChoices.Add( "Red" );
colorChoices.Add( "Green" );
colorChoices.Add( "Blue" );
colorChoices.Add( "Yellow" );
colorChoices.Add( "Magenta" );
colorChoices.Add( "Cyan" );
wxMultiChoiceDialog multiChoiceDialog( this, wxT( "Who will particpate in this game?" ), wxT( "Choose Participants" ), colorChoices );
if( wxID_OK != multiChoiceDialog.ShowModal() )
return;
wxArrayInt selections = multiChoiceDialog.GetSelections();
if( selections.Count() < 2 )
return;
int participants = 0;
for( wxArrayInt::iterator iter = selections.begin(); iter != selections.end(); iter++ )
{
int color = *iter + 1;
participants |= 1 << color;
}
wxScopedPtr< Server > serverPtr;
serverPtr.reset( new Server( participants ) );
unsigned short port = ( unsigned short )wxGetNumberFromUser( wxT( "On what port should the server listen?" ), wxT( "Port:" ), wxT( "Choose Port" ), 3000, 3000, 5000, this );
if( !serverPtr->Initialize( port ) )
return;
server = serverPtr.release();
wxGetApp().SetServer( server );
wxMessageBox( wxT( "Your game server is online and running!" ), wxT( "Server Initialization Success" ), wxOK | wxCENTRE, this );
}
//=====================================================================================
void Frame::OnJoinGame( wxCommandEvent& event )
{
Client* client = wxGetApp().GetClient();
if( client )
return;
wxString addressString = wxT( "127.0.0.1:3000" );
wxTextEntryDialog textEntryDialog( this, wxT( "Please enter the address of the host with port number." ), wxT( "Enter Address Of Host" ), addressString );
if( wxID_OK != textEntryDialog.ShowModal() )
return;
wxStringTokenizer stringTokenizer( addressString, ":" );
wxString ipAddressString, portString;
if( !stringTokenizer.HasMoreTokens() )
return;
ipAddressString = stringTokenizer.GetNextToken();
if( !stringTokenizer.HasMoreTokens() )
return;
portString = stringTokenizer.GetNextToken();
unsigned long port;
if( !portString.ToULong( &port ) )
return;
wxIPV4address address;
if( !address.Hostname( ipAddressString ) )
return;
address.Service( ( unsigned short )port );
wxArrayString typeChoices;
typeChoices.Add( "Human" );
typeChoices.Add( "Computer" );
wxSingleChoiceDialog singleChoiceDialog( this, wxT( "Will this be a human or computer client?" ), wxT( "Choose Client Type" ), typeChoices );
if( wxID_OK != singleChoiceDialog.ShowModal() )
return;
Client::Type clientType = Client::HUMAN;
wxString selection = singleChoiceDialog.GetStringSelection();
if( selection == wxT( "Computer" ) )
clientType = Client::COMPUTER;
wxScopedPtr< Client > clientPtr;
clientPtr.reset( new Client( clientType ) );
if( !clientPtr->Connect( address ) )
return;
client = clientPtr.release();
wxGetApp().SetClient( client );
}
//=====================================================================================
void Frame::OnLeaveGame( wxCommandEvent& event )
{
KillClient();
}
//=====================================================================================
void Frame::OnKillGame( wxCommandEvent& event )
{
KillServer();
}
//=====================================================================================
void Frame::OnExit( wxCommandEvent& event )
{
Close( true );
}
//=====================================================================================
void Frame::KillServer( void )
{
Server* server = wxGetApp().GetServer();
if( server )
{
server->Finalize();
delete server;
wxGetApp().SetServer(0);
}
}
//=====================================================================================
void Frame::KillClient( void )
{
Client* client = wxGetApp().GetClient();
if( client )
{
delete client;
wxGetApp().SetClient(0);
}
}
//=====================================================================================
void Frame::OnClose( wxCloseEvent& event )
{
KillServer();
KillClient();
event.Skip();
}
//=====================================================================================
void Frame::OnToggleSound( wxCommandEvent& event )
{
wxGetApp().GetSound()->Enable( !wxGetApp().GetSound()->IsEnabled() );
}
//=====================================================================================
void Frame::OnToggleEffect( wxCommandEvent& event )
{
switch( event.GetId() )
{
case ID_DoinkEffect:
{
wxGetApp().soundEffect = "Doink";
break;
}
case ID_FartEffect:
{
wxGetApp().soundEffect = "Fart";
break;
}
case ID_HiyawEffect:
{
wxGetApp().soundEffect = "Hiyaw";
break;
}
}
}
//=====================================================================================
void Frame::OnAbout( wxCommandEvent& event )
{
wxAboutDialogInfo aboutDialogInfo;
aboutDialogInfo.SetName( wxT( "Chinese Checkers" ) );
aboutDialogInfo.SetVersion( wxT( "1.0" ) );
aboutDialogInfo.SetDescription( wxT( "This program is free software and distributed under the MIT license." ) );
aboutDialogInfo.SetCopyright( wxT( "Copyright (C) 2013 Spencer T. Parkin <spencer.parkin@disney.com>" ) );
wxAboutBox( aboutDialogInfo );
}
//=====================================================================================
void Frame::OnUpdateMenuItemUI( wxUpdateUIEvent& event )
{
switch( event.GetId() )
{
case ID_JoinGame:
{
event.Enable( wxGetApp().GetClient() ? false : true );
break;
}
case ID_HostGame:
{
event.Enable( wxGetApp().GetServer() ? false : true );
break;
}
case ID_LeaveGame:
{
event.Enable( wxGetApp().GetClient() ? true : false );
break;
}
case ID_KillGame:
{
event.Enable( wxGetApp().GetServer() ? true : false );
break;
}
case ID_ToggleSound:
{
if( !wxGetApp().GetSound()->IsSetup() )
event.Enable( false );
else
{
event.Enable( true );
event.Check( wxGetApp().GetSound()->IsEnabled() );
}
break;
}
case ID_Effect:
{
event.Enable( wxGetApp().GetSound()->IsSetup() && wxGetApp().GetSound()->IsEnabled() );
break;
}
case ID_DoinkEffect:
{
event.Check( wxGetApp().soundEffect == "Doink" ? true : false );
break;
}
case ID_FartEffect:
{
event.Check( wxGetApp().soundEffect == "Fart" ? true : false );
break;
}
case ID_HiyawEffect:
{
event.Check( wxGetApp().soundEffect == "Hiyaw" ? true : false );
break;
}
}
}
//=====================================================================================
void Frame::OnTimer( wxTimerEvent& event )
{
// This routine was never meant to be re-entrant.
// Re-entrancy could cause a crash due to client or server death.
// If a dialog is put up in this routine, wxWidgets still calls the timer,
// which can cause re-entrancy.
static bool inOnTimer = false;
if( inOnTimer )
return;
inOnTimer = true;
Server* server = wxGetApp().GetServer();
if( server && !server->Run() )
KillServer();
Client* client = wxGetApp().GetClient();
if( client )
{
if( !client->Run() )
{
KillClient();
wxMessageBox( wxT( "We have lost our connection with the server, possibly because the game server has gone down." ), wxT( "Connection Lost" ), wxOK | wxCENTRE, wxGetApp().GetFrame() );
}
else
{
client->Animate( canvas->FrameRate() );
if( continuousRefresh )
canvas->Refresh();
}
}
inOnTimer = false;
}
//=====================================================================================
void Frame::OnActivate( wxActivateEvent& event )
{
continuousRefresh = event.GetActive();
}
//=====================================================================================
wxStatusBar* Frame::GetStatusBar( void )
{
return statusBar;
}
// ChiCheFrame.cpp
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "astimportshandler.h"
#include "asttools.h"
#include "builtindeclarations.h"
#include "filecontext.h"
#include "itemreadervisitorstate.h"
#include "jsextensions/jsextensions.h"
#include <logging/logger.h>
#include <logging/translator.h>
#include <parser/qmljsast_p.h>
#include <tools/error.h>
#include <tools/fileinfo.h>
#include <tools/qttools.h>
#include <tools/version.h>
#include <QDirIterator>
namespace qbs {
namespace Internal {
ASTImportsHandler::ASTImportsHandler(ItemReaderVisitorState &visitorState, Logger &logger,
const FileContextPtr &file)
: m_visitorState(visitorState)
, m_logger(logger)
, m_file(file)
, m_directory(FileInfo::path(m_file->filePath()))
{
}
void ASTImportsHandler::handleImports(const QbsQmlJS::AST::UiImportList *uiImportList)
{
foreach (const QString &searchPath, m_file->searchPaths())
collectPrototypes(searchPath + QLatin1String("/imports"), QString());
// files in the same directory are available as prototypes
collectPrototypes(m_directory, QString());
for (const auto *it = uiImportList; it; it = it->next)
handleImport(it->import);
for (auto it = m_jsImports.constBegin(); it != m_jsImports.constEnd(); ++it)
m_file->addJsImport(it.value());
}
void ASTImportsHandler::handleImport(const QbsQmlJS::AST::UiImport *import)
{
QStringList importUri;
bool isBase = false;
if (import->importUri) {
importUri = toStringList(import->importUri);
isBase = (importUri.size() == 1 && importUri.first() == QLatin1String("qbs"))
|| (importUri.size() == 2 && importUri.first() == QLatin1String("qbs")
&& importUri.last() == QLatin1String("base"));
if (isBase) {
checkImportVersion(import->versionToken);
} else if (import->versionToken.length) {
m_logger.printWarning(ErrorInfo(Tr::tr("Superfluous version specification."),
toCodeLocation(m_file->filePath(), import->versionToken)));
}
}
QString as;
if (isBase) {
if (Q_UNLIKELY(!import->importId.isNull())) {
throw ErrorInfo(Tr::tr("Import of qbs.base must have no 'as <Name>'"),
toCodeLocation(m_file->filePath(), import->importIdToken));
}
} else {
if (importUri.count() == 2 && importUri.first() == QLatin1String("qbs")) {
const QString extensionName = importUri.last();
if (JsExtensions::hasExtension(extensionName)) {
if (Q_UNLIKELY(!import->importId.isNull())) {
throw ErrorInfo(Tr::tr("Import of built-in extension '%1' "
"must not have 'as' specifier.").arg(extensionName));
}
if (Q_UNLIKELY(m_file->jsExtensions().contains(extensionName))) {
m_logger.printWarning(Tr::tr("Built-in extension '%1' already "
"imported.").arg(extensionName));
} else {
m_file->addJsExtension(extensionName);
}
return;
}
}
if (import->importId.isNull()) {
if (!import->fileName.isNull()) {
throw ErrorInfo(Tr::tr("File imports require 'as <Name>'"),
toCodeLocation(m_file->filePath(), import->importToken));
}
if (importUri.isEmpty()) {
throw ErrorInfo(Tr::tr("Invalid import URI."),
toCodeLocation(m_file->filePath(), import->importToken));
}
as = importUri.last();
} else {
as = import->importId.toString();
}
if (Q_UNLIKELY(m_importAsNames.contains(as))) {
throw ErrorInfo(Tr::tr("Cannot import into the same name more than once."),
toCodeLocation(m_file->filePath(), import->importIdToken));
}
if (Q_UNLIKELY(JsExtensions::hasExtension(as)))
throw ErrorInfo(Tr::tr("Cannot reuse the name of built-in extension '%1'.").arg(as));
m_importAsNames.insert(as);
}
if (!import->fileName.isNull()) {
QString filePath = FileInfo::resolvePath(m_directory, import->fileName.toString());
QFileInfo fi(filePath);
if (Q_UNLIKELY(!fi.exists()))
throw ErrorInfo(Tr::tr("Cannot find imported file %0.").arg(filePath),
CodeLocation(m_file->filePath(), import->fileNameToken.startLine,
import->fileNameToken.startColumn));
filePath = fi.canonicalFilePath();
if (fi.isDir()) {
collectPrototypesAndJsCollections(filePath, as,
toCodeLocation(m_file->filePath(), import->fileNameToken));
} else {
if (filePath.endsWith(QLatin1String(".js"), Qt::CaseInsensitive)) {
JsImport &jsImport = m_jsImports[as];
jsImport.scopeName = as;
jsImport.filePaths.append(filePath);
jsImport.location
= toCodeLocation(m_file->filePath(), import->firstSourceLocation());
} else if (filePath.endsWith(QLatin1String(".qbs"), Qt::CaseInsensitive)) {
m_typeNameToFile.insert(QStringList(as), filePath);
} else {
throw ErrorInfo(Tr::tr("Can only import .qbs and .js files"),
CodeLocation(m_file->filePath(), import->fileNameToken.startLine,
import->fileNameToken.startColumn));
}
}
} else if (!importUri.isEmpty()) {
const QString importPath = isBase
? QLatin1String("qbs/base") : importUri.join(QDir::separator());
bool found = m_typeNameToFile.contains(importUri);
if (!found) {
foreach (const QString &searchPath, m_file->searchPaths()) {
const QFileInfo fi(FileInfo::resolvePath(
FileInfo::resolvePath(searchPath,
QLatin1String("imports")),
importPath));
if (fi.isDir()) {
// ### versioning, qbsdir file, etc.
const QString &resultPath = fi.absoluteFilePath();
collectPrototypesAndJsCollections(resultPath, as,
toCodeLocation(m_file->filePath(), import->importIdToken));
found = true;
break;
}
}
}
if (Q_UNLIKELY(!found)) {
throw ErrorInfo(Tr::tr("import %1 not found")
.arg(importUri.join(QLatin1Char('.'))),
toCodeLocation(m_file->filePath(), import->fileNameToken));
}
}
}
Version ASTImportsHandler::readImportVersion(const QString &str, const CodeLocation &location)
{
const Version v = Version::fromString(str);
if (Q_UNLIKELY(!v.isValid()))
throw ErrorInfo(Tr::tr("Cannot parse version number in import statement."), location);
if (Q_UNLIKELY(v.patchLevel() != 0)) {
throw ErrorInfo(Tr::tr("Version number in import statement cannot have more than "
"two components."), location);
}
return v;
}
bool ASTImportsHandler::addPrototype(const QString &fileName, const QString &filePath,
const QString &as, bool needsCheck)
{
if (needsCheck && fileName.size() <= 4)
return false;
const QString componentName = fileName.left(fileName.size() - 4);
// ### validate componentName
if (needsCheck && !componentName.at(0).isUpper())
return false;
QStringList prototypeName;
if (!as.isEmpty())
prototypeName.append(as);
prototypeName.append(componentName);
m_typeNameToFile.insert(prototypeName, filePath);
return true;
}
void ASTImportsHandler::checkImportVersion(const QbsQmlJS::AST::SourceLocation &versionToken) const
{
if (!versionToken.length)
return;
const QString importVersionString
= m_file->content().mid(versionToken.offset, versionToken.length);
const Version importVersion = readImportVersion(importVersionString,
toCodeLocation(m_file->filePath(), versionToken));
if (Q_UNLIKELY(importVersion != BuiltinDeclarations::instance().languageVersion()))
throw ErrorInfo(Tr::tr("Incompatible qbs language version %1. This is version %2.").arg(
importVersionString,
BuiltinDeclarations::instance().languageVersion().toString()),
toCodeLocation(m_file->filePath(), versionToken));
}
void ASTImportsHandler::collectPrototypes(const QString &path, const QString &as)
{
QStringList fileNames; // Yes, file *names*.
if (m_visitorState.findDirectoryEntries(path, &fileNames)) {
foreach (const QString &fileName, fileNames)
addPrototype(fileName, path + QLatin1Char('/') + fileName, as, false);
return;
}
QDirIterator dirIter(path, QStringList(QLatin1String("*.qbs")));
while (dirIter.hasNext()) {
const QString filePath = dirIter.next();
const QString fileName = dirIter.fileName();
if (addPrototype(fileName, filePath, as, true))
fileNames << fileName;
}
m_visitorState.cacheDirectoryEntries(path, fileNames);
}
void ASTImportsHandler::collectPrototypesAndJsCollections(const QString &path, const QString &as,
const CodeLocation &location)
{
collectPrototypes(path, as);
QDirIterator dirIter(path, QStringList(QLatin1String("*.js")));
while (dirIter.hasNext()) {
dirIter.next();
JsImport &jsImport = m_jsImports[as];
if (jsImport.scopeName.isNull()) {
jsImport.scopeName = as;
jsImport.location = location;
}
jsImport.filePaths.append(dirIter.filePath());
}
}
} // namespace Internal
} // namespace qbs
<commit_msg>Use native separators in error message.<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "astimportshandler.h"
#include "asttools.h"
#include "builtindeclarations.h"
#include "filecontext.h"
#include "itemreadervisitorstate.h"
#include "jsextensions/jsextensions.h"
#include <logging/logger.h>
#include <logging/translator.h>
#include <parser/qmljsast_p.h>
#include <tools/error.h>
#include <tools/fileinfo.h>
#include <tools/qttools.h>
#include <tools/version.h>
#include <QDirIterator>
namespace qbs {
namespace Internal {
ASTImportsHandler::ASTImportsHandler(ItemReaderVisitorState &visitorState, Logger &logger,
const FileContextPtr &file)
: m_visitorState(visitorState)
, m_logger(logger)
, m_file(file)
, m_directory(FileInfo::path(m_file->filePath()))
{
}
void ASTImportsHandler::handleImports(const QbsQmlJS::AST::UiImportList *uiImportList)
{
foreach (const QString &searchPath, m_file->searchPaths())
collectPrototypes(searchPath + QLatin1String("/imports"), QString());
// files in the same directory are available as prototypes
collectPrototypes(m_directory, QString());
for (const auto *it = uiImportList; it; it = it->next)
handleImport(it->import);
for (auto it = m_jsImports.constBegin(); it != m_jsImports.constEnd(); ++it)
m_file->addJsImport(it.value());
}
void ASTImportsHandler::handleImport(const QbsQmlJS::AST::UiImport *import)
{
QStringList importUri;
bool isBase = false;
if (import->importUri) {
importUri = toStringList(import->importUri);
isBase = (importUri.size() == 1 && importUri.first() == QLatin1String("qbs"))
|| (importUri.size() == 2 && importUri.first() == QLatin1String("qbs")
&& importUri.last() == QLatin1String("base"));
if (isBase) {
checkImportVersion(import->versionToken);
} else if (import->versionToken.length) {
m_logger.printWarning(ErrorInfo(Tr::tr("Superfluous version specification."),
toCodeLocation(m_file->filePath(), import->versionToken)));
}
}
QString as;
if (isBase) {
if (Q_UNLIKELY(!import->importId.isNull())) {
throw ErrorInfo(Tr::tr("Import of qbs.base must have no 'as <Name>'"),
toCodeLocation(m_file->filePath(), import->importIdToken));
}
} else {
if (importUri.count() == 2 && importUri.first() == QLatin1String("qbs")) {
const QString extensionName = importUri.last();
if (JsExtensions::hasExtension(extensionName)) {
if (Q_UNLIKELY(!import->importId.isNull())) {
throw ErrorInfo(Tr::tr("Import of built-in extension '%1' "
"must not have 'as' specifier.").arg(extensionName));
}
if (Q_UNLIKELY(m_file->jsExtensions().contains(extensionName))) {
m_logger.printWarning(Tr::tr("Built-in extension '%1' already "
"imported.").arg(extensionName));
} else {
m_file->addJsExtension(extensionName);
}
return;
}
}
if (import->importId.isNull()) {
if (!import->fileName.isNull()) {
throw ErrorInfo(Tr::tr("File imports require 'as <Name>'"),
toCodeLocation(m_file->filePath(), import->importToken));
}
if (importUri.isEmpty()) {
throw ErrorInfo(Tr::tr("Invalid import URI."),
toCodeLocation(m_file->filePath(), import->importToken));
}
as = importUri.last();
} else {
as = import->importId.toString();
}
if (Q_UNLIKELY(m_importAsNames.contains(as))) {
throw ErrorInfo(Tr::tr("Cannot import into the same name more than once."),
toCodeLocation(m_file->filePath(), import->importIdToken));
}
if (Q_UNLIKELY(JsExtensions::hasExtension(as)))
throw ErrorInfo(Tr::tr("Cannot reuse the name of built-in extension '%1'.").arg(as));
m_importAsNames.insert(as);
}
if (!import->fileName.isNull()) {
QString filePath = FileInfo::resolvePath(m_directory, import->fileName.toString());
QFileInfo fi(filePath);
if (Q_UNLIKELY(!fi.exists()))
throw ErrorInfo(Tr::tr("Cannot find imported file %0.")
.arg(QDir::toNativeSeparators(filePath)),
CodeLocation(m_file->filePath(), import->fileNameToken.startLine,
import->fileNameToken.startColumn));
filePath = fi.canonicalFilePath();
if (fi.isDir()) {
collectPrototypesAndJsCollections(filePath, as,
toCodeLocation(m_file->filePath(), import->fileNameToken));
} else {
if (filePath.endsWith(QLatin1String(".js"), Qt::CaseInsensitive)) {
JsImport &jsImport = m_jsImports[as];
jsImport.scopeName = as;
jsImport.filePaths.append(filePath);
jsImport.location
= toCodeLocation(m_file->filePath(), import->firstSourceLocation());
} else if (filePath.endsWith(QLatin1String(".qbs"), Qt::CaseInsensitive)) {
m_typeNameToFile.insert(QStringList(as), filePath);
} else {
throw ErrorInfo(Tr::tr("Can only import .qbs and .js files"),
CodeLocation(m_file->filePath(), import->fileNameToken.startLine,
import->fileNameToken.startColumn));
}
}
} else if (!importUri.isEmpty()) {
const QString importPath = isBase
? QLatin1String("qbs/base") : importUri.join(QDir::separator());
bool found = m_typeNameToFile.contains(importUri);
if (!found) {
foreach (const QString &searchPath, m_file->searchPaths()) {
const QFileInfo fi(FileInfo::resolvePath(
FileInfo::resolvePath(searchPath,
QLatin1String("imports")),
importPath));
if (fi.isDir()) {
// ### versioning, qbsdir file, etc.
const QString &resultPath = fi.absoluteFilePath();
collectPrototypesAndJsCollections(resultPath, as,
toCodeLocation(m_file->filePath(), import->importIdToken));
found = true;
break;
}
}
}
if (Q_UNLIKELY(!found)) {
throw ErrorInfo(Tr::tr("import %1 not found")
.arg(importUri.join(QLatin1Char('.'))),
toCodeLocation(m_file->filePath(), import->fileNameToken));
}
}
}
Version ASTImportsHandler::readImportVersion(const QString &str, const CodeLocation &location)
{
const Version v = Version::fromString(str);
if (Q_UNLIKELY(!v.isValid()))
throw ErrorInfo(Tr::tr("Cannot parse version number in import statement."), location);
if (Q_UNLIKELY(v.patchLevel() != 0)) {
throw ErrorInfo(Tr::tr("Version number in import statement cannot have more than "
"two components."), location);
}
return v;
}
bool ASTImportsHandler::addPrototype(const QString &fileName, const QString &filePath,
const QString &as, bool needsCheck)
{
if (needsCheck && fileName.size() <= 4)
return false;
const QString componentName = fileName.left(fileName.size() - 4);
// ### validate componentName
if (needsCheck && !componentName.at(0).isUpper())
return false;
QStringList prototypeName;
if (!as.isEmpty())
prototypeName.append(as);
prototypeName.append(componentName);
m_typeNameToFile.insert(prototypeName, filePath);
return true;
}
void ASTImportsHandler::checkImportVersion(const QbsQmlJS::AST::SourceLocation &versionToken) const
{
if (!versionToken.length)
return;
const QString importVersionString
= m_file->content().mid(versionToken.offset, versionToken.length);
const Version importVersion = readImportVersion(importVersionString,
toCodeLocation(m_file->filePath(), versionToken));
if (Q_UNLIKELY(importVersion != BuiltinDeclarations::instance().languageVersion()))
throw ErrorInfo(Tr::tr("Incompatible qbs language version %1. This is version %2.").arg(
importVersionString,
BuiltinDeclarations::instance().languageVersion().toString()),
toCodeLocation(m_file->filePath(), versionToken));
}
void ASTImportsHandler::collectPrototypes(const QString &path, const QString &as)
{
QStringList fileNames; // Yes, file *names*.
if (m_visitorState.findDirectoryEntries(path, &fileNames)) {
foreach (const QString &fileName, fileNames)
addPrototype(fileName, path + QLatin1Char('/') + fileName, as, false);
return;
}
QDirIterator dirIter(path, QStringList(QLatin1String("*.qbs")));
while (dirIter.hasNext()) {
const QString filePath = dirIter.next();
const QString fileName = dirIter.fileName();
if (addPrototype(fileName, filePath, as, true))
fileNames << fileName;
}
m_visitorState.cacheDirectoryEntries(path, fileNames);
}
void ASTImportsHandler::collectPrototypesAndJsCollections(const QString &path, const QString &as,
const CodeLocation &location)
{
collectPrototypes(path, as);
QDirIterator dirIter(path, QStringList(QLatin1String("*.js")));
while (dirIter.hasNext()) {
dirIter.next();
JsImport &jsImport = m_jsImports[as];
if (jsImport.scopeName.isNull()) {
jsImport.scopeName = as;
jsImport.location = location;
}
jsImport.filePaths.append(dirIter.filePath());
}
}
} // namespace Internal
} // namespace qbs
<|endoftext|> |
<commit_before>// DOC: https://tools.ietf.org/html/rfc3550#appendix-A.1
#define MS_CLASS "RTC::RtpStream"
// #define MS_LOG_DEV
#include "RTC/RtpStream.h"
#include "DepLibUV.h"
#include "Logger.h"
#define MIN_SEQUENTIAL 2
#define MAX_DROPOUT 3000
#define MAX_MISORDER 100
#define RTP_SEQ_MOD (1<<16)
namespace RTC
{
/* Instance methods. */
RtpStream::RtpStream(uint32_t clockRate, size_t bufferSize) :
clockRate(clockRate),
storage(bufferSize)
{
MS_TRACE();
}
RtpStream::~RtpStream()
{
MS_TRACE();
// Clear buffer.
CleanBuffer();
}
bool RtpStream::ReceivePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
uint16_t seq = packet->GetSequenceNumber();
// If this is the first packet seen, initialize stuff.
if (!this->started)
{
this->started = true;
InitSeq(seq);
this->max_seq = seq - 1;
this->probation = MIN_SEQUENTIAL;
}
// If not a valid packet ignore it.
if (!UpdateSeq(seq))
{
MS_WARN_TAG(rtp, "invalid packet [seq:%" PRIu16 "]", packet->GetSequenceNumber());
return false;
}
// If bufferSize was given, store the packet into the buffer.
if (this->storage.size() > 0)
{
StorePacket(packet);
// TODO: TMP
// Dump();
}
// Calculate Jitter.
CalculateJitter(packet->GetTimestamp());
return true;
}
// This method looks for the requested RTP packets and inserts them into the
// given container (and set to null the next container position).
void RtpStream::RequestRtpRetransmission(uint16_t seq, uint16_t bitmask, std::vector<RTC::RtpPacket*>& container)
{
MS_TRACE();
// 17: 16 bit mask + the initial sequence number.
static size_t maxRequestedPackets = 17;
// If the buffer is empty, just return.
if (this->buffer.size() == 0)
return;
// Convert the given sequence numbers to 32 bits.
uint32_t first_seq32 = (uint32_t)seq + this->cycles;
uint32_t last_seq32 = first_seq32 + maxRequestedPackets - 1;
size_t container_idx = 0;
// Number of requested packets cannot be greater than the container size - 1.
MS_ASSERT(container.size() - 1 >= maxRequestedPackets, "RtpPacket container is too small");
auto buffer_it = this->buffer.begin();
auto buffer_it_r = this->buffer.rbegin();
uint32_t buffer_first_seq32 = (*buffer_it).seq32;
uint32_t buffer_last_seq32 = (*buffer_it_r).seq32;
// Requested packet range not found.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
{
// Let's try with sequence numbers in the previous 16 cycle.
if (this->cycles > 0)
{
first_seq32 -= RTP_SEQ_MOD;
last_seq32 -= RTP_SEQ_MOD;
// Try again.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
return;
}
// Otherwise just return.
else
{
return;
}
}
// Look for each requested packet.
uint32_t seq32 = first_seq32;
bool requested = true;
do
{
if (requested)
{
for (; buffer_it != this->buffer.end(); ++buffer_it)
{
auto current_seq32 = (*buffer_it).seq32;
// Found.
if (current_seq32 == seq32)
{
auto current_packet = (*buffer_it).packet;
// Store the packet in the container and then increment its index.
container[container_idx++] = current_packet;
// Exit the loop.
break;
}
}
}
requested = (bitmask & 1) ? true : false;
bitmask >>= 1;
++seq32;
}
while (bitmask != 0);
// Set the next container element to null.
container[container_idx] = nullptr;
}
void RtpStream::InitSeq(uint16_t seq)
{
MS_TRACE();
// Initialize/reset RTP counters.
this->base_seq = seq;
this->max_seq = seq;
this->bad_seq = RTP_SEQ_MOD + 1; // So seq == bad_seq is false.
this->cycles = 0;
this->received = 0;
this->received_prior = 0;
this->expected_prior = 0;
// Clean buffer.
CleanBuffer();
}
bool RtpStream::UpdateSeq(uint16_t seq)
{
MS_TRACE();
uint16_t udelta = seq - this->max_seq;
/*
* Source is not valid until MIN_SEQUENTIAL packets with
* sequential sequence numbers have been received.
*/
if (this->probation)
{
// Packet is in sequence.
if (seq == this->max_seq + 1)
{
this->probation--;
this->max_seq = seq;
if (this->probation == 0)
{
InitSeq(seq);
this->received++;
return true;
}
}
else
{
this->probation = MIN_SEQUENTIAL - 1;
this->max_seq = seq;
}
return false;
}
else if (udelta < MAX_DROPOUT)
{
// In order, with permissible gap.
if (seq < this->max_seq)
{
// Sequence number wrapped: count another 64K cycle.
this->cycles += RTP_SEQ_MOD;
}
this->max_seq = seq;
}
else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER)
{
// The sequence number made a very large jump.
if (seq == this->bad_seq)
{
/*
* Two sequential packets -- assume that the other side
* restarted without telling us so just re-sync
* (i.e., pretend this was the first packet).
*/
InitSeq(seq);
}
else
{
this->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
return false;
}
}
else
{
// Duplicate or reordered packet.
// NOTE: This would never happen because libsrtp rejects duplicated packets.
}
this->received++;
return true;
}
void RtpStream::CleanBuffer()
{
MS_TRACE();
// Delete cloned packets.
for (auto& buffer_item : this->buffer)
{
delete buffer_item.packet;
}
// Clear list.
this->buffer.clear();
}
inline
void RtpStream::StorePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
// Sum the packet seq number and the number of 16 bits cycles.
uint32_t packet_seq32 = (uint32_t)packet->GetSequenceNumber() + this->cycles;
BufferItem buffer_item;
buffer_item.seq32 = packet_seq32;
// If empty do it easy.
if (this->buffer.size() == 0)
{
auto store = this->storage[0].store;
buffer_item.packet = packet->Clone(store);
this->buffer.push_back(buffer_item);
return;
}
// Otherwise, do the stuff.
Buffer::iterator new_buffer_it;
uint8_t* store = nullptr;
// Iterate the buffer in reverse order and find the proper place to store the
// packet.
auto buffer_it_r = this->buffer.rbegin();
for (; buffer_it_r != this->buffer.rend(); ++buffer_it_r)
{
auto current_seq32 = (*buffer_it_r).seq32;
if (packet_seq32 > current_seq32)
{
// Get a forward iterator pointing to the same element.
auto it = buffer_it_r.base();
new_buffer_it = this->buffer.insert(it, buffer_item);
// Exit the loop.
break;
}
}
// If the packet was older than anything in the buffer, just ignore it.
// NOTE: This should never happen.
if (buffer_it_r == this->buffer.rend())
{
MS_WARN_TAG(rtp, "packet is older than anything in the buffer, ignoring it");
return;
}
// If the buffer is not full use the next free storage item.
if (this->buffer.size() - 1 < this->storage.size())
{
store = this->storage[this->buffer.size() - 1].store;
}
// Otherwise remove the first packet of the buffer and replace its storage area.
else
{
auto& first_buffer_item = *(this->buffer.begin());
auto first_packet = first_buffer_item.packet;
// Store points to the store used by the first packet.
store = (uint8_t*)first_packet->GetData();
// Free the first packet.
delete first_packet;
// Remove the first element in the list.
this->buffer.pop_front();
}
// Update the new buffer item so it points to the cloned packed.
(*new_buffer_it).packet = packet->Clone(store);
}
void RtpStream::CalculateJitter(uint32_t rtpTimestamp)
{
if (!this->clockRate)
return;
int transit = DepLibUV::GetTime() - (rtpTimestamp * 1000 / this->clockRate);
int d = transit - this->transit;
this->transit = transit;
if (d < 0) d = -d;
this->jitter += (1./16.) * ((double)d - this->jitter);
}
RTC::RTCP::ReceiverReport* RtpStream::GetRtcpReceiverReport()
{
RTC::RTCP::ReceiverReport* report = new RTC::RTCP::ReceiverReport();
// Calculate Packets Expected and Lost.
uint32_t expected = (this->cycles + this->max_seq) - this->base_seq + 1;
int32_t total_lost = expected - this->received;
report->SetTotalLost(total_lost);
// Calculate Fraction Lost.
uint32_t expected_interval = expected - this->expected_prior;
this->expected_prior = expected;
uint32_t received_interval = this->received - this->received_prior;
this->received_prior = this->received;
uint32_t lost_interval = expected_interval - received_interval;
uint8_t fraction_lost;
if (expected_interval == 0 || lost_interval <= 0)
fraction_lost = 0;
else
fraction_lost = (lost_interval << 8) / expected_interval;
report->SetFractionLost(fraction_lost);
// Fill the rest of the report.
report->SetLastSeq((uint32_t)this->max_seq + this->cycles);
report->SetJitter(this->jitter);
if (this->last_sr_received)
{
// Get delay in milliseconds.
uint32_t delayMs = (DepLibUV::GetTime() - this->last_sr_received);
// Express delay in units of 1/65536 seconds.
uint32_t dlsr = (delayMs / 1000) << 16;
dlsr |= (uint32_t)((delayMs % 1000) * 65536 / 1000);
report->SetDelaySinceLastSenderReport(dlsr);
report->SetLastSenderReport(this->last_sr_timestamp);
}
else
{
report->SetDelaySinceLastSenderReport(0);
report->SetLastSenderReport(0);
}
return report;
}
void RtpStream::ReceiveRtcpSenderReport(RTC::RTCP::SenderReport* report)
{
this->last_sr_received = DepLibUV::GetTime();
this->last_sr_timestamp = htonl(report->GetNtpSec()) << 16;
this->last_sr_timestamp += htonl(report->GetNtpFrac()) >> 16;
}
// TODO: TMP
void RtpStream::Dump()
{
MS_TRACE();
MS_DEBUG_TAG(rtp, "<RtpStream>");
MS_DEBUG_TAG(rtp, " [buffer.size:%zu, storage.size:%zu]", this->buffer.size(), this->storage.size());
for (auto& buffer_item : this->buffer)
{
auto packet = buffer_item.packet;
MS_DEBUG_TAG(rtp, " packet [seq:%" PRIu16 ", seq32:%" PRIu32 "]", packet->GetSequenceNumber(), buffer_item.seq32);
}
MS_DEBUG_TAG(rtp, "</RtpStream>");
}
}
<commit_msg>Rtcp: fix typo on RR fraction lost calculation<commit_after>// DOC: https://tools.ietf.org/html/rfc3550#appendix-A.1
#define MS_CLASS "RTC::RtpStream"
// #define MS_LOG_DEV
#include "RTC/RtpStream.h"
#include "DepLibUV.h"
#include "Logger.h"
#define MIN_SEQUENTIAL 2
#define MAX_DROPOUT 3000
#define MAX_MISORDER 100
#define RTP_SEQ_MOD (1<<16)
namespace RTC
{
/* Instance methods. */
RtpStream::RtpStream(uint32_t clockRate, size_t bufferSize) :
clockRate(clockRate),
storage(bufferSize)
{
MS_TRACE();
}
RtpStream::~RtpStream()
{
MS_TRACE();
// Clear buffer.
CleanBuffer();
}
bool RtpStream::ReceivePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
uint16_t seq = packet->GetSequenceNumber();
// If this is the first packet seen, initialize stuff.
if (!this->started)
{
this->started = true;
InitSeq(seq);
this->max_seq = seq - 1;
this->probation = MIN_SEQUENTIAL;
}
// If not a valid packet ignore it.
if (!UpdateSeq(seq))
{
MS_WARN_TAG(rtp, "invalid packet [seq:%" PRIu16 "]", packet->GetSequenceNumber());
return false;
}
// If bufferSize was given, store the packet into the buffer.
if (this->storage.size() > 0)
{
StorePacket(packet);
// TODO: TMP
// Dump();
}
// Calculate Jitter.
CalculateJitter(packet->GetTimestamp());
return true;
}
// This method looks for the requested RTP packets and inserts them into the
// given container (and set to null the next container position).
void RtpStream::RequestRtpRetransmission(uint16_t seq, uint16_t bitmask, std::vector<RTC::RtpPacket*>& container)
{
MS_TRACE();
// 17: 16 bit mask + the initial sequence number.
static size_t maxRequestedPackets = 17;
// If the buffer is empty, just return.
if (this->buffer.size() == 0)
return;
// Convert the given sequence numbers to 32 bits.
uint32_t first_seq32 = (uint32_t)seq + this->cycles;
uint32_t last_seq32 = first_seq32 + maxRequestedPackets - 1;
size_t container_idx = 0;
// Number of requested packets cannot be greater than the container size - 1.
MS_ASSERT(container.size() - 1 >= maxRequestedPackets, "RtpPacket container is too small");
auto buffer_it = this->buffer.begin();
auto buffer_it_r = this->buffer.rbegin();
uint32_t buffer_first_seq32 = (*buffer_it).seq32;
uint32_t buffer_last_seq32 = (*buffer_it_r).seq32;
// Requested packet range not found.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
{
// Let's try with sequence numbers in the previous 16 cycle.
if (this->cycles > 0)
{
first_seq32 -= RTP_SEQ_MOD;
last_seq32 -= RTP_SEQ_MOD;
// Try again.
if (first_seq32 > buffer_last_seq32 || last_seq32 < buffer_first_seq32)
return;
}
// Otherwise just return.
else
{
return;
}
}
// Look for each requested packet.
uint32_t seq32 = first_seq32;
bool requested = true;
do
{
if (requested)
{
for (; buffer_it != this->buffer.end(); ++buffer_it)
{
auto current_seq32 = (*buffer_it).seq32;
// Found.
if (current_seq32 == seq32)
{
auto current_packet = (*buffer_it).packet;
// Store the packet in the container and then increment its index.
container[container_idx++] = current_packet;
// Exit the loop.
break;
}
}
}
requested = (bitmask & 1) ? true : false;
bitmask >>= 1;
++seq32;
}
while (bitmask != 0);
// Set the next container element to null.
container[container_idx] = nullptr;
}
void RtpStream::InitSeq(uint16_t seq)
{
MS_TRACE();
// Initialize/reset RTP counters.
this->base_seq = seq;
this->max_seq = seq;
this->bad_seq = RTP_SEQ_MOD + 1; // So seq == bad_seq is false.
this->cycles = 0;
this->received = 0;
this->received_prior = 0;
this->expected_prior = 0;
// Clean buffer.
CleanBuffer();
}
bool RtpStream::UpdateSeq(uint16_t seq)
{
MS_TRACE();
uint16_t udelta = seq - this->max_seq;
/*
* Source is not valid until MIN_SEQUENTIAL packets with
* sequential sequence numbers have been received.
*/
if (this->probation)
{
// Packet is in sequence.
if (seq == this->max_seq + 1)
{
this->probation--;
this->max_seq = seq;
if (this->probation == 0)
{
InitSeq(seq);
this->received++;
return true;
}
}
else
{
this->probation = MIN_SEQUENTIAL - 1;
this->max_seq = seq;
}
return false;
}
else if (udelta < MAX_DROPOUT)
{
// In order, with permissible gap.
if (seq < this->max_seq)
{
// Sequence number wrapped: count another 64K cycle.
this->cycles += RTP_SEQ_MOD;
}
this->max_seq = seq;
}
else if (udelta <= RTP_SEQ_MOD - MAX_MISORDER)
{
// The sequence number made a very large jump.
if (seq == this->bad_seq)
{
/*
* Two sequential packets -- assume that the other side
* restarted without telling us so just re-sync
* (i.e., pretend this was the first packet).
*/
InitSeq(seq);
}
else
{
this->bad_seq = (seq + 1) & (RTP_SEQ_MOD - 1);
return false;
}
}
else
{
// Duplicate or reordered packet.
// NOTE: This would never happen because libsrtp rejects duplicated packets.
}
this->received++;
return true;
}
void RtpStream::CleanBuffer()
{
MS_TRACE();
// Delete cloned packets.
for (auto& buffer_item : this->buffer)
{
delete buffer_item.packet;
}
// Clear list.
this->buffer.clear();
}
inline
void RtpStream::StorePacket(RTC::RtpPacket* packet)
{
MS_TRACE();
// Sum the packet seq number and the number of 16 bits cycles.
uint32_t packet_seq32 = (uint32_t)packet->GetSequenceNumber() + this->cycles;
BufferItem buffer_item;
buffer_item.seq32 = packet_seq32;
// If empty do it easy.
if (this->buffer.size() == 0)
{
auto store = this->storage[0].store;
buffer_item.packet = packet->Clone(store);
this->buffer.push_back(buffer_item);
return;
}
// Otherwise, do the stuff.
Buffer::iterator new_buffer_it;
uint8_t* store = nullptr;
// Iterate the buffer in reverse order and find the proper place to store the
// packet.
auto buffer_it_r = this->buffer.rbegin();
for (; buffer_it_r != this->buffer.rend(); ++buffer_it_r)
{
auto current_seq32 = (*buffer_it_r).seq32;
if (packet_seq32 > current_seq32)
{
// Get a forward iterator pointing to the same element.
auto it = buffer_it_r.base();
new_buffer_it = this->buffer.insert(it, buffer_item);
// Exit the loop.
break;
}
}
// If the packet was older than anything in the buffer, just ignore it.
// NOTE: This should never happen.
if (buffer_it_r == this->buffer.rend())
{
MS_WARN_TAG(rtp, "packet is older than anything in the buffer, ignoring it");
return;
}
// If the buffer is not full use the next free storage item.
if (this->buffer.size() - 1 < this->storage.size())
{
store = this->storage[this->buffer.size() - 1].store;
}
// Otherwise remove the first packet of the buffer and replace its storage area.
else
{
auto& first_buffer_item = *(this->buffer.begin());
auto first_packet = first_buffer_item.packet;
// Store points to the store used by the first packet.
store = (uint8_t*)first_packet->GetData();
// Free the first packet.
delete first_packet;
// Remove the first element in the list.
this->buffer.pop_front();
}
// Update the new buffer item so it points to the cloned packed.
(*new_buffer_it).packet = packet->Clone(store);
}
void RtpStream::CalculateJitter(uint32_t rtpTimestamp)
{
if (!this->clockRate)
return;
int transit = DepLibUV::GetTime() - (rtpTimestamp * 1000 / this->clockRate);
int d = transit - this->transit;
this->transit = transit;
if (d < 0) d = -d;
this->jitter += (1./16.) * ((double)d - this->jitter);
}
RTC::RTCP::ReceiverReport* RtpStream::GetRtcpReceiverReport()
{
RTC::RTCP::ReceiverReport* report = new RTC::RTCP::ReceiverReport();
// Calculate Packets Expected and Lost.
uint32_t expected = (this->cycles + this->max_seq) - this->base_seq + 1;
int32_t total_lost = expected - this->received;
report->SetTotalLost(total_lost);
// Calculate Fraction Lost.
uint32_t expected_interval = expected - this->expected_prior;
this->expected_prior = expected;
uint32_t received_interval = this->received - this->received_prior;
this->received_prior = this->received;
int32_t lost_interval = expected_interval - received_interval;
uint8_t fraction_lost;
if (expected_interval == 0 || lost_interval <= 0)
fraction_lost = 0;
else
fraction_lost = (lost_interval << 8) / expected_interval;
report->SetFractionLost(fraction_lost);
// Fill the rest of the report.
report->SetLastSeq((uint32_t)this->max_seq + this->cycles);
report->SetJitter(this->jitter);
if (this->last_sr_received)
{
// Get delay in milliseconds.
uint32_t delayMs = (DepLibUV::GetTime() - this->last_sr_received);
// Express delay in units of 1/65536 seconds.
uint32_t dlsr = (delayMs / 1000) << 16;
dlsr |= (uint32_t)((delayMs % 1000) * 65536 / 1000);
report->SetDelaySinceLastSenderReport(dlsr);
report->SetLastSenderReport(this->last_sr_timestamp);
}
else
{
report->SetDelaySinceLastSenderReport(0);
report->SetLastSenderReport(0);
}
return report;
}
void RtpStream::ReceiveRtcpSenderReport(RTC::RTCP::SenderReport* report)
{
this->last_sr_received = DepLibUV::GetTime();
this->last_sr_timestamp = htonl(report->GetNtpSec()) << 16;
this->last_sr_timestamp += htonl(report->GetNtpFrac()) >> 16;
}
// TODO: TMP
void RtpStream::Dump()
{
MS_TRACE();
MS_DEBUG_TAG(rtp, "<RtpStream>");
MS_DEBUG_TAG(rtp, " [buffer.size:%zu, storage.size:%zu]", this->buffer.size(), this->storage.size());
for (auto& buffer_item : this->buffer)
{
auto packet = buffer_item.packet;
MS_DEBUG_TAG(rtp, " packet [seq:%" PRIu16 ", seq32:%" PRIu32 "]", packet->GetSequenceNumber(), buffer_item.seq32);
}
MS_DEBUG_TAG(rtp, "</RtpStream>");
}
}
<|endoftext|> |
<commit_before>#include "zs.hh"
#include "test_util.hh"
int main(){
zs_init();
// traditional macro (extension)
check_e_success("(define tmp-func (lambda (x) `(define ,x ',x)))");
check_e("(tmp-func 'a)", "(define a (quote a))");
check_e_success("(define-syntax tmp-macro (traditional-transformer tmp-func))");
check_e_undef("a");
check_e_success("(tmp-macro a)");
check_e("a", "a");
check_e_success("(define-syntax swap! (traditional-transformer"
"(lambda (x y)"
" (let ((tmp (gensym)))"
" `(let ((,tmp '()))"
" (set! ,tmp ,x) (set! ,x ,y) (set! ,y ,tmp))))))");
check_e_success("(define x 1)");
check_e_success("(define y 2)");
check_e("x", "1");
check_e("y", "2");
check_e_success("(swap! x y)");
check_e("x", "2");
check_e("y", "1");
check_e_success("(define-syntax sc-test-1 (sc-macro-transformer"
"(lambda (form env) (cadr form))))");
check_e("(sc-test-1 (list x y))", "(2 1)");
check_e_success("(swap! x y)");
check_e("x", "1");
check_e("y", "2");
check_e("(sc-test-1 (list x y))", "(2 1)");
check_e_success("(define-syntax sc-test-2 (sc-macro-transformer"
"(lambda (form env)"
" (make-syntactic-closure env () (cadr form)))))");
check_e("(sc-test-2 (list x y))", "(1 2)");
check_e_success("(swap! x y)");
check_e("x", "2");
check_e("y", "1");
check_e("(sc-test-2 (list x y))", "(2 1)");
check_e_success("(define sc-test-3"
" (make-syntactic-closure (interaction-environment) '(x) 'x))");
check_e_success("sc-test-3");
check_e("(eval sc-test-3 (null-environment 5))", "x");
check_e("(identifier? 'a)", "#t");
check_e("(identifier? (make-syntactic-closure (null-environment 5) '() 'a))",
"#t");
check_e("(identifier? \"a\")", "#f");
check_e("(identifier? #\\a)", "#f");
check_e("(identifier? 97)", "#f");
check_e("(identifier? #f)", "#f");
check_e("(identifier? '(a))", "#f");
check_e("(identifier? '#(a))", "#f");
check_e_success(
"(define-syntax push"
" (sc-macro-transformer"
" (lambda (exp env)"
" (let ((item (make-syntactic-closure env '() (cadr exp)))"
" (list (make-syntactic-closure env '() (caddr exp))))"
" `(set! ,list (cons ,item ,list))))))");
check_e_success("(define push-test-lis ())");
check_e("push-test-lis", "()");
check_e_success("(push 1 push-test-lis)");
check_e("push-test-lis", "(1)");
return RESULT;
}
<commit_msg>added test<commit_after>#include "zs.hh"
#include "test_util.hh"
int main(){
zs_init();
// traditional macro
check_e_success("(define tmp-func (lambda (x) `(define ,x ',x)))");
check_e("(tmp-func 'a)", "(define a (quote a))");
check_e_success("(define-syntax tmp-macro (traditional-transformer tmp-func))");
check_e_undef("a");
check_e_success("(tmp-macro a)");
check_e("a", "a");
check_e_success("(define-syntax swap! (traditional-transformer"
"(lambda (x y)"
" (let ((tmp (gensym)))"
" `(let ((,tmp '()))"
" (set! ,tmp ,x) (set! ,x ,y) (set! ,y ,tmp))))))");
check_e_success("(define x 1)");
check_e_success("(define y 2)");
check_e("x", "1");
check_e("y", "2");
check_e_success("(swap! x y)");
check_e("x", "2");
check_e("y", "1");
// syntactic closure
check_e_success("(define-syntax sc-test-1 (sc-macro-transformer"
"(lambda (form env) (cadr form))))");
check_e("(sc-test-1 (list x y))", "(2 1)");
check_e_success("(swap! x y)");
check_e("x", "1");
check_e("y", "2");
check_e("(sc-test-1 (list x y))", "(2 1)");
check_e_success("(define-syntax sc-test-2 (sc-macro-transformer"
"(lambda (form env)"
" (make-syntactic-closure env () (cadr form)))))");
check_e("(sc-test-2 (list x y))", "(1 2)");
check_e_success("(swap! x y)");
check_e("x", "2");
check_e("y", "1");
check_e("(sc-test-2 (list x y))", "(2 1)");
check_e_success("(define sc-test-3"
" (make-syntactic-closure (interaction-environment) '(x) 'x))");
check_e_success("sc-test-3");
check_e("(eval sc-test-3 (null-environment 5))", "x");
check_e("(identifier? 'a)", "#t");
check_e("(identifier? (make-syntactic-closure (null-environment 5) '() 'a))",
"#t");
check_e("(identifier? \"a\")", "#f");
check_e("(identifier? #\\a)", "#f");
check_e("(identifier? 97)", "#f");
check_e("(identifier? #f)", "#f");
check_e("(identifier? '(a))", "#f");
check_e("(identifier? '#(a))", "#f");
check_e_success(
"(define-syntax push"
" (sc-macro-transformer"
" (lambda (exp env)"
" (let ((item (make-syntactic-closure env '() (cadr exp)))"
" (list (make-syntactic-closure env '() (caddr exp))))"
" `(set! ,list (cons ,item ,list))))))");
check_e_success("(define push-test-lis ())");
check_e("push-test-lis", "()");
check_e_success("(push 1 push-test-lis)");
check_e("push-test-lis", "(1)");
check_e_success("(push 2 push-test-lis)");
check_e("push-test-lis", "(2 1)");
return RESULT;
}
<|endoftext|> |
<commit_before><commit_msg>Updated guessing_game<commit_after><|endoftext|> |
<commit_before><commit_msg>Added comparison objects (Issue #3)<commit_after><|endoftext|> |
<commit_before>#include "MetaProvider.ipp"
#include "../../meta/ClassBase.ipp"
BEGIN_INANITY_V8
//*** class MetaProvider::NamedCallableBase
MetaProvider::NamedCallableBase::NamedCallableBase(const char* name)
: name(name) {}
const char* MetaProvider::NamedCallableBase::GetName() const
{
return name;
}
//*** class MetaProvider::ClassBase
MetaProvider::ClassBase::ClassBase(const char* name, const char* fullName)
: Meta::ClassBase<Traits>(name, fullName) {}
// Ensure we have all methods of Meta::ClassBase for linking.
template Meta::ClassBase<MetaProvider::Traits>;
END_INANITY_V8
<commit_msg>fix explicit instantiation syntax in v8 subsystem<commit_after>#include "MetaProvider.ipp"
#include "../../meta/ClassBase.ipp"
BEGIN_INANITY_V8
//*** class MetaProvider::NamedCallableBase
MetaProvider::NamedCallableBase::NamedCallableBase(const char* name)
: name(name) {}
const char* MetaProvider::NamedCallableBase::GetName() const
{
return name;
}
//*** class MetaProvider::ClassBase
MetaProvider::ClassBase::ClassBase(const char* name, const char* fullName)
: Meta::ClassBase<Traits>(name, fullName) {}
END_INANITY_V8
// Ensure we have all methods of Meta::ClassBase for linking.
template class Inanity::Meta::ClassBase<Inanity::Script::V8::MetaProvider::Traits>;
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDA_HPP
#define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDA_HPP
#include <stan/math/prim/scal/fun/inc_beta.hpp>
#include <stan/math/prim/scal/fun/inc_beta_ddb.hpp>
#include <cmath>
namespace stan {
namespace math {
template <typename T>
T inc_beta_ddb(T a, T b, T z,
T digamma_b, T digamma_ab);
template <typename T>
T inc_beta_dda(T a, T b, T z,
T digamma_a, T digamma_ab) {
using std::log;
if (b > a)
if ((0.1 < z && z <= 0.75 && b > 500)
|| (0.01 < z && z <= 0.1 && b > 2500)
|| (0.001 < z && z <= 0.01 && b > 1e5))
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.75 && a < 500)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.9 && a < 2500)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.99 && a < 1e5)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.999)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
double threshold = 1e-10;
digamma_a += 1.0 / a; // Need digamma(a + 1), not digamma(a);
// Common prefactor to regularize numerator and denomentator
T prefactor = (a + 1) / (a + b);
prefactor = prefactor * prefactor * prefactor;
T sum_numer = (digamma_ab - digamma_a) * prefactor;
T sum_denom = prefactor;
T summand = prefactor * z * (a + b) / (a + 1);
T k = 1;
digamma_ab += 1.0 / (a + b);
digamma_a += 1.0 / (a + 1);
while (fabs(summand) > threshold) {
sum_numer += (digamma_ab - digamma_a) * summand;
sum_denom += summand;
summand *= (1 + (a + b) / k) * (1 + k) / (1 + (a + 1) / k);
digamma_ab += 1.0 / (a + b + k);
digamma_a += 1.0 / (a + 1 + k);
++k;
summand *= z / k;
if (k > 1e5)
throw std::domain_error("stan::math::inc_beta_dda did "
"not converge within 100000 iterations");
}
return inc_beta(a, b, z) * (log(z) + sum_numer / sum_denom);
}
} // math
} // stan
#endif
<commit_msg>basic doc<commit_after>#ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDA_HPP
#define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDA_HPP
#include <stan/math/prim/scal/fun/inc_beta.hpp>
#include <stan/math/prim/scal/fun/inc_beta_ddb.hpp>
#include <cmath>
namespace stan {
namespace math {
template <typename T>
T inc_beta_ddb(T a, T b, T z,
T digamma_b, T digamma_ab);
/**
* Returns the partial derivative of the incomplete beta function
* with respect to a.
*
* @tparam T scalar types of arguments
* @param a a
* @param b b
* @param z upper bound of the integral; must be greater than 0
* @param digamma_a value of digamma(a)
* @param digamma_ab value of digamma(b)
* @return partial derivative of the incomplete beta with respect to a
*/
template <typename T>
T inc_beta_dda(T a, T b, T z,
T digamma_a, T digamma_ab) {
using std::log;
if (b > a)
if ((0.1 < z && z <= 0.75 && b > 500)
|| (0.01 < z && z <= 0.1 && b > 2500)
|| (0.001 < z && z <= 0.01 && b > 1e5))
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.75 && a < 500)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.9 && a < 2500)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.99 && a < 1e5)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
if (z > 0.999)
return -inc_beta_ddb(b, a, 1 - z, digamma_a, digamma_ab);
double threshold = 1e-10;
digamma_a += 1.0 / a; // Need digamma(a + 1), not digamma(a);
// Common prefactor to regularize numerator and denomentator
T prefactor = (a + 1) / (a + b);
prefactor = prefactor * prefactor * prefactor;
T sum_numer = (digamma_ab - digamma_a) * prefactor;
T sum_denom = prefactor;
T summand = prefactor * z * (a + b) / (a + 1);
T k = 1;
digamma_ab += 1.0 / (a + b);
digamma_a += 1.0 / (a + 1);
while (fabs(summand) > threshold) {
sum_numer += (digamma_ab - digamma_a) * summand;
sum_denom += summand;
summand *= (1 + (a + b) / k) * (1 + k) / (1 + (a + 1) / k);
digamma_ab += 1.0 / (a + b + k);
digamma_a += 1.0 / (a + 1 + k);
++k;
summand *= z / k;
if (k > 1e5)
throw std::domain_error("stan::math::inc_beta_dda did "
"not converge within 100000 iterations");
}
return inc_beta(a, b, z) * (log(z) + sum_numer / sum_denom);
}
} // math
} // stan
#endif
<|endoftext|> |
<commit_before>#include <stdint.h>
#include "ndb_wrapper.h"
#include "../varkey.h"
#include "../macros.h"
void *
ndb_wrapper::new_txn()
{
return new transaction;
}
bool
ndb_wrapper::commit_txn(void *txn)
{
bool ret;
try {
((transaction *) txn)->commit();
ret = true;
} catch (transaction_abort_exception &ex) {
ret = false;
}
delete (transaction *) txn;
return ret;
}
void
ndb_wrapper::abort_txn(void *txn)
{
((transaction *) txn)->abort();
delete (transaction *) txn;
}
bool
ndb_wrapper::get(
void *txn,
const char *key, size_t keylen,
char *&value, size_t &valuelen)
{
try {
txn_btree::value_type v = 0;
bool ret = btr.search(*((transaction *) txn), varkey((const uint8_t *) key, keylen), v);
if (!ret)
return false;
INVARIANT(v != NULL);
size_t *sp = (size_t *) v;
valuelen = *sp;
value = (char *) malloc(valuelen);
INVARIANT(value != NULL); // XXX: deal with this later
memcpy(value, v + sizeof(size_t), valuelen);
return true;
} catch (transaction_abort_exception &ex) {
throw abstract_abort_exception();
}
}
void
ndb_wrapper::put(
void *txn,
const char *key, size_t keylen,
const char *value, size_t valuelen)
{
uint8_t *record = new uint8_t[sizeof(size_t) + valuelen];
size_t *sp = (size_t *) record;
*sp = valuelen;
memcpy(record + sizeof(size_t), value, valuelen);
try {
btr.insert(*((transaction *) txn), varkey((const uint8_t *) key, keylen), record);
} catch (transaction_abort_exception &ex) {
delete [] record;
throw abstract_abort_exception();
}
}
<commit_msg>register record cleanup callback<commit_after>#include <stdint.h>
#include "ndb_wrapper.h"
#include "../varkey.h"
#include "../macros.h"
void *
ndb_wrapper::new_txn()
{
return new transaction;
}
bool
ndb_wrapper::commit_txn(void *txn)
{
bool ret;
try {
((transaction *) txn)->commit();
ret = true;
} catch (transaction_abort_exception &ex) {
ret = false;
}
delete (transaction *) txn;
return ret;
}
void
ndb_wrapper::abort_txn(void *txn)
{
((transaction *) txn)->abort();
delete (transaction *) txn;
}
bool
ndb_wrapper::get(
void *txn,
const char *key, size_t keylen,
char *&value, size_t &valuelen)
{
try {
txn_btree::value_type v = 0;
bool ret = btr.search(*((transaction *) txn), varkey((const uint8_t *) key, keylen), v);
if (!ret)
return false;
INVARIANT(v != NULL);
size_t *sp = (size_t *) v;
valuelen = *sp;
value = (char *) malloc(valuelen);
INVARIANT(value != NULL); // XXX: deal with this later
memcpy(value, v + sizeof(size_t), valuelen);
return true;
} catch (transaction_abort_exception &ex) {
throw abstract_abort_exception();
}
}
void
ndb_wrapper::put(
void *txn,
const char *key, size_t keylen,
const char *value, size_t valuelen)
{
uint8_t *record = new uint8_t[sizeof(size_t) + valuelen];
size_t *sp = (size_t *) record;
*sp = valuelen;
memcpy(record + sizeof(size_t), value, valuelen);
try {
btr.insert(*((transaction *) txn), varkey((const uint8_t *) key, keylen), record);
} catch (transaction_abort_exception &ex) {
delete [] record;
throw abstract_abort_exception();
}
}
static void
record_cleanup_callback(uint8_t *record)
{
delete [] record;
}
NDB_TXN_REGISTER_CLEANUP_CALLBACK(record_cleanup_callback);
<|endoftext|> |
<commit_before>
#include <random>
#include <tuple>
#include "benchmark/benchmark.h"
#include "numerics/polynomial.hpp"
namespace principia {
namespace numerics {
namespace {
int const evaluations_per_iteration = 1000;
} // namespace
template<typename T>
T GenerateElement(std::mt19937_64& random);
template<>
double GenerateElement(std::mt19937_64& random) {
return static_cast<double>(random());
}
template<typename Tuple, int k, int size = std::tuple_size_v<Tuple>>
struct RandomTupleGenerator {
static void Fill(Tuple& t, std::mt19937_64& random) {
std::get<k>(t) = GenerateElement<std::tuple_element_t<k, Tuple>>(random);
RandomTupleGenerator<Tuple, k + 1, size>::Fill(t, random);
}
};
template<typename Tuple, int size>
struct RandomTupleGenerator<Tuple, size, size> {
static void Fill(Tuple& t, std::mt19937_64& random) {}
};
template<typename Value, typename Argument, typename degree>
void EvaluatePolynomialInMonomialBasis(benchmark::State& state) {
using P = PolynomialInMonomialBasis<Value, Argument, degree>;
std::mt19937_64 random(42);
P::Coefficients coefficients;
RandomTupleGenerator<P::Coefficients, 0>::Fill(coefficients, random);
double const min = static_cast<double>(random());
double const max = static_cast<double>(random());
P4 const p4(coefficients, min, max);
double argument = min;
double const Δargument = (max - min) * 1e-9;
double result = 0.0;
while (state.KeepRunning()) {
for (int i = 0; i < evaluations_per_iteration; ++i) {
result += p4.Evaluate(argument);
argument += Δargument;
}
}
// This weird call to |SetLabel| has no effect except that it uses |result|
// and therefore prevents the loop from being optimized away.
state.SetLabel(std::to_string(result).substr(0, 0));
}
void BM_EvaluatePolynomial(benchmark::State& state) {
using P4 = PolynomialInMonomialBasis<double, double, 4>;
std::mt19937_64 random(42);
P4::Coefficients coefficients;
RandomTupleGenerator<P4::Coefficients, 0>::Fill(coefficients, random);
double const min = static_cast<double>(random());
double const max = static_cast<double>(random());
P4 const p4(coefficients, min, max);
double argument = min;
double const Δargument = (max - min) * 1e-9;
double result = 0.0;
while (state.KeepRunning()) {
for (int i = 0; i < evaluations_per_iteration; ++i) {
result += p4.Evaluate(argument);
argument += Δargument;
}
}
// This weird call to |SetLabel| has no effect except that it uses |result|
// and therefore prevents the loop from being optimized away.
state.SetLabel(std::to_string(result).substr(0, 0));
}
BENCHMARK(BM_EvaluatePolynomial);
} // namespace numerics
} // namespace principia
<commit_msg>Benchmark multiple degrees.<commit_after>
#include <random>
#include <tuple>
#include "benchmark/benchmark.h"
#include "numerics/polynomial.hpp"
#include "quantities/quantities.hpp"
#include "quantities/si.hpp"
namespace principia {
using quantities::Length;
using quantities::Quantity;
using quantities::SIUnit;
using quantities::Time;
namespace numerics {
namespace {
int const evaluations_per_iteration = 1000;
} // namespace
template<typename T>
struct ValueGenerator;
template<>
struct ValueGenerator<double> {
static double Get(std::mt19937_64& random) {
return static_cast<double>(random());
}
};
template<typename D>
struct ValueGenerator<Quantity<D>> {
static Quantity<D> Get(std::mt19937_64& random) {
return static_cast<double>(random()) * SIUnit<Quantity<D>>();
}
};
template<typename Tuple, int k, int size = std::tuple_size_v<Tuple>>
struct RandomTupleGenerator {
static void Fill(Tuple& t, std::mt19937_64& random) {
std::get<k>(t) =
ValueGenerator<std::tuple_element_t<k, Tuple>>::Get(random);
RandomTupleGenerator<Tuple, k + 1, size>::Fill(t, random);
}
};
template<typename Tuple, int size>
struct RandomTupleGenerator<Tuple, size, size> {
static void Fill(Tuple& t, std::mt19937_64& random) {}
};
template<typename Value, typename Argument, int degree>
void EvaluatePolynomialInMonomialBasis(benchmark::State& state) {
using P = PolynomialInMonomialBasis<Value, Argument, degree>;
std::mt19937_64 random(42);
P::Coefficients coefficients;
RandomTupleGenerator<P::Coefficients, 0>::Fill(coefficients, random);
auto const min = ValueGenerator<Argument>::Get(random);
auto const max = ValueGenerator<Argument>::Get(random);
P const p(coefficients, min, max);
auto argument = min;
auto const Δargument = (max - min) * 1e-9;
auto result = Value{};
while (state.KeepRunning()) {
for (int i = 0; i < evaluations_per_iteration; ++i) {
result += p.Evaluate(argument);
argument += Δargument;
}
}
// This weird call to |SetLabel| has no effect except that it uses |result|
// and therefore prevents the loop from being optimized away.
std::stringstream ss;
ss << result;
state.SetLabel(ss.str().substr(0, 0));
}
void BM_EvaluatePolynomialDouble(benchmark::State& state) {
int const degree = state.range_x();
switch (degree) {
case 4:
EvaluatePolynomialInMonomialBasis<double, Time, 4>(state);
break;
case 8:
EvaluatePolynomialInMonomialBasis<double, Time, 8>(state);
break;
case 16:
EvaluatePolynomialInMonomialBasis<double, Time, 16>(state);
break;
default:
LOG(FATAL) << "Degree " << degree << " in BM_EvaluatePolynomialDouble";
}
}
void BM_EvaluatePolynomialQuantity(benchmark::State& state) {
int const degree = state.range_x();
switch (degree) {
case 4:
EvaluatePolynomialInMonomialBasis<Length, Time, 4>(state);
break;
case 8:
EvaluatePolynomialInMonomialBasis<Length, Time, 8>(state);
break;
case 16:
EvaluatePolynomialInMonomialBasis<Length, Time, 16>(state);
break;
default:
LOG(FATAL) << "Degree " << degree << " in BM_EvaluatePolynomialQuantity";
}
}
BENCHMARK(BM_EvaluatePolynomialDouble)->Arg(4)->Arg(8)->Arg(16);
BENCHMARK(BM_EvaluatePolynomialQuantity)->Arg(4)->Arg(8)->Arg(16);
} // namespace numerics
} // namespace principia
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2010 Laurent Bauer
Copyright (C) 2010 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib 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 3 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_sphere.cpp implementation of the GLC_Sphere class.
#include "glc_sphere.h"
// Class chunk id
quint32 GLC_Sphere::m_ChunkId= 0xA710;
GLC_Sphere::GLC_Sphere(double radius)
: GLC_Mesh()
, m_Radius (radius)
, m_Discret(glc::GLC_POLYDISCRET)
, m_ThetaMin (0.0)
, m_ThetaMax(2 * glc::PI)
, m_PhiMin(-glc::PI / 2.0)
, m_PhiMax(glc::PI / 2.0)
{
}
GLC_Sphere::GLC_Sphere(const GLC_Sphere & sphere)
:GLC_Mesh(sphere)
, m_Radius (sphere.m_Radius)
, m_Discret(sphere.m_Discret)
, m_ThetaMin (sphere.m_ThetaMin)
, m_ThetaMax(sphere.m_ThetaMax)
, m_PhiMin(sphere.m_PhiMin)
, m_PhiMax(sphere.m_PhiMax)
{
}
GLC_Sphere::~GLC_Sphere()
{
}
GLC_Geometry* GLC_Sphere::clone() const
{
return new GLC_Sphere (*this);
}
const GLC_BoundingBox& GLC_Sphere::boundingBox()
{
if ( GLC_Mesh::isEmpty() )
{
createMesh();
}
return GLC_Mesh::boundingBox();
}
void GLC_Sphere::setRadius(double Radius)
{
Q_ASSERT(Radius > 0.0);
m_Radius= Radius;
GLC_Mesh::clearMeshWireAndBoundingBox();
}
void GLC_Sphere::setDiscretion(int TargetDiscret)
{
Q_ASSERT(TargetDiscret > 0);
if (TargetDiscret != m_Discret)
{
m_Discret= TargetDiscret;
if (m_Discret < 6) m_Discret= 6;
GLC_Mesh::clearMeshWireAndBoundingBox();
}
}
void GLC_Sphere::glDraw(const GLC_RenderProperties& renderProperties)
{
if (GLC_Mesh::isEmpty())
{
createMesh();
}
GLC_Mesh::glDraw(renderProperties);
}
void GLC_Sphere::createMesh()
{
Q_ASSERT(GLC_Mesh::isEmpty());
GLfloatVector verticeFloat;
GLfloatVector normalsFloat;
GLfloatVector texelVector;
int currentIndex=0;
float wishedThetaStep= glc::PI / m_Discret;
float thetaRange= m_ThetaMax-m_ThetaMin;
int nbThetaSteps= (int) (thetaRange / wishedThetaStep) + 1 ;
float thetaStep= thetaRange / nbThetaSteps;
float wishedPhiStep= wishedThetaStep;
float phiRange= m_PhiMax-m_PhiMin;
int nbPhiSteps= (int) (phiRange / wishedPhiStep) + 1 ;
float phiStep= phiRange / nbPhiSteps;
float cost, sint, cosp, sinp, cospp, sinpp;
float xi, yi, zi, xf, yf, zf;
float theta= m_ThetaMin;
float phi= m_PhiMin;
GLfloatVector thetaMinWire;
GLfloatVector thetaMaxWire;
GLfloatVector phiMinWire;
GLfloatVector phiMaxWire;
GLC_Material* pMaterial;
if (hasMaterial())
pMaterial= this->firstMaterial();
else
pMaterial= new GLC_Material();
// shaded face
for (int p= 0; p < nbPhiSteps; ++p)
{
cosp= cos (phi);
sinp= sin (phi);
cospp= cos (phi + phiStep);
sinpp= sin (phi + phiStep);
zi = m_Radius * sinp;
zf = m_Radius * sinpp;
IndexList indexFace;
theta = m_ThetaMin;
int t;
for (t= 0; t <= nbThetaSteps; ++t)
{
cost= cos( theta );
sint= sin( theta );
xi= m_Radius * cost * cosp;
yi= m_Radius * sint * cosp;
xf= m_Radius * cost * cospp;
yf= m_Radius * sint * cospp;
verticeFloat << xi << yi << zi << xf << yf << zf;
normalsFloat << cost * cosp << sint * cosp << sinp << cost * cospp << sint * cospp << sinpp ;
texelVector << static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps)
<< static_cast<double>(p) * 1.0 / static_cast<double>(nbPhiSteps)
<< static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps)
<< static_cast<double>(p+1) * 1.0 / static_cast<double>(nbPhiSteps);
indexFace << currentIndex + 2 * t << currentIndex + 2 * t + 1 ;
theta+= thetaStep;
}
currentIndex+= 2 * t;
addTrianglesStrip(pMaterial, indexFace);
phi+= phiStep;
}
addVertice(verticeFloat);
addNormals(normalsFloat);
addTexels(texelVector);
finish();
}
<commit_msg>Fix rendering bug (Face vertices order)<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2010 Laurent Bauer
Copyright (C) 2010 Laurent Ribon (laumaya@users.sourceforge.net)
http://glc-lib.sourceforge.net
GLC-lib 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 3 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_sphere.cpp implementation of the GLC_Sphere class.
#include "glc_sphere.h"
// Class chunk id
quint32 GLC_Sphere::m_ChunkId= 0xA710;
GLC_Sphere::GLC_Sphere(double radius)
: GLC_Mesh()
, m_Radius (radius)
, m_Discret(glc::GLC_POLYDISCRET)
, m_ThetaMin (0.0)
, m_ThetaMax(2 * glc::PI)
, m_PhiMin(-glc::PI / 2.0)
, m_PhiMax(glc::PI / 2.0)
{
}
GLC_Sphere::GLC_Sphere(const GLC_Sphere & sphere)
:GLC_Mesh(sphere)
, m_Radius (sphere.m_Radius)
, m_Discret(sphere.m_Discret)
, m_ThetaMin (sphere.m_ThetaMin)
, m_ThetaMax(sphere.m_ThetaMax)
, m_PhiMin(sphere.m_PhiMin)
, m_PhiMax(sphere.m_PhiMax)
{
}
GLC_Sphere::~GLC_Sphere()
{
}
GLC_Geometry* GLC_Sphere::clone() const
{
return new GLC_Sphere (*this);
}
const GLC_BoundingBox& GLC_Sphere::boundingBox()
{
if ( GLC_Mesh::isEmpty() )
{
createMesh();
}
return GLC_Mesh::boundingBox();
}
void GLC_Sphere::setRadius(double Radius)
{
Q_ASSERT(Radius > 0.0);
m_Radius= Radius;
GLC_Mesh::clearMeshWireAndBoundingBox();
}
void GLC_Sphere::setDiscretion(int TargetDiscret)
{
Q_ASSERT(TargetDiscret > 0);
if (TargetDiscret != m_Discret)
{
m_Discret= TargetDiscret;
if (m_Discret < 6) m_Discret= 6;
GLC_Mesh::clearMeshWireAndBoundingBox();
}
}
void GLC_Sphere::glDraw(const GLC_RenderProperties& renderProperties)
{
if (GLC_Mesh::isEmpty())
{
createMesh();
}
GLC_Mesh::glDraw(renderProperties);
}
void GLC_Sphere::createMesh()
{
Q_ASSERT(GLC_Mesh::isEmpty());
GLfloatVector verticeFloat;
GLfloatVector normalsFloat;
GLfloatVector texelVector;
int currentIndex=0;
float wishedThetaStep= glc::PI / m_Discret;
float thetaRange= m_ThetaMax-m_ThetaMin;
int nbThetaSteps= (int) (thetaRange / wishedThetaStep) + 1 ;
float thetaStep= thetaRange / nbThetaSteps;
float wishedPhiStep= wishedThetaStep;
float phiRange= m_PhiMax-m_PhiMin;
int nbPhiSteps= (int) (phiRange / wishedPhiStep) + 1 ;
float phiStep= phiRange / nbPhiSteps;
float cost, sint, cosp, sinp, cospp, sinpp;
float xi, yi, zi, xf, yf, zf;
float theta= m_ThetaMin;
float phi= m_PhiMin;
GLfloatVector thetaMinWire;
GLfloatVector thetaMaxWire;
GLfloatVector phiMinWire;
GLfloatVector phiMaxWire;
GLC_Material* pMaterial;
if (hasMaterial())
pMaterial= this->firstMaterial();
else
pMaterial= new GLC_Material();
// shaded face
for (int p= 0; p < nbPhiSteps; ++p)
{
cosp= cos (phi);
sinp= sin (phi);
cospp= cos (phi + phiStep);
sinpp= sin (phi + phiStep);
zi = m_Radius * sinp;
zf = m_Radius * sinpp;
IndexList indexFace;
theta = m_ThetaMin;
int t;
for (t= 0; t <= nbThetaSteps; ++t)
{
cost= cos( theta );
sint= sin( theta );
xi= m_Radius * cost * cosp;
yi= m_Radius * sint * cosp;
xf= m_Radius * cost * cospp;
yf= m_Radius * sint * cospp;
verticeFloat << xf << yf << zf << xi << yi << zi;
normalsFloat << cost * cospp << sint * cospp << sinpp << cost * cosp << sint * cosp << sinp;
texelVector << static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps)
<< static_cast<double>(p) * 1.0 / static_cast<double>(nbPhiSteps)
<< static_cast<double>(t) * 1.0 / static_cast<double>(nbThetaSteps)
<< static_cast<double>(p+1) * 1.0 / static_cast<double>(nbPhiSteps);
indexFace << currentIndex + 2 * t << currentIndex + 2 * t + 1 ;
theta+= thetaStep;
}
currentIndex+= 2 * t;
addTrianglesStrip(pMaterial, indexFace);
phi+= phiStep;
}
addVertice(verticeFloat);
addNormals(normalsFloat);
addTexels(texelVector);
finish();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2015, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"
namespace El {
template<typename Real,typename=EnableIf<IsReal<Real>>>
ValueInt<Real> VectorMinLoc( const Matrix<Real>& x )
{
DEBUG_ONLY(CSE cse("VectorMinLoc"))
const Int m = x.Height();
const Int n = x.Width();
DEBUG_ONLY(
if( m != 1 && n != 1 )
LogicError("Input should have been a vector");
)
ValueInt<Real> pivot;
pivot.index = -1;
pivot.value = std::numeric_limits<Real>::max();
if( n == 1 )
{
for( Int i=0; i<m; ++i )
{
const Real value = x.Get(i,0);
if( value > pivot.value )
{
pivot.value = value;
pivot.index = i;
}
}
}
else
{
for( Int j=0; j<n; ++j )
{
const Real value = x.Get(0,j);
if( value > pivot.value )
{
pivot.value = value;
pivot.index = j;
}
}
}
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
ValueInt<Real> VectorMinLoc( const AbstractDistMatrix<Real>& x )
{
DEBUG_ONLY(CSE cse("VectorMinLoc"))
const Int m = x.Height();
const Int n = x.Width();
DEBUG_ONLY(
if( m != 1 && n != 1 )
LogicError("Input should have been a vector");
if( !x.Grid().InGrid() )
LogicError("viewing processes are not allowed");
)
ValueInt<Real> pivot;
pivot.index = -1;
pivot.value = std::numeric_limits<Real>::max();
if( x.Participating() )
{
if( n == 1 )
{
if( x.RowRank() == x.RowAlign() )
{
const Int mLocal = x.LocalHeight();
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
{
const Real value = x.GetLocal(iLoc,0);
if( value > pivot.value )
{
pivot.value = value;
pivot.index = x.GlobalRow(iLoc);
}
}
}
}
else
{
if( x.ColRank() == x.ColAlign() )
{
const Int nLocal = x.LocalWidth();
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Real value = x.GetLocal(0,jLoc);
if( value > pivot.value )
{
pivot.value = value;
pivot.index = x.GlobalCol(jLoc);
}
}
}
}
pivot = mpi::AllReduce( pivot, mpi::MinLocOp<Real>(), x.DistComm() );
}
mpi::Broadcast( pivot, x.Root(), x.CrossComm() );
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
ValueInt<Real> VectorMinLoc( const DistMultiVec<Real>& x )
{
DEBUG_ONLY(CSE cse("VectorMinLoc"))
const Int height = x.Height();
DEBUG_ONLY(
if( x.Width() != 1 )
LogicError("Input should have been a vector");
)
ValueInt<Real> pivot;
pivot.index = -1;
pivot.value = std::numeric_limits<Real>::max();
const Int mLocal = x.LocalHeight();
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
{
const Real value = x.GetLocal(iLoc,0);
if( value > pivot.value )
{
pivot.value = value;
pivot.index = x.GlobalRow(iLoc);
}
}
pivot = mpi::AllReduce( pivot, mpi::MinLocOp<Real>(), x.Comm() );
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real> MinLoc( const Matrix<Real>& A )
{
DEBUG_ONLY(CSE cse("MinLoc"))
const Int m = A.Height();
const Int n = A.Width();
const Real* ABuf = A.LockedBuffer();
const Int ALDim = A.LDim();
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
for( Int j=0; j<n; ++j )
{
for( Int i=0; i<m; ++i )
{
const Real value = ABuf[i+j*ALDim];
if( value > pivot.value )
{
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real> MinLoc( const AbstractDistMatrix<Real>& A )
{
DEBUG_ONLY(
CSE cse("MinLoc");
if( !A.Grid().InGrid() )
LogicError("Viewing processes are not allowed");
)
const Real* ABuf = A.LockedBuffer();
const Int ALDim = A.LDim();
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
if( A.Participating() )
{
// Store the index/value of the local pivot candidate
const Int mLocal = A.LocalHeight();
const Int nLocal = A.LocalWidth();
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Int j = A.GlobalCol(jLoc);
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
{
const Real value = ABuf[iLoc+jLoc*ALDim];
if( value > pivot.value )
{
const Int i = A.GlobalRow(iLoc);
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
// Compute and store the location of the new pivot
pivot = mpi::AllReduce
( pivot, mpi::MinLocPairOp<Real>(), A.DistComm() );
}
mpi::Broadcast( pivot, A.Root(), A.CrossComm() );
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real> SymmetricMinLoc( UpperOrLower uplo, const Matrix<Real>& A )
{
DEBUG_ONLY(
CSE cse("SymmetricMinLoc");
if( A.Height() != A.Width() )
LogicError("A must be square");
)
const Int n = A.Width();
const Real* ABuf = A.LockedBuffer();
const Int ALDim = A.LDim();
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
if( uplo == LOWER )
{
for( Int j=0; j<n; ++j )
{
for( Int i=j; i<n; ++i )
{
const Real value = ABuf[i+j*ALDim];
if( value > pivot.value )
{
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
else
{
for( Int j=0; j<n; ++j )
{
for( Int i=0; i<=j; ++i )
{
const Real value = ABuf[i+j*ALDim];
if( value > pivot.value )
{
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real>
SymmetricMinLoc( UpperOrLower uplo, const AbstractDistMatrix<Real>& A )
{
DEBUG_ONLY(
CSE cse("SymmetricMinLoc");
if( A.Height() != A.Width() )
LogicError("A must be square");
if( !A.Grid().InGrid() )
LogicError("Viewing processes are not allowed");
)
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
if( A.Participating() )
{
const Int mLocal = A.LocalHeight();
const Int nLocal = A.LocalWidth();
if( uplo == LOWER )
{
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Int j = A.GlobalCol(jLoc);
const Int mLocBefore = A.LocalRowOffset(j);
for( Int iLoc=mLocBefore; iLoc<mLocal; ++iLoc )
{
const Real value = A.GetLocal(iLoc,jLoc);
if( value > pivot.value )
{
const Int i = A.GlobalRow(iLoc);
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
else
{
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Int j = A.GlobalCol(jLoc);
const Int mLocBefore = A.LocalRowOffset(j+1);
for( Int iLoc=0; iLoc<mLocBefore; ++iLoc )
{
const Real value = A.GetLocal(iLoc,jLoc);
if( value > pivot.value )
{
const Int i = A.GlobalRow(iLoc);
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
// Compute and store the location of the new pivot
pivot = mpi::AllReduce
( pivot, mpi::MinLocPairOp<Real>(), A.DistComm() );
}
mpi::Broadcast( pivot, A.Root(), A.CrossComm() );
return pivot;
}
#define PROTO(Real) \
template ValueInt<Real> VectorMinLoc( const Matrix<Real>& x ); \
template ValueInt<Real> VectorMinLoc( const AbstractDistMatrix<Real>& x ); \
template ValueInt<Real> VectorMinLoc( const DistMultiVec<Real>& x ); \
template Entry<Real> MinLoc( const Matrix<Real>& x ); \
template Entry<Real> MinLoc( const AbstractDistMatrix<Real>& x ); \
template Entry<Real> SymmetricMinLoc \
( UpperOrLower uplo, const Matrix<Real>& A ); \
template Entry<Real> SymmetricMinLoc \
( UpperOrLower uplo, const AbstractDistMatrix<Real>& A );
#define EL_NO_COMPLEX_PROTO
#define EL_ENABLE_QUAD
#include "El/macros/Instantiate.h"
} // namespace El
<commit_msg>Fixing mistake in MinLoc introduced early today from copying and pasting the MaxLoc implementation and manually then manually converting<commit_after>/*
Copyright (c) 2009-2015, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#include "El.hpp"
namespace El {
template<typename Real,typename=EnableIf<IsReal<Real>>>
ValueInt<Real> VectorMinLoc( const Matrix<Real>& x )
{
DEBUG_ONLY(CSE cse("VectorMinLoc"))
const Int m = x.Height();
const Int n = x.Width();
DEBUG_ONLY(
if( m != 1 && n != 1 )
LogicError("Input should have been a vector");
)
ValueInt<Real> pivot;
pivot.index = -1;
pivot.value = std::numeric_limits<Real>::max();
if( n == 1 )
{
for( Int i=0; i<m; ++i )
{
const Real value = x.Get(i,0);
if( value < pivot.value )
{
pivot.value = value;
pivot.index = i;
}
}
}
else
{
for( Int j=0; j<n; ++j )
{
const Real value = x.Get(0,j);
if( value < pivot.value )
{
pivot.value = value;
pivot.index = j;
}
}
}
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
ValueInt<Real> VectorMinLoc( const AbstractDistMatrix<Real>& x )
{
DEBUG_ONLY(CSE cse("VectorMinLoc"))
const Int m = x.Height();
const Int n = x.Width();
DEBUG_ONLY(
if( m != 1 && n != 1 )
LogicError("Input should have been a vector");
if( !x.Grid().InGrid() )
LogicError("viewing processes are not allowed");
)
ValueInt<Real> pivot;
pivot.index = -1;
pivot.value = std::numeric_limits<Real>::max();
if( x.Participating() )
{
if( n == 1 )
{
if( x.RowRank() == x.RowAlign() )
{
const Int mLocal = x.LocalHeight();
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
{
const Real value = x.GetLocal(iLoc,0);
if( value < pivot.value )
{
pivot.value = value;
pivot.index = x.GlobalRow(iLoc);
}
}
}
}
else
{
if( x.ColRank() == x.ColAlign() )
{
const Int nLocal = x.LocalWidth();
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Real value = x.GetLocal(0,jLoc);
if( value < pivot.value )
{
pivot.value = value;
pivot.index = x.GlobalCol(jLoc);
}
}
}
}
pivot = mpi::AllReduce( pivot, mpi::MinLocOp<Real>(), x.DistComm() );
}
mpi::Broadcast( pivot, x.Root(), x.CrossComm() );
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
ValueInt<Real> VectorMinLoc( const DistMultiVec<Real>& x )
{
DEBUG_ONLY(CSE cse("VectorMinLoc"))
const Int height = x.Height();
DEBUG_ONLY(
if( x.Width() != 1 )
LogicError("Input should have been a vector");
)
ValueInt<Real> pivot;
pivot.index = -1;
pivot.value = std::numeric_limits<Real>::max();
const Int mLocal = x.LocalHeight();
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
{
const Real value = x.GetLocal(iLoc,0);
if( value < pivot.value )
{
pivot.value = value;
pivot.index = x.GlobalRow(iLoc);
}
}
pivot = mpi::AllReduce( pivot, mpi::MinLocOp<Real>(), x.Comm() );
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real> MinLoc( const Matrix<Real>& A )
{
DEBUG_ONLY(CSE cse("MinLoc"))
const Int m = A.Height();
const Int n = A.Width();
const Real* ABuf = A.LockedBuffer();
const Int ALDim = A.LDim();
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
for( Int j=0; j<n; ++j )
{
for( Int i=0; i<m; ++i )
{
const Real value = ABuf[i+j*ALDim];
if( value < pivot.value )
{
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real> MinLoc( const AbstractDistMatrix<Real>& A )
{
DEBUG_ONLY(
CSE cse("MinLoc");
if( !A.Grid().InGrid() )
LogicError("Viewing processes are not allowed");
)
const Real* ABuf = A.LockedBuffer();
const Int ALDim = A.LDim();
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
if( A.Participating() )
{
// Store the index/value of the local pivot candidate
const Int mLocal = A.LocalHeight();
const Int nLocal = A.LocalWidth();
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Int j = A.GlobalCol(jLoc);
for( Int iLoc=0; iLoc<mLocal; ++iLoc )
{
const Real value = ABuf[iLoc+jLoc*ALDim];
if( value < pivot.value )
{
const Int i = A.GlobalRow(iLoc);
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
// Compute and store the location of the new pivot
pivot = mpi::AllReduce
( pivot, mpi::MinLocPairOp<Real>(), A.DistComm() );
}
mpi::Broadcast( pivot, A.Root(), A.CrossComm() );
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real> SymmetricMinLoc( UpperOrLower uplo, const Matrix<Real>& A )
{
DEBUG_ONLY(
CSE cse("SymmetricMinLoc");
if( A.Height() != A.Width() )
LogicError("A must be square");
)
const Int n = A.Width();
const Real* ABuf = A.LockedBuffer();
const Int ALDim = A.LDim();
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
if( uplo == LOWER )
{
for( Int j=0; j<n; ++j )
{
for( Int i=j; i<n; ++i )
{
const Real value = ABuf[i+j*ALDim];
if( value < pivot.value )
{
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
else
{
for( Int j=0; j<n; ++j )
{
for( Int i=0; i<=j; ++i )
{
const Real value = ABuf[i+j*ALDim];
if( value < pivot.value )
{
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
return pivot;
}
template<typename Real,typename=EnableIf<IsReal<Real>>>
Entry<Real>
SymmetricMinLoc( UpperOrLower uplo, const AbstractDistMatrix<Real>& A )
{
DEBUG_ONLY(
CSE cse("SymmetricMinLoc");
if( A.Height() != A.Width() )
LogicError("A must be square");
if( !A.Grid().InGrid() )
LogicError("Viewing processes are not allowed");
)
Entry<Real> pivot;
pivot.i = -1;
pivot.j = -1;
pivot.value = std::numeric_limits<Real>::max();
if( A.Participating() )
{
const Int mLocal = A.LocalHeight();
const Int nLocal = A.LocalWidth();
if( uplo == LOWER )
{
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Int j = A.GlobalCol(jLoc);
const Int mLocBefore = A.LocalRowOffset(j);
for( Int iLoc=mLocBefore; iLoc<mLocal; ++iLoc )
{
const Real value = A.GetLocal(iLoc,jLoc);
if( value < pivot.value )
{
const Int i = A.GlobalRow(iLoc);
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
else
{
for( Int jLoc=0; jLoc<nLocal; ++jLoc )
{
const Int j = A.GlobalCol(jLoc);
const Int mLocBefore = A.LocalRowOffset(j+1);
for( Int iLoc=0; iLoc<mLocBefore; ++iLoc )
{
const Real value = A.GetLocal(iLoc,jLoc);
if( value < pivot.value )
{
const Int i = A.GlobalRow(iLoc);
pivot.i = i;
pivot.j = j;
pivot.value = value;
}
}
}
}
// Compute and store the location of the new pivot
pivot = mpi::AllReduce
( pivot, mpi::MinLocPairOp<Real>(), A.DistComm() );
}
mpi::Broadcast( pivot, A.Root(), A.CrossComm() );
return pivot;
}
#define PROTO(Real) \
template ValueInt<Real> VectorMinLoc( const Matrix<Real>& x ); \
template ValueInt<Real> VectorMinLoc( const AbstractDistMatrix<Real>& x ); \
template ValueInt<Real> VectorMinLoc( const DistMultiVec<Real>& x ); \
template Entry<Real> MinLoc( const Matrix<Real>& x ); \
template Entry<Real> MinLoc( const AbstractDistMatrix<Real>& x ); \
template Entry<Real> SymmetricMinLoc \
( UpperOrLower uplo, const Matrix<Real>& A ); \
template Entry<Real> SymmetricMinLoc \
( UpperOrLower uplo, const AbstractDistMatrix<Real>& A );
#define EL_NO_COMPLEX_PROTO
#define EL_ENABLE_QUAD
#include "El/macros/Instantiate.h"
} // namespace El
<|endoftext|> |
<commit_before>/*
Copyright 2015-2020 Igor Petrovic
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "board/Board.h"
#include "board/Internal.h"
#include "core/src/general/Interrupt.h"
#include "board/common/io/Helpers.h"
#include "Pins.h"
namespace Board
{
void uniqueID(uniqueID_t& uid)
{
uint32_t id[3];
id[0] = HAL_GetUIDw0();
id[1] = HAL_GetUIDw1();
id[2] = HAL_GetUIDw2();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF;
}
}
namespace detail
{
namespace setup
{
void application()
{
//Reset of all peripherals, Initializes the Flash interface and the Systick
HAL_Init();
detail::setup::clocks();
detail::setup::io();
NVM::init();
detail::setup::adc();
detail::setup::timers();
#ifdef USB_MIDI_SUPPORTED
detail::setup::usb();
#endif
}
void bootloader()
{
HAL_Init();
detail::setup::clocks();
detail::setup::io();
}
void io()
{
#ifdef NUMBER_OF_IN_SR
CORE_IO_CONFIG({ SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#else
#ifdef NUMBER_OF_BUTTON_ROWS
for (int i = 0; i < NUMBER_OF_BUTTON_ROWS; i++)
#else
for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++)
#endif
{
core::io::mcuPin_t pin = detail::map::buttonPin(i);
#ifndef BUTTONS_EXT_PULLUPS
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::up, core::io::gpioSpeed_t::medium, 0x00 });
#else
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#endif
}
#endif
#ifdef NUMBER_OF_BUTTON_COLUMNS
CORE_IO_CONFIG({ DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0);
CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1);
CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2);
#endif
#ifdef NUMBER_OF_OUT_SR
CORE_IO_CONFIG({ SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#ifdef SR_OUT_OE_PORT
CORE_IO_CONFIG({ SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#endif
//init all outputs on shift register
CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
{
EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);
CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
detail::io::sr595wait();
CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
}
CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
#ifdef SR_OUT_OE_PORT
CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN);
#endif
#else
#ifdef NUMBER_OF_LED_ROWS
CORE_IO_CONFIG({ DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0);
CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1);
CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2);
for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)
#else
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
#endif
{
core::io::mcuPin_t pin = detail::map::ledPin(i);
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
#endif
#if MAX_ADC_CHANNELS > 0
for (int i = 0; i < MAX_ADC_CHANNELS; i++)
{
core::io::mcuPin_t pin = detail::map::adcPin(i);
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::analog });
CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
#endif
#ifdef NUMBER_OF_MUX
CORE_IO_CONFIG({ MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#ifdef MUX_PORT_S3
CORE_IO_CONFIG({ MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#endif
#endif
#ifdef BTLDR_BUTTON_PORT
CORE_IO_CONFIG({ BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input });
#endif
#ifdef LED_INDICATORS
CORE_IO_CONFIG({ LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN);
INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN);
INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN);
INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN);
#endif
#ifdef LED_BTLDR_PORT
CORE_IO_CONFIG({ LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN);
#endif
}
} // namespace setup
} // namespace detail
} // namespace Board<commit_msg>board: use open drain outputs for led matrix rows on stm32<commit_after>/*
Copyright 2015-2020 Igor Petrovic
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "board/Board.h"
#include "board/Internal.h"
#include "core/src/general/Interrupt.h"
#include "board/common/io/Helpers.h"
#include "Pins.h"
namespace Board
{
void uniqueID(uniqueID_t& uid)
{
uint32_t id[3];
id[0] = HAL_GetUIDw0();
id[1] = HAL_GetUIDw1();
id[2] = HAL_GetUIDw2();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
uid.uid[(i * 4) + j] = id[i] >> ((3 - j) * 8) & 0xFF;
}
}
namespace detail
{
namespace setup
{
void application()
{
//Reset of all peripherals, Initializes the Flash interface and the Systick
HAL_Init();
detail::setup::clocks();
detail::setup::io();
NVM::init();
detail::setup::adc();
detail::setup::timers();
#ifdef USB_MIDI_SUPPORTED
detail::setup::usb();
#endif
}
void bootloader()
{
HAL_Init();
detail::setup::clocks();
detail::setup::io();
}
void io()
{
#ifdef NUMBER_OF_IN_SR
CORE_IO_CONFIG({ SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#else
#ifdef NUMBER_OF_BUTTON_ROWS
for (int i = 0; i < NUMBER_OF_BUTTON_ROWS; i++)
#else
for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++)
#endif
{
core::io::mcuPin_t pin = detail::map::buttonPin(i);
#ifndef BUTTONS_EXT_PULLUPS
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::up, core::io::gpioSpeed_t::medium, 0x00 });
#else
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#endif
}
#endif
#ifdef NUMBER_OF_BUTTON_COLUMNS
CORE_IO_CONFIG({ DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0);
CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1);
CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2);
#endif
#ifdef NUMBER_OF_OUT_SR
CORE_IO_CONFIG({ SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#ifdef SR_OUT_OE_PORT
CORE_IO_CONFIG({ SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#endif
//init all outputs on shift register
CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
{
EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);
CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
detail::io::sr595wait();
CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);
}
CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);
#ifdef SR_OUT_OE_PORT
CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN);
#endif
#else
#ifdef NUMBER_OF_LED_ROWS
CORE_IO_CONFIG({ DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0);
CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1);
CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2);
for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)
#else
for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)
#endif
{
core::io::mcuPin_t pin = detail::map::ledPin(i);
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::outputOD, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
#endif
#if MAX_ADC_CHANNELS > 0
for (int i = 0; i < MAX_ADC_CHANNELS; i++)
{
core::io::mcuPin_t pin = detail::map::adcPin(i);
CORE_IO_CONFIG({ CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::analog });
CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));
}
#endif
#ifdef NUMBER_OF_MUX
CORE_IO_CONFIG({ MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#ifdef MUX_PORT_S3
CORE_IO_CONFIG({ MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
#endif
#endif
#ifdef BTLDR_BUTTON_PORT
CORE_IO_CONFIG({ BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input });
#endif
#ifdef LED_INDICATORS
CORE_IO_CONFIG({ LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_CONFIG({ LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN);
INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN);
INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN);
INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN);
#endif
#ifdef LED_BTLDR_PORT
CORE_IO_CONFIG({ LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::outputPP, core::io::pullMode_t::none, core::io::gpioSpeed_t::medium, 0x00 });
CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN);
#endif
}
} // namespace setup
} // namespace detail
} // namespace Board<|endoftext|> |
<commit_before>/***************************************************************************
LALR.cpp - description
------------------------
begin : Fri Jun 14 2002
copyright : (C) 2002 by Manuel Astudillo
***************************************************************************/
/***************************************************************************
* *
* This program 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. *
* *
***************************************************************************/
#include <assert.h>
#include "LALR.h"
LALR::LALR (const LALRStateTable *stateTable, const SymbolTable *symbolTable,
const RuleTable *ruleTable, integer startState) {
this->stateTable = stateTable;
this->symbolTable = symbolTable;
this->ruleTable = ruleTable;
this->startState = startState;
errorTab = NULL;
nbrBackUpTokens = 10;
}
LALR::~LALR () {
delete errorTab;
// Clean the stack in case elements are still there
// TODO: Investigate why there are elements in the stack if the parser worked nicely
while (!symbolStack.empty()) {
// delete symbolStack.top();
symbolStack.pop();
}
}
/*!
Initializes the parser.
Call this function before calling buildParseTree()
/sa buildParseTree();
*/
void LALR::init (const vector <Token*> &tokens) {
// Copy the tokens vector (maybe just having a reference to it is enough...)
this->tokens = tokens;
// Initialize stack (And clear it in case there still are elements there)
while (!symbolStack.empty()) {
//delete symbolStack.top();
symbolStack.pop();
}
// Create the start symbol (maybe it is not needed to place it in both stack and reductionList
// Maybe is enough to put it in the stack and then at the end of the parsing return the top
// of the stack, which would possible be the desired reduction
Symbol *startReduction;
startReduction = new Symbol ();
startReduction->state = startState;
symbolStack.push (startReduction);
currentState = startState;
tokenIndex = 0;
delete errorTab;
errorTab = new ErrorTable();
trim = false;
}
/*!
Parse the tokens until it reduces a rule.
/param trimReduction especifies trimming enable or disable. Trimming will
simplify rules of the form: NonTerminal1 := Nonterminal2
/return next reduction or NULL if error or test accepted
/sa getResult (), parse ()
*/
Symbol *LALR::nextReduction (bool trimReductions, bool reportOnlyOneError) {
Action *actObj;
Token *tok;
NonTerminal *newNonTerminal;
Terminal *newTerminal;
integer index;
integer i;
int action, target;
m_trimReductions = trimReductions;
for (;tokenIndex < tokens.size();tokenIndex++) {
// Save this tokens information for the error system.
tok = tokens[tokenIndex];
lastTerminal.symbol = tok->symbol;
lastTerminal.image = tok->image;
lastTerminal.line = tok->line;
lastTerminal.col = tok->col;
// Get next action
actObj = getNextAction (tokens[tokenIndex]->symbolIndex, currentState);
// Test for errors
if (actObj == NULL) {
// Generate ERROR & recover pushing expected symbol in the stack
// RECOVERING IS IN THE TODO LIST!
// FOR THAT WE NEED A MECHANISM TO "ESTIMATE" THE NEXT TOKEN
// Or use Burke-Fisher recovering algorithm
// Create a symbol traceback vector.
vector <Symbol*> traceback;
vector <Symbol*> tmptokvector = symbolStack.get_vector();
for (short k = tmptokvector.size()-1; k >= 0; k--) {
traceback.push_back (tmptokvector[k]);
}
vector <wstring> expectedTokens = getPossibleTokens (currentState);
// Add the error to the Error class.
errorTab->addError (ERROR_PARSE, UNEXPECTED_TOKEN, prevReduction, &lastTerminal,
expectedTokens, traceback,
tokens[tokenIndex]->line,
tokens[tokenIndex]->col);
if (reportOnlyOneError) {
reductionResult = REDUCTION_ERROR;
return NULL;
}
} else {
// Update Global Error recovery system
if (action == ACTION_SHIFT) {
updateBurkeFisher (createTerminal(tokens[tokenIndex]));
}
Symbol *rdc = parseToken (actObj, symbolStack, tokenIndex, currentState);
if (rdc == NULL) {
if (reductionResult != REDUCTION_TOKEN_SHIFT) {
return NULL;
}
} else {
return rdc;
}
/*
action = actObj->action;
target = actObj->target;
if (DEBUG) wprintf (L"Action: %d\n", action);
switch (action) {
// Pushes current token into the stack
case ACTION_SHIFT:
if (DEBUG) {
wprintf (L"Shifting: ");
wprintf (tokens[tokenIndex]->symbol.c_str());
wprintf ( L"\nGo to state:%d\n\n", target);
}
// Push current token on the stack
currentState = target;
currentLine = tokens[tokenIndex]->line;
currentCol = tokens[tokenIndex]->col;
tokens[tokenIndex]->state = currentState;
// Create a terminal symbol and push it on the stack
newTerminal = new Terminal();
tok = tokens[tokenIndex];
newTerminal->symbol = tok->symbol;
newTerminal->image = tok->image;
newTerminal->symbolIndex = tok->symbolIndex;
newTerminal->state = tok->state;
newTerminal->line = tok->line;
newTerminal->col = tok->col;
currentLine = tok->line;
currentCol = tok->col;
symbolStack.push (newTerminal);
// Update Burke-Fisher Queue and Stack
updateBurkeFisher (newTerminal);
break;
// Creates a new reduction. Pops all the terminals and non terminals
// for this rule and pushes the most left non terminal.
case ACTION_REDUCE:
if (DEBUG) {
wprintf (L"Reducing...\n");
}
// Create a new Non Terminal (to represent this reduction)
newNonTerminal = new NonTerminal();
index = ruleTable->rules[target].symbolIndex;
newNonTerminal->symbolIndex = index;
newNonTerminal->symbol = symbolTable->symbols [index].name;
newNonTerminal->ruleIndex = ruleTable->rules[target].ruleIndex;
newNonTerminal->line = currentLine;
newNonTerminal->col = currentCol;
// If the rule has only a nonterminal then we dont create a reduction
// node for this rule in the tree since its not usefull.
// User can decide to simplify this by enabling the trimming
if ((ruleTable->rules[target].symbols.size() == 1) &&
(symbolTable->symbols[ruleTable->rules[target].symbols[0]].kind ==
NON_TERMINAL) && trimReductions) {
trim = true;
newNonTerminal->trimmed = true;
} else {
newNonTerminal->trimmed = false;
trim = false;
}
if (DEBUG) {
wprintf (symbolTable->symbols[ruleTable->rules[target].ruleIndex].name.c_str());
wprintf (L" = ");
}
// pop from the stack the tokens for the reduced rule
// and store them in the reduction
for (i=0; i < ruleTable->rules[target].symbols.size(); i++) {
Symbol *s = symbolStack.top ();
// If the symbol is trimmed we just pick up its children
if (s->trimmed) {
assert (s->type == NON_TERMINAL);
NonTerminal *trimmedNT = (NonTerminal*) s;
assert (trimmedNT->children.size() == 1);
newNonTerminal->children.push_front (trimmedNT->children[0]);
} else {
newNonTerminal->children.push_front (s);
}
symbolStack.pop();
}
if (DEBUG) {
for (i=0; i < ruleTable->rules[target].symbols.size(); i++) {
int symIndex;
if (!trim) {
symIndex = newNonTerminal->children[i]->symbolIndex;
}
wprintf (symbolTable->symbols[symIndex].name.c_str());
wprintf (L" ");
}
wprintf (L"\n");
}
// Perform GOTO
if (DEBUG) {
wprintf (L"state: %d index: %d\n", symbolStack.top()->state,
newNonTerminal->symbolIndex);
}
actObj = getNextAction (newNonTerminal->symbolIndex, symbolStack.top()->state);
if ((actObj != NULL) && (actObj->action == ACTION_GOTO)) {
if (DEBUG) wprintf (L"Go to state: %d\n\n", actObj->target);
currentState = actObj->target;
newNonTerminal->state = currentState;
// Push the reduced nonterminal in the stack
symbolStack.push (newNonTerminal);
updateBurkeFisher (newNonTerminal);
} else {
wprintf (L"Internal Error!!\n");
reductionResult = REDUCTION_ERROR;
return NULL;
}
return newNonTerminal;
break;
// This Action should never happen...
case ACTION_GOTO:
wprintf (L"Goto: %d", target);
currentState = target;
break;
case ACTION_ACCEPT:
reductionResult = REDUCTION_TEXT_ACCEPTED;
if (DEBUG) wprintf (L"text parsed succesfully\n");
return NULL;
break;
}
*/
}
}
reductionResult = REDUCTION_ERROR;
return NULL;
}
/*!
Computes an Action object from the input parameters
/param symbolIndex the index in the symbol table that we want to match
/param index the current state in the LALR state machine
/return Action NULL if no action found for this symbol Index.
*/
Action *LALR::getNextAction (integer symbolIndex, integer index) {
for (integer i=0; i < stateTable->states[index].actions.size(); i++) {
if (stateTable->states[index].actions[i].symbolIndex == symbolIndex) {
return &stateTable->states[index].actions[i];
}
}
return NULL;
}
vector<wstring> LALR::getPossibleTokens (integer index) {
vector<wstring> tokenVector;
for (integer i=0; i < stateTable->states[index].actions.size(); i++) {
integer j = stateTable->states[index].actions[i].symbolIndex;
if (symbolTable->symbols[j].kind == TERMINAL) {
wstring tokenName = symbolTable->symbols[j].name;
tokenVector.push_back (tokenName);
}
}
return tokenVector;
}
/*!
Builds a parse tree with reductions as nodes.
Sets the Error object with the possible compiling errors.
/sa getError(), getNextReduction()
*/
Symbol *LALR::parse (const vector <Token*> &tokens, bool trimReductions,
bool reportOnlyOneError) {
init (tokens);
Symbol *reduction;
prevReduction = NULL;
while (true) {
reduction = nextReduction(trimReductions, reportOnlyOneError);
if ((reduction == NULL) && ((getResult() == REDUCTION_ERROR) ||
(getResult() == REDUCTION_TEXT_ACCEPTED))) {
break;
} else if (reduction) {
prevReduction = reduction;
}
}
if (getResult() == REDUCTION_TEXT_ACCEPTED) {
return prevReduction;
} else {
return NULL;
}
}
int LALR::getResult () {
return reductionResult;
}
ErrorTable *LALR::getErrors() {
return errorTab;
}
void LALR::printReductionTree (Symbol *reduction, int deep) {
integer i;
// print tabs
for (i=0; i < deep; i++) {
wprintf (L" ");
}
if (reduction == NULL) {
wprintf (L"NULL\n");
return;
}
if (reduction->type == NON_TERMINAL) {
wprintf (symbolTable->symbols[reduction->symbolIndex].name.c_str());
wprintf (L"\n");
for (i=0; i < ((NonTerminal*) reduction)->children.size(); i++) {
printReductionTree (((NonTerminal*)reduction)->children[i], deep+1);
}
} else {
wprintf (((Terminal*)reduction)->symbol.c_str());
wprintf (L":");
wprintf (((Terminal*)reduction)->image.c_str());
wprintf (L"\n");
}
}
void LALR::updateBurkeFisher (Symbol *symbol) {
if (errorQueue.size() == nbrBackUpTokens) {
errorStack.push (errorQueue.front());
errorQueue.pop();
}
errorQueue.push (symbol);
}
Symbol *LALR::parseToken (Action *actObj, SymbolStack &theStack, int tokenIndex,
integer ¤tState) {
Token *tok;
NonTerminal *newNonTerminal;
Terminal *newTerminal;
integer index, i;
int action, target;
action = actObj->action;
target = actObj->target;
switch (action) {
/*
Pushes current token into the stack
*/
case ACTION_SHIFT:
// Push current token on the stack
currentState = target;
currentLine = tokens[tokenIndex]->line;
currentCol = tokens[tokenIndex]->col;
tokens[tokenIndex]->state = target;
// Create a terminal symbol and push it onto the stack
newTerminal = createTerminal (tokens[tokenIndex]);
theStack.push (newTerminal);
reductionResult = REDUCTION_TOKEN_SHIFT;
return NULL;
break;
/*
Creates a new reduction. Pops all the terminals and non terminals
for this rule and pushes the most left non terminal.
*/
case ACTION_REDUCE:
// Create a new Non Terminal (to represent this reduction)
index = ruleTable->rules[target].symbolIndex;
newNonTerminal = createNonTerminal (index, target);
// If the rule has only a nonterminal then we dont create a reduction
// node for this rule in the tree since its not usefull.
// User can decide to simplify this by enabling the trimming
if ((ruleTable->rules[target].symbols.size() == 1) &&
(symbolTable->symbols[ruleTable->rules[target].symbols[0]].kind ==
NON_TERMINAL) && m_trimReductions) {
trim = true;
newNonTerminal->trimmed = true;
} else {
newNonTerminal->trimmed = false;
trim = false;
}
// pop from the stack the tokens for the reduced rule
// and store them in the NonTerminal as its sons.
for (i=0; i < ruleTable->rules[target].symbols.size(); i++) {
Symbol *s = theStack.top ();
// If the symbol is trimmed we just pick up its children
if (s->trimmed) {
assert (s->type == NON_TERMINAL);
NonTerminal *trimmedNT = (NonTerminal*) s;
assert (trimmedNT->children.size() == 1);
newNonTerminal->children.push_front (trimmedNT->children[0]);
} else {
newNonTerminal->children.push_front (s);
}
theStack.pop();
}
// Perform GOTO
actObj = getNextAction (newNonTerminal->symbolIndex, theStack.top()->state);
if ((actObj != NULL) && (actObj->action == ACTION_GOTO)) {
currentState = actObj->target;
newNonTerminal->state = currentState;
// Push the reduced nonterminal in the stack
theStack.push (newNonTerminal);
} else {
wprintf (L"Internal Error!!\n");
reductionResult = REDUCTION_ERROR;
return NULL;
}
reductionResult = REDUCTION_COMPLETED;
return newNonTerminal;
break;
// This Action should never happen...
case ACTION_GOTO:
wprintf (L"Goto: %d", target);
currentState = target;
break;
case ACTION_ACCEPT:
reductionResult = REDUCTION_TEXT_ACCEPTED;
return NULL;
break;
}
return NULL;
}
Terminal *LALR::createTerminal (Token *tok) {
Terminal *newTerminal;
newTerminal = new Terminal();
newTerminal->symbol = tok->symbol;
newTerminal->image = tok->image;
newTerminal->symbolIndex = tok->symbolIndex;
newTerminal->state = tok->state;
newTerminal->line = tok->line;
newTerminal->col = tok->col;
return newTerminal;
}
NonTerminal *LALR::createNonTerminal (int index, int target) {
NonTerminal *newNonTerminal;
newNonTerminal = new NonTerminal();
newNonTerminal->symbolIndex = index;
newNonTerminal->symbol = symbolTable->symbols [index].name;
newNonTerminal->ruleIndex = ruleTable->rules[target].ruleIndex;
newNonTerminal->line = currentLine;
newNonTerminal->col = currentCol;
return newNonTerminal;
}
<commit_msg>Removed several warnings.<commit_after>/***************************************************************************
LALR.cpp - description
------------------------
begin : Fri Jun 14 2002
copyright : (C) 2002 by Manuel Astudillo
***************************************************************************/
/***************************************************************************
* *
* This program 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. *
* *
***************************************************************************/
#include <assert.h>
#include "LALR.h"
LALR::LALR (const LALRStateTable *stateTable, const SymbolTable *symbolTable,
const RuleTable *ruleTable, integer startState) {
this->stateTable = stateTable;
this->symbolTable = symbolTable;
this->ruleTable = ruleTable;
this->startState = startState;
errorTab = NULL;
nbrBackUpTokens = 10;
}
LALR::~LALR () {
delete errorTab;
// Clean the stack in case elements are still there
// TODO: Investigate why there are elements in the stack if the parser worked nicely
while (!symbolStack.empty()) {
// delete symbolStack.top();
symbolStack.pop();
}
}
/*!
Initializes the parser.
Call this function before calling buildParseTree()
/sa buildParseTree();
*/
void LALR::init (const vector <Token*> &tokens) {
// Copy the tokens vector (maybe just having a reference to it is enough...)
this->tokens = tokens;
// Initialize stack (And clear it in case there still are elements there)
while (!symbolStack.empty()) {
//delete symbolStack.top();
symbolStack.pop();
}
// Create the start symbol (maybe it is not needed to place it in both stack and reductionList
// Maybe is enough to put it in the stack and then at the end of the parsing return the top
// of the stack, which would possible be the desired reduction
Symbol *startReduction;
startReduction = new Symbol ();
startReduction->state = startState;
symbolStack.push (startReduction);
currentState = startState;
tokenIndex = 0;
delete errorTab;
errorTab = new ErrorTable();
trim = false;
}
/*!
Parse the tokens until it reduces a rule.
/param trimReduction especifies trimming enable or disable. Trimming will
simplify rules of the form: NonTerminal1 := Nonterminal2
/return next reduction or NULL if error or test accepted
/sa getResult (), parse ()
*/
Symbol *LALR::nextReduction (bool trimReductions, bool reportOnlyOneError) {
Action *actObj;
Token *tok;
int action;
m_trimReductions = trimReductions;
for (;tokenIndex < tokens.size();tokenIndex++) {
// Save this tokens information for the error system.
tok = tokens[tokenIndex];
lastTerminal.symbol = tok->symbol;
lastTerminal.image = tok->image;
lastTerminal.line = tok->line;
lastTerminal.col = tok->col;
// Get next action
actObj = getNextAction (tokens[tokenIndex]->symbolIndex, currentState);
// Test for errors
if (actObj == NULL) {
// Generate ERROR & recover pushing expected symbol in the stack
// RECOVERING IS IN THE TODO LIST!
// FOR THAT WE NEED A MECHANISM TO "ESTIMATE" THE NEXT TOKEN
// Or use Burke-Fisher recovering algorithm
// Create a symbol traceback vector.
vector <Symbol*> traceback;
vector <Symbol*> tmptokvector = symbolStack.get_vector();
for (short k = tmptokvector.size()-1; k >= 0; k--) {
traceback.push_back (tmptokvector[k]);
}
vector <wstring> expectedTokens = getPossibleTokens (currentState);
// Add the error to the Error class.
errorTab->addError (ERROR_PARSE, UNEXPECTED_TOKEN, prevReduction, &lastTerminal,
expectedTokens, traceback,
tokens[tokenIndex]->line,
tokens[tokenIndex]->col);
if (reportOnlyOneError) {
reductionResult = REDUCTION_ERROR;
return NULL;
}
} else {
// Update Global Error recovery system
if (action == ACTION_SHIFT) {
updateBurkeFisher (createTerminal(tokens[tokenIndex]));
}
Symbol *rdc = parseToken (actObj, symbolStack, tokenIndex, currentState);
if (rdc == NULL) {
if (reductionResult != REDUCTION_TOKEN_SHIFT) {
return NULL;
}
} else {
return rdc;
}
}
}
reductionResult = REDUCTION_ERROR;
return NULL;
}
/*!
Computes an Action object from the input parameters
/param symbolIndex the index in the symbol table that we want to match
/param index the current state in the LALR state machine
/return Action NULL if no action found for this symbol Index.
*/
Action *LALR::getNextAction (integer symbolIndex, integer index) {
for (integer i=0; i < stateTable->states[index].actions.size(); i++) {
if (stateTable->states[index].actions[i].symbolIndex == symbolIndex) {
return &stateTable->states[index].actions[i];
}
}
return NULL;
}
vector<wstring> LALR::getPossibleTokens (integer index) {
vector<wstring> tokenVector;
for (integer i=0; i < stateTable->states[index].actions.size(); i++) {
integer j = stateTable->states[index].actions[i].symbolIndex;
if (symbolTable->symbols[j].kind == TERMINAL) {
wstring tokenName = symbolTable->symbols[j].name;
tokenVector.push_back (tokenName);
}
}
return tokenVector;
}
/*!
Builds a parse tree with reductions as nodes.
Sets the Error object with the possible compiling errors.
/sa getError(), getNextReduction()
*/
Symbol *LALR::parse (const vector <Token*> &tokens, bool trimReductions,
bool reportOnlyOneError) {
init (tokens);
Symbol *reduction;
prevReduction = NULL;
while (true) {
reduction = nextReduction(trimReductions, reportOnlyOneError);
if ((reduction == NULL) && ((getResult() == REDUCTION_ERROR) ||
(getResult() == REDUCTION_TEXT_ACCEPTED))) {
break;
} else if (reduction) {
prevReduction = reduction;
}
}
if (getResult() == REDUCTION_TEXT_ACCEPTED) {
return prevReduction;
} else {
return NULL;
}
}
int LALR::getResult () {
return reductionResult;
}
ErrorTable *LALR::getErrors() {
return errorTab;
}
void LALR::printReductionTree (Symbol *reduction, int deep) {
integer i;
// print tabs
for (i=0; i < deep; i++) {
wprintf (L" ");
}
if (reduction == NULL) {
wprintf (L"NULL\n");
return;
}
if (reduction->type == NON_TERMINAL) {
wprintf (symbolTable->symbols[reduction->symbolIndex].name.c_str());
wprintf (L"\n");
for (i=0; i < ((NonTerminal*) reduction)->children.size(); i++) {
printReductionTree (((NonTerminal*)reduction)->children[i], deep+1);
}
} else {
wprintf (((Terminal*)reduction)->symbol.c_str());
wprintf (L":");
wprintf (((Terminal*)reduction)->image.c_str());
wprintf (L"\n");
}
}
void LALR::updateBurkeFisher (Symbol *symbol) {
if (errorQueue.size() == nbrBackUpTokens) {
errorStack.push (errorQueue.front());
errorQueue.pop();
}
errorQueue.push (symbol);
}
Symbol *LALR::parseToken (Action *actObj, SymbolStack &theStack, int tokenIndex,
integer ¤tState) {
NonTerminal *newNonTerminal;
Terminal *newTerminal;
integer index, i;
int action, target;
action = actObj->action;
target = actObj->target;
switch (action) {
/*
Pushes current token into the stack
*/
case ACTION_SHIFT:
// Push current token on the stack
currentState = target;
currentLine = tokens[tokenIndex]->line;
currentCol = tokens[tokenIndex]->col;
tokens[tokenIndex]->state = target;
// Create a terminal symbol and push it onto the stack
newTerminal = createTerminal (tokens[tokenIndex]);
theStack.push (newTerminal);
reductionResult = REDUCTION_TOKEN_SHIFT;
return NULL;
break;
/*
Creates a new reduction. Pops all the terminals and non terminals
for this rule and pushes the most left non terminal.
*/
case ACTION_REDUCE:
// Create a new Non Terminal (to represent this reduction)
index = ruleTable->rules[target].symbolIndex;
newNonTerminal = createNonTerminal (index, target);
// If the rule has only a nonterminal then we dont create a reduction
// node for this rule in the tree since its not usefull.
// User can decide to simplify this by enabling the trimming
if ((ruleTable->rules[target].symbols.size() == 1) &&
(symbolTable->symbols[ruleTable->rules[target].symbols[0]].kind ==
NON_TERMINAL) && m_trimReductions) {
trim = true;
newNonTerminal->trimmed = true;
} else {
newNonTerminal->trimmed = false;
trim = false;
}
// pop from the stack the tokens for the reduced rule
// and store them in the NonTerminal as its sons.
for (i=0; i < ruleTable->rules[target].symbols.size(); i++) {
Symbol *s = theStack.top ();
// If the symbol is trimmed we just pick up its children
if (s->trimmed) {
assert (s->type == NON_TERMINAL);
NonTerminal *trimmedNT = (NonTerminal*) s;
assert (trimmedNT->children.size() == 1);
newNonTerminal->children.push_front (trimmedNT->children[0]);
} else {
newNonTerminal->children.push_front (s);
}
theStack.pop();
}
// Perform GOTO
actObj = getNextAction (newNonTerminal->symbolIndex, theStack.top()->state);
if ((actObj != NULL) && (actObj->action == ACTION_GOTO)) {
currentState = actObj->target;
newNonTerminal->state = currentState;
// Push the reduced nonterminal in the stack
theStack.push (newNonTerminal);
} else {
wprintf (L"Internal Error!!\n");
reductionResult = REDUCTION_ERROR;
return NULL;
}
reductionResult = REDUCTION_COMPLETED;
return newNonTerminal;
break;
// This Action should never happen...
case ACTION_GOTO:
wprintf (L"Goto: %d", target);
currentState = target;
break;
case ACTION_ACCEPT:
reductionResult = REDUCTION_TEXT_ACCEPTED;
return NULL;
break;
}
return NULL;
}
Terminal *LALR::createTerminal (Token *tok) {
Terminal *newTerminal;
newTerminal = new Terminal();
newTerminal->symbol = tok->symbol;
newTerminal->image = tok->image;
newTerminal->symbolIndex = tok->symbolIndex;
newTerminal->state = tok->state;
newTerminal->line = tok->line;
newTerminal->col = tok->col;
return newTerminal;
}
NonTerminal *LALR::createNonTerminal (int index, int target) {
NonTerminal *newNonTerminal;
newNonTerminal = new NonTerminal();
newNonTerminal->symbolIndex = index;
newNonTerminal->symbol = symbolTable->symbols [index].name;
newNonTerminal->ruleIndex = ruleTable->rules[target].ruleIndex;
newNonTerminal->line = currentLine;
newNonTerminal->col = currentCol;
return newNonTerminal;
}
<|endoftext|> |
<commit_before>#include "Compiler.h"
#include <fstream>
#include <cstring>
using namespace std;
using namespace compiler;
void print_help(char *program_name)
{
cout << "Usage: " << program_name << " [options] <inputs>" << endl;
cout << "Options:" << endl;
cout << " --help -h Show available options" << endl << endl;
cout << " --output -o <file> Set binary output file" << endl;
cout << " --header-output -ho <file> Set header output file" << endl << endl;
#ifdef CCPP
cout << " --cpp C++ backend" << endl;
cout << " --cpar Parallel C backend" << endl;
#endif
#ifdef CGNUASM
cout << " --gnuasm GNU Assembly backend" << endl;
#endif
#ifdef CHASKELL
cout << " --haskell Haskell backend" << endl;
#endif
#ifdef CLLVM
cout << " --llvm LLVM backend" << endl;
#endif
cout << " --pprinter Pretty printer backend" << endl;
}
int main(int argc, char *argv[])
{
Backend BE = Backend::PPRINTER;
vector<string> Inputs;
string Output("a.out");
string HeaderOutput("a.h");
if (argc == 1) {
print_help(argv[0]);
return 0;
}
for (int i = 1; i < argc; ++i) {
string Arg = string(argv[i]);
if (Arg.compare("--help") == 0 || Arg.compare("-h") == 0) {
print_help(argv[0]);
return 0;
}
#ifdef CCPP
else if (Arg.compare("--cpp") == 0)
BE = Backend::CPP;
else if (Arg.compare("--cpar") == 0)
BE = Backend::CPAR;
else if (Arg.compare("--c") == 0)
BE = Backend::CPAR;
#endif
#endif
#ifdef CGNUASM
else if (Arg.compare("--gnuasm") == 0)
backend = Backend::GNUASM;
#endif
#ifdef CHASKELL
else if (Arg.compare("--haskell") == 0)
backend = Backend::GNUASM;
#endif
#ifdef CLLVM
else if (Arg.compare("--llvm") == 0)
BE = Backend::LLVM;
#endif
else if (Arg.compare("--pprinter") == 0)
BE = Backend::PPRINTER;
else if (Arg.compare("--output") == 0 || Arg.compare("-o") == 0)
if (i < argc - 1)
Output = argv[++i];
else {
cerr << "No output file specified" << endl;
return 2;
}
else if (Arg.compare("--header-output") == 0 || Arg.compare("-ho") == 0)
if (i < argc - 1)
HeaderOutput = argv[++i];
else {
cerr << "No output header specified" << endl;
return 3;
}
else if (Arg.compare(0, 2, "--") == 0) {
cerr << "No such option: " << Arg << endl;
cerr << "For help use --help" << endl;
return 4;
}
else {
Inputs.push_back(Arg);
}
}
if (Inputs.size() == 0)
{
cerr << "No input files" << endl;
return 1;
}
Compiler compiler;
compiler.setOutput(Output);
compiler.setHeaderOutput(HeaderOutput);
compiler.setBackend(BE);
return compiler.compile(Inputs);
}
<commit_msg>sc: fix compile<commit_after>#include "Compiler.h"
#include <fstream>
#include <cstring>
using namespace std;
using namespace compiler;
void print_help(char *program_name)
{
cout << "Usage: " << program_name << " [options] <inputs>" << endl;
cout << "Options:" << endl;
cout << " --help -h Show available options" << endl << endl;
cout << " --output -o <file> Set binary output file" << endl;
cout << " --header-output -ho <file> Set header output file" << endl << endl;
#ifdef CCPP
cout << " --cpp C++ backend" << endl;
cout << " --cpar Parallel C backend" << endl;
#endif
#ifdef CGNUASM
cout << " --gnuasm GNU Assembly backend" << endl;
#endif
#ifdef CHASKELL
cout << " --haskell Haskell backend" << endl;
#endif
#ifdef CLLVM
cout << " --llvm LLVM backend" << endl;
#endif
cout << " --pprinter Pretty printer backend" << endl;
}
int main(int argc, char *argv[])
{
Backend BE = Backend::PPRINTER;
vector<string> Inputs;
string Output("a.out");
string HeaderOutput("a.h");
if (argc == 1) {
print_help(argv[0]);
return 0;
}
for (int i = 1; i < argc; ++i) {
string Arg = string(argv[i]);
if (Arg.compare("--help") == 0 || Arg.compare("-h") == 0) {
print_help(argv[0]);
return 0;
}
#ifdef CCPP
else if (Arg.compare("--cpp") == 0)
BE = Backend::CPP;
else if (Arg.compare("--cpar") == 0)
BE = Backend::CPAR;
else if (Arg.compare("--c") == 0)
BE = Backend::CPAR;
#endif
#ifdef CGNUASM
else if (Arg.compare("--gnuasm") == 0)
backend = Backend::GNUASM;
#endif
#ifdef CHASKELL
else if (Arg.compare("--haskell") == 0)
backend = Backend::GNUASM;
#endif
#ifdef CLLVM
else if (Arg.compare("--llvm") == 0)
BE = Backend::LLVM;
#endif
else if (Arg.compare("--pprinter") == 0)
BE = Backend::PPRINTER;
else if (Arg.compare("--output") == 0 || Arg.compare("-o") == 0)
if (i < argc - 1)
Output = argv[++i];
else {
cerr << "No output file specified" << endl;
return 2;
}
else if (Arg.compare("--header-output") == 0 || Arg.compare("-ho") == 0)
if (i < argc - 1)
HeaderOutput = argv[++i];
else {
cerr << "No output header specified" << endl;
return 3;
}
else if (Arg.compare(0, 2, "--") == 0) {
cerr << "No such option: " << Arg << endl;
cerr << "For help use --help" << endl;
return 4;
}
else {
Inputs.push_back(Arg);
}
}
if (Inputs.size() == 0)
{
cerr << "No input files" << endl;
return 1;
}
Compiler compiler;
compiler.setOutput(Output);
compiler.setHeaderOutput(HeaderOutput);
compiler.setBackend(BE);
return compiler.compile(Inputs);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.